diff --git a/.gitea/issue_template/bug.md b/.gitea/issue_template/bug.md index 752ebbdb..550b2f82 100644 --- a/.gitea/issue_template/bug.md +++ b/.gitea/issue_template/bug.md @@ -36,6 +36,5 @@ Android version: -[ ] - I read -the [contributing page](https://codeberg.org/tom79/Fedilab/src/branch/main/CONTRIBUTING.md) +- [ ] I read the [contributing page](https://codeberg.org/tom79/Fedilab/src/branch/main/CONTRIBUTING.md) diff --git a/.gitea/issue_template/feature.md b/.gitea/issue_template/feature.md index 7239177c..17afaa78 100644 --- a/.gitea/issue_template/feature.md +++ b/.gitea/issue_template/feature.md @@ -22,5 +22,4 @@ labels: -[ ] - I read -the [contributing page](https://codeberg.org/tom79/Fedilab/src/branch/main/CONTRIBUTING.md) \ No newline at end of file +- [ ] I read the [contributing page](https://codeberg.org/tom79/Fedilab/src/branch/main/CONTRIBUTING.md) diff --git a/app/build.gradle b/app/build.gradle index fb85bb8b..5d2cc468 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -13,8 +13,8 @@ android { defaultConfig { minSdk 21 targetSdk 34 - versionCode 505 - versionName "3.26.0" + versionCode 510 + versionName "3.27.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } flavorDimensions "default" diff --git a/app/src/main/assets/release_notes/notes.json b/app/src/main/assets/release_notes/notes.json index f9fbcfdb..52f71e62 100644 --- a/app/src/main/assets/release_notes/notes.json +++ b/app/src/main/assets/release_notes/notes.json @@ -1,4 +1,9 @@ [ + { + "version": "3.27.0", + "code": "510", + "note": "Added:\n- Fixed top bar (default: disabled)\n- Usage frequency of tags when composing\n\nChanged:\n- Markdown support disabled by default\n\nFixed:\n- Fix crashes during interactions or when opening a new screen\n- Fix color of dialogs in Settings\n- Some minor crashes" + }, { "version": "3.26.0", "code": "505", diff --git a/app/src/main/java/app/fedilab/android/BaseMainActivity.java b/app/src/main/java/app/fedilab/android/BaseMainActivity.java index 850de4de..9b5af2da 100644 --- a/app/src/main/java/app/fedilab/android/BaseMainActivity.java +++ b/app/src/main/java/app/fedilab/android/BaseMainActivity.java @@ -36,7 +36,6 @@ import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; -import android.content.res.Configuration; import android.database.MatrixCursor; import android.graphics.PorterDuff; import android.graphics.drawable.BitmapDrawable; @@ -72,8 +71,8 @@ import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.PopupMenu; import androidx.appcompat.widget.SearchView; +import androidx.appcompat.widget.Toolbar; import androidx.core.app.ActivityCompat; -import androidx.core.app.ActivityOptionsCompat; import androidx.core.content.ContextCompat; import androidx.core.view.GravityCompat; import androidx.cursoradapter.widget.CursorAdapter; @@ -81,7 +80,7 @@ import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import androidx.lifecycle.ViewModelProvider; - +import androidx.multidex.BuildConfig; import androidx.navigation.NavController; import androidx.navigation.Navigation; import androidx.navigation.ui.AppBarConfiguration; @@ -99,6 +98,7 @@ import com.bumptech.glide.request.RequestOptions; import com.bumptech.glide.request.target.CustomTarget; import com.bumptech.glide.request.target.Target; import com.bumptech.glide.request.transition.Transition; +import com.google.android.material.appbar.AppBarLayout; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.navigation.NavigationView; @@ -163,6 +163,7 @@ import app.fedilab.android.mastodon.client.entities.api.Tag; import app.fedilab.android.mastodon.client.entities.app.Account; import app.fedilab.android.mastodon.client.entities.app.BaseAccount; import app.fedilab.android.mastodon.client.entities.app.BottomMenu; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.client.entities.app.MutedAccounts; import app.fedilab.android.mastodon.client.entities.app.Pinned; import app.fedilab.android.mastodon.client.entities.app.PinnedTimeline; @@ -222,24 +223,34 @@ public abstract class BaseMainActivity extends BaseActivity implements NetworkSt private final BroadcastReceiver broadcast_error_message = new BroadcastReceiver() { @Override public void onReceive(android.content.Context context, Intent intent) { - Bundle b = intent.getExtras(); - if (b != null) { - if (b.getBoolean(Helper.RECEIVE_COMPOSE_ERROR_MESSAGE, false)) { - String errorMessage = b.getString(Helper.RECEIVE_ERROR_MESSAGE); - StatusDraft statusDraft = (StatusDraft) b.getSerializable(Helper.ARG_STATUS_DRAFT); - Snackbar snackbar = Snackbar.make(binding.getRoot(), errorMessage, 5000); - View snackbarView = snackbar.getView(); - TextView textView = snackbarView.findViewById(com.google.android.material.R.id.snackbar_text); - textView.setMaxLines(5); - snackbar - .setAction(getString(R.string.open_draft), view -> { - Intent intentCompose = new Intent(context, ComposeActivity.class); - intentCompose.putExtra(Helper.ARG_STATUS_DRAFT, statusDraft); - intentCompose.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(intentCompose); - }) - .show(); - } + Bundle args = intent.getExtras(); + if (args != null) { + long bundleId = args.getLong(Helper.ARG_INTENT_ID, -1); + new CachedBundle(BaseMainActivity.this).getBundle(bundleId, currentAccount, bundle -> { + if (bundle.getBoolean(Helper.RECEIVE_COMPOSE_ERROR_MESSAGE, false)) { + String errorMessage = bundle.getString(Helper.RECEIVE_ERROR_MESSAGE); + StatusDraft statusDraft = (StatusDraft) bundle.getSerializable(Helper.ARG_STATUS_DRAFT); + Snackbar snackbar = Snackbar.make(binding.getRoot(), errorMessage, 5000); + View snackbarView = snackbar.getView(); + TextView textView = snackbarView.findViewById(com.google.android.material.R.id.snackbar_text); + textView.setMaxLines(5); + snackbar + .setAction(getString(R.string.open_draft), view -> { + Intent intentCompose = new Intent(context, ComposeActivity.class); + Bundle args2 = new Bundle(); + args2.putSerializable(Helper.ARG_STATUS_DRAFT, statusDraft); + new CachedBundle(BaseMainActivity.this).insertBundle(args2, currentAccount, bundleId2 -> { + Bundle bundle2 = new Bundle(); + bundle2.putLong(Helper.ARG_INTENT_ID, bundleId2); + intentCompose.putExtras(bundle2); + intentCompose.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(intentCompose); + }); + }) + .show(); + } + }); + } } }; @@ -248,88 +259,97 @@ public abstract class BaseMainActivity extends BaseActivity implements NetworkSt private final BroadcastReceiver broadcast_data = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { - Bundle b = intent.getExtras(); - if (b != null) { - if (b.getBoolean(Helper.RECEIVE_REDRAW_TOPBAR, false)) { - List mastodonLists = (List) b.getSerializable(Helper.RECEIVE_MASTODON_LIST); - redrawPinned(mastodonLists); - } - if (b.getBoolean(Helper.RECEIVE_REDRAW_BOTTOM, false)) { - bottomMenu = new BottomMenu(BaseMainActivity.this).hydrate(currentAccount, binding.bottomNavView); - if (bottomMenu != null) { - //ManageClick on bottom menu items - if (binding.bottomNavView.findViewById(R.id.nav_home) != null) { - binding.bottomNavView.findViewById(R.id.nav_home).setOnLongClickListener(view -> { - int position = BottomMenu.getPosition(bottomMenu, R.id.nav_home); - if (position >= 0) { - manageFilters(position); - } - return false; - }); - } - if (binding.bottomNavView.findViewById(R.id.nav_local) != null) { - binding.bottomNavView.findViewById(R.id.nav_local).setOnLongClickListener(view -> { - int position = BottomMenu.getPosition(bottomMenu, R.id.nav_local); + Bundle args = intent.getExtras(); + if (args != null) { + long bundleId = args.getLong(Helper.ARG_INTENT_ID, -1); + new CachedBundle(BaseMainActivity.this).getBundle(bundleId, currentAccount, bundle -> { + if (bundle.getBoolean(Helper.RECEIVE_REDRAW_TOPBAR, false)) { + List mastodonLists = (List) bundle.getSerializable(Helper.RECEIVE_MASTODON_LIST); + redrawPinned(mastodonLists); + } + if (bundle.getBoolean(Helper.RECEIVE_REDRAW_BOTTOM, false)) { + bottomMenu = new BottomMenu(BaseMainActivity.this).hydrate(currentAccount, binding.bottomNavView); + if (bottomMenu != null) { + //ManageClick on bottom menu items + if (binding.bottomNavView.findViewById(R.id.nav_home) != null) { + binding.bottomNavView.findViewById(R.id.nav_home).setOnLongClickListener(view -> { + int position = BottomMenu.getPosition(bottomMenu, R.id.nav_home); + if (position >= 0) { + manageFilters(position); + } + return false; + }); + } + if (binding.bottomNavView.findViewById(R.id.nav_local) != null) { + binding.bottomNavView.findViewById(R.id.nav_local).setOnLongClickListener(view -> { + int position = BottomMenu.getPosition(bottomMenu, R.id.nav_local); + if (position >= 0) { + manageFilters(position); + } + return false; + }); + } + if (binding.bottomNavView.findViewById(R.id.nav_public) != null) { + binding.bottomNavView.findViewById(R.id.nav_public).setOnLongClickListener(view -> { + int position = BottomMenu.getPosition(bottomMenu, R.id.nav_public); + if (position >= 0) { + manageFilters(position); + } + return false; + }); + } + binding.bottomNavView.setOnItemSelectedListener(item -> { + int itemId = item.getItemId(); + int position = BottomMenu.getPosition(bottomMenu, itemId); if (position >= 0) { - manageFilters(position); + if (binding.viewPager.getCurrentItem() == position) { + scrollToTop(); + } else { + binding.viewPager.setCurrentItem(position, false); + } } - return false; + return true; }); } - if (binding.bottomNavView.findViewById(R.id.nav_public) != null) { - binding.bottomNavView.findViewById(R.id.nav_public).setOnLongClickListener(view -> { - int position = BottomMenu.getPosition(bottomMenu, R.id.nav_public); - if (position >= 0) { - manageFilters(position); + } else if (bundle.getBoolean(Helper.RECEIVE_RECREATE_ACTIVITY, false)) { + recreate(); + } else if (bundle.getBoolean(Helper.RECEIVE_NEW_MESSAGE, false)) { + Status statusSent = (Status) bundle.getSerializable(Helper.RECEIVE_STATUS_ACTION); + String statusEditId = bundle.getString(Helper.ARG_EDIT_STATUS_ID, null); + Snackbar.make(binding.displaySnackBar, getString(R.string.message_has_been_sent), Snackbar.LENGTH_LONG) + .setAction(getString(R.string.display), view -> { + Intent intentContext = new Intent(BaseMainActivity.this, ContextActivity.class); + Bundle args2 = new Bundle(); + args2.putSerializable(Helper.ARG_STATUS, statusSent); + new CachedBundle(BaseMainActivity.this).insertBundle(args2, currentAccount, bundleId2 -> { + Bundle bundle2 = new Bundle(); + bundle2.putLong(Helper.ARG_INTENT_ID, bundleId2); + intentContext.putExtras(bundle2); + intentContext.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(intentContext); + }); + }) + .show(); + //The message was edited, we need to update the timeline + if (statusEditId != null) { + //Update message in cache + new Thread(() -> { + StatusCache statusCache = new StatusCache(); + statusCache.instance = BaseMainActivity.currentInstance; + statusCache.user_id = BaseMainActivity.currentUserID; + statusCache.status = statusSent; + statusCache.status_id = statusEditId; + try { + new StatusCache(BaseMainActivity.this).updateIfExists(statusCache); + } catch (DBException e) { + e.printStackTrace(); } - return false; - }); + }).start(); + //Update timelines + sendAction(context, Helper.ARG_STATUS_UPDATED, statusSent, null); } - binding.bottomNavView.setOnItemSelectedListener(item -> { - int itemId = item.getItemId(); - int position = BottomMenu.getPosition(bottomMenu, itemId); - if (position >= 0) { - if (binding.viewPager.getCurrentItem() == position) { - scrollToTop(); - } else { - binding.viewPager.setCurrentItem(position, false); - } - } - return true; - }); } - } else if (b.getBoolean(Helper.RECEIVE_RECREATE_ACTIVITY, false)) { - recreate(); - } else if (b.getBoolean(Helper.RECEIVE_NEW_MESSAGE, false)) { - Status statusSent = (Status) b.getSerializable(Helper.RECEIVE_STATUS_ACTION); - String statusEditId = b.getString(Helper.ARG_EDIT_STATUS_ID, null); - Snackbar.make(binding.displaySnackBar, getString(R.string.message_has_been_sent), Snackbar.LENGTH_LONG) - .setAction(getString(R.string.display), view -> { - Intent intentContext = new Intent(BaseMainActivity.this, ContextActivity.class); - intentContext.putExtra(Helper.ARG_STATUS, statusSent); - intentContext.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intentContext); - }) - .show(); - //The message was edited, we need to update the timeline - if (statusEditId != null) { - //Update message in cache - new Thread(() -> { - StatusCache statusCache = new StatusCache(); - statusCache.instance = BaseMainActivity.currentInstance; - statusCache.user_id = BaseMainActivity.currentUserID; - statusCache.status = statusSent; - statusCache.status_id = statusEditId; - try { - new StatusCache(BaseMainActivity.this).updateIfExists(statusCache); - } catch (DBException e) { - e.printStackTrace(); - } - }).start(); - //Update timelines - sendAction(context, Helper.ARG_STATUS_UPDATED, statusSent, null); - } - } + }); } } }; @@ -359,6 +379,7 @@ public abstract class BaseMainActivity extends BaseActivity implements NetworkSt //Delete cache older than 7 days new StatusCache(activity).deleteForAllAccountAfter7Days(); new TimelineCacheLogs(activity).deleteForAllAccountAfter7Days(); + new CachedBundle(activity).deleteOldIntent(); } catch (DBException e) { e.printStackTrace(); } @@ -659,16 +680,26 @@ public abstract class BaseMainActivity extends BaseActivity implements NetworkSt Status status = (Status) bundle.getSerializable(Helper.INTENT_TARGETED_STATUS); if (account != null) { Intent intentAccount = new Intent(activity, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, account); - intentAccount.putExtras(b); - intentAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - activity.startActivity(intentAccount); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, account); + new CachedBundle(activity).insertBundle(args, currentAccount, bundleId -> { + Bundle bundleCached = new Bundle(); + bundleCached.putLong(Helper.ARG_INTENT_ID, bundleId); + intentAccount.putExtras(bundleCached); + intentAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + activity.startActivity(intentAccount); + }); } else if (status != null) { Intent intentContext = new Intent(activity, ContextActivity.class); - intentContext.putExtra(Helper.ARG_STATUS, status); - intentContext.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - activity.startActivity(intentContext); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS, status); + new CachedBundle(activity).insertBundle(args, currentAccount, bundleId -> { + Bundle bundleCached = new Bundle(); + bundleCached.putLong(Helper.ARG_INTENT_ID, bundleId); + intentContext.putExtras(bundleCached); + intentContext.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + activity.startActivity(intentContext); + }); } } final Handler handler = new Handler(); @@ -693,12 +724,17 @@ public abstract class BaseMainActivity extends BaseActivity implements NetworkSt } viewPager.setCurrentItem(position); } - Bundle b = new Bundle(); - b.putBoolean(ARG_REFRESH_NOTFICATION, true); + Bundle args = new Bundle(); + args.putBoolean(ARG_REFRESH_NOTFICATION, true); Intent intentBC = new Intent(Helper.RECEIVE_STATUS_ACTION); intentBC.setPackage(BuildConfig.APPLICATION_ID); - intentBC.putExtras(b); - activity.sendBroadcast(intentBC); + new CachedBundle(activity).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intentBC.putExtras(bundle); + activity.sendBroadcast(intentBC); + }); + } }, 1000); intent.removeExtra(Helper.INTENT_ACTION); @@ -774,9 +810,15 @@ public abstract class BaseMainActivity extends BaseActivity implements NetworkSt public void federatedStatus(Status status) { if (status != null) { Intent intent = new Intent(activity, ContextActivity.class); - intent.putExtra(Helper.ARG_STATUS, status); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - activity.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS, status); + new CachedBundle(activity).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + activity.startActivity(intent); + }); } } @@ -1013,9 +1055,15 @@ public abstract class BaseMainActivity extends BaseActivity implements NetworkSt public void federatedStatus(Status status) { if (status != null) { Intent intent = new Intent(activity, ContextActivity.class); - intent.putExtra(Helper.ARG_STATUS, status); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - activity.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS, status); + new CachedBundle(activity).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + activity.startActivity(intent); + }); } else { Toasty.error(activity, activity.getString(R.string.toast_error), Toasty.LENGTH_SHORT).show(); } @@ -1035,11 +1083,15 @@ public abstract class BaseMainActivity extends BaseActivity implements NetworkSt public void federatedAccount(app.fedilab.android.mastodon.client.entities.api.Account account) { if (account != null) { Intent intent = new Intent(activity, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, account); - intent.putExtras(b); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - activity.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, account); + new CachedBundle(activity).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + activity.startActivity(intent); + }); } else { Toasty.error(activity, activity.getString(R.string.toast_error), Toasty.LENGTH_SHORT).show(); } @@ -1327,6 +1379,7 @@ public abstract class BaseMainActivity extends BaseActivity implements NetworkSt if (actionBar != null) { actionBar.setDisplayShowTitleEnabled(false); } + manageTopBarScrolling(binding.toolbar); rateThisApp(); binding.compose.setOnClickListener(v -> startActivity(new Intent(this, ComposeActivity.class))); @@ -1418,10 +1471,15 @@ public abstract class BaseMainActivity extends BaseActivity implements NetworkSt headerMainBinding.instanceInfo.setOnClickListener(v -> (new InstanceHealthActivity()).show(getSupportFragmentManager(), null)); headerMainBinding.accountProfilePicture.setOnClickListener(v -> { Intent intent = new Intent(BaseMainActivity.this, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, currentAccount.mastodon_account); - intent.putExtras(b); - startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, currentAccount.mastodon_account); + new CachedBundle(BaseMainActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + startActivity(intent); + }); + }); headerMainBinding.accountAcc.setOnClickListener(v -> headerMainBinding.changeAccount.callOnClick()); @@ -1545,6 +1603,23 @@ public abstract class BaseMainActivity extends BaseActivity implements NetworkSt fetchRecentAccounts(BaseMainActivity.this, headerMainBinding); } + private void manageTopBarScrolling(Toolbar toolbar) { + final SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this); + final boolean topBarScrolling = !sharedpreferences.getBoolean(getString(R.string.SET_DISABLE_TOPBAR_SCROLLING), false); + + final AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams(); + + int scrollFlags = toolbarLayoutParams.getScrollFlags(); + + if (topBarScrolling) { + scrollFlags |= AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL; + + } else { + scrollFlags &= ~AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL; + } + toolbarLayoutParams.setScrollFlags(scrollFlags); + } + private void manageFilters(int position) { View view = binding.bottomNavView.findViewById(R.id.nav_home); boolean showExtendedFilter = true; @@ -1605,8 +1680,7 @@ public abstract class BaseMainActivity extends BaseActivity implements NetworkSt if (binding.viewPager.getAdapter() != null) { int tabPosition = binding.tabLayout.getSelectedTabPosition(); Fragment fragment = (Fragment) binding.viewPager.getAdapter().instantiateItem(binding.viewPager, Math.max(tabPosition, 0)); - if (fragment instanceof FragmentMastodonTimeline && fragment.isVisible()) { - FragmentMastodonTimeline fragmentMastodonTimeline = ((FragmentMastodonTimeline) fragment); + if (fragment instanceof FragmentMastodonTimeline fragmentMastodonTimeline && fragment.isVisible()) { fragmentMastodonTimeline.refreshAllAdapters(); } } @@ -1901,14 +1975,11 @@ public abstract class BaseMainActivity extends BaseActivity implements NetworkSt int position = binding.tabLayout.getSelectedTabPosition(); if (binding.viewPager.getAdapter() != null) { Fragment fragment = (Fragment) binding.viewPager.getAdapter().instantiateItem(binding.viewPager, Math.max(position, 0)); - if (fragment instanceof FragmentMastodonTimeline) { - FragmentMastodonTimeline fragmentMastodonTimeline = ((FragmentMastodonTimeline) fragment); + if (fragment instanceof FragmentMastodonTimeline fragmentMastodonTimeline) { fragmentMastodonTimeline.scrollToTop(); - } else if (fragment instanceof FragmentMastodonConversation) { - FragmentMastodonConversation fragmentMastodonConversation = ((FragmentMastodonConversation) fragment); + } else if (fragment instanceof FragmentMastodonConversation fragmentMastodonConversation) { fragmentMastodonConversation.scrollToTop(); - } else if (fragment instanceof FragmentNotificationContainer) { - FragmentNotificationContainer fragmentNotificationContainer = ((FragmentNotificationContainer) fragment); + } else if (fragment instanceof FragmentNotificationContainer fragmentNotificationContainer) { fragmentNotificationContainer.scrollToTop(); } } diff --git a/app/src/main/java/app/fedilab/android/activities/AboutActivity.java b/app/src/main/java/app/fedilab/android/activities/AboutActivity.java index 209351fc..7e7841f5 100644 --- a/app/src/main/java/app/fedilab/android/activities/AboutActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/AboutActivity.java @@ -15,6 +15,8 @@ package app.fedilab.android.activities; * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; + import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; @@ -26,7 +28,6 @@ import android.view.MenuItem; import android.view.View; import android.widget.Toast; -import androidx.core.app.ActivityOptionsCompat; import androidx.lifecycle.ViewModelProvider; import java.util.ArrayList; @@ -40,6 +41,7 @@ import app.fedilab.android.mastodon.activities.BaseBarActivity; import app.fedilab.android.mastodon.activities.ProfileActivity; import app.fedilab.android.mastodon.client.entities.api.Account; import app.fedilab.android.mastodon.client.entities.api.Status; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.helper.CrossActionHelper; import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.helper.MastodonHelper; @@ -84,10 +86,10 @@ public class AboutActivity extends BaseBarActivity { String finalVersion = version; - binding.aboutVersionCopy.setOnClickListener(v->{ + binding.aboutVersionCopy.setOnClickListener(v -> { ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); - String content = "Fedilab v" + finalVersion + " for " + (BuildConfig.DONATIONS?"FDroid":"Google"); + String content = "Fedilab v" + finalVersion + " for " + (BuildConfig.DONATIONS ? "FDroid" : "Google"); ClipData clip = ClipData.newPlainText(Helper.CLIP_BOARD, content); if (clipboard != null) { @@ -119,10 +121,14 @@ public class AboutActivity extends BaseBarActivity { binding.accountUn.setText(account.acct); binding.accountPp.setOnClickListener(v -> { Intent intent = new Intent(AboutActivity.this, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, account); - intent.putExtras(b); - startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, account); + new CachedBundle(AboutActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + startActivity(intent); + }); }); AccountsVM accountsVM = new ViewModelProvider(AboutActivity.this).get(AccountsVM.class); List ids = new ArrayList<>(); diff --git a/app/src/main/java/app/fedilab/android/mastodon/activities/AccountReportActivity.java b/app/src/main/java/app/fedilab/android/mastodon/activities/AccountReportActivity.java index 8a1b2b08..84c454ba 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/activities/AccountReportActivity.java +++ b/app/src/main/java/app/fedilab/android/mastodon/activities/AccountReportActivity.java @@ -15,6 +15,8 @@ package app.fedilab.android.mastodon.activities; * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; + import android.app.Activity; import android.graphics.PorterDuff; import android.os.Bundle; @@ -35,6 +37,7 @@ import app.fedilab.android.databinding.ActivityAdminReportBinding; import app.fedilab.android.mastodon.client.entities.api.Status; import app.fedilab.android.mastodon.client.entities.api.admin.AdminAccount; import app.fedilab.android.mastodon.client.entities.api.admin.AdminReport; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.helper.ThemeHelper; import app.fedilab.android.mastodon.ui.drawer.StatusReportAdapter; @@ -48,6 +51,7 @@ public class AccountReportActivity extends BaseBarActivity { private AdminReport report; private ActivityAdminReportBinding binding; private AdminVM adminVM; + private AdminAccount targeted_account; @Override protected void onCreate(Bundle savedInstanceState) { @@ -61,12 +65,22 @@ public class AccountReportActivity extends BaseBarActivity { } report = null; - AdminAccount targeted_account = null; - Bundle b = getIntent().getExtras(); - if (b != null) { - account_id = b.getString(Helper.ARG_ACCOUNT_ID, null); - targeted_account = (AdminAccount) b.getSerializable(Helper.ARG_ACCOUNT); - report = (AdminReport) b.getSerializable(Helper.ARG_REPORT); + targeted_account = null; + Bundle args = getIntent().getExtras(); + if (args != null) { + long bundleId = args.getLong(Helper.ARG_INTENT_ID, -1); + new CachedBundle(AccountReportActivity.this).getBundle(bundleId, currentAccount, this::initializeAfterBundle); + } else { + initializeAfterBundle(null); + } + } + + private void initializeAfterBundle(Bundle bundle) { + + if (bundle != null) { + account_id = bundle.getString(Helper.ARG_ACCOUNT_ID, null); + targeted_account = (AdminAccount) bundle.getSerializable(Helper.ARG_ACCOUNT); + report = (AdminReport) bundle.getSerializable(Helper.ARG_REPORT); } binding.allow.getBackground().setColorFilter(ThemeHelper.getAttColor(this, R.attr.colorPrimary), PorterDuff.Mode.MULTIPLY); @@ -103,7 +117,6 @@ public class AccountReportActivity extends BaseBarActivity { account_id = targeted_account.username; } - } private void fillReport(AdminAccount accountAdmin, actionType type) { diff --git a/app/src/main/java/app/fedilab/android/mastodon/activities/ActionActivity.java b/app/src/main/java/app/fedilab/android/mastodon/activities/ActionActivity.java index a943e6dd..d3c89017 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/activities/ActionActivity.java +++ b/app/src/main/java/app/fedilab/android/mastodon/activities/ActionActivity.java @@ -100,24 +100,12 @@ public class ActionActivity extends BaseBarActivity { } switch (type) { - case MUTED_TIMELINE: - setTitle(R.string.muted_menu); - break; - case FAVOURITE_TIMELINE: - setTitle(R.string.favourite); - break; - case BLOCKED_TIMELINE: - setTitle(R.string.blocked_menu); - break; - case BOOKMARK_TIMELINE: - setTitle(R.string.bookmarks); - break; - case BLOCKED_DOMAIN_TIMELINE: - setTitle(R.string.blocked_domains); - break; - case MUTED_TIMELINE_HOME: - setTitle(R.string.muted_menu_home); - break; + case MUTED_TIMELINE -> setTitle(R.string.muted_menu); + case FAVOURITE_TIMELINE -> setTitle(R.string.favourite); + case BLOCKED_TIMELINE -> setTitle(R.string.blocked_menu); + case BOOKMARK_TIMELINE -> setTitle(R.string.bookmarks); + case BLOCKED_DOMAIN_TIMELINE -> setTitle(R.string.blocked_domains); + case MUTED_TIMELINE_HOME -> setTitle(R.string.muted_menu_home); } } diff --git a/app/src/main/java/app/fedilab/android/mastodon/activities/BaseActivity.java b/app/src/main/java/app/fedilab/android/mastodon/activities/BaseActivity.java index 6ab76c08..b0c2041d 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/activities/BaseActivity.java +++ b/app/src/main/java/app/fedilab/android/mastodon/activities/BaseActivity.java @@ -39,7 +39,6 @@ import org.conscrypt.Conscrypt; import java.security.Security; -import app.fedilab.android.BaseMainActivity; import app.fedilab.android.R; import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.helper.ThemeHelper; diff --git a/app/src/main/java/app/fedilab/android/mastodon/activities/ComposeActivity.java b/app/src/main/java/app/fedilab/android/mastodon/activities/ComposeActivity.java index 6d9c24d5..1664337d 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/activities/ComposeActivity.java +++ b/app/src/main/java/app/fedilab/android/mastodon/activities/ComposeActivity.java @@ -50,7 +50,6 @@ import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AlertDialog; import androidx.core.content.ContextCompat; import androidx.lifecycle.ViewModelProvider; - import androidx.preference.PreferenceManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.work.Data; @@ -88,6 +87,7 @@ import app.fedilab.android.mastodon.client.entities.api.Mention; import app.fedilab.android.mastodon.client.entities.api.ScheduledStatus; import app.fedilab.android.mastodon.client.entities.api.Status; import app.fedilab.android.mastodon.client.entities.app.BaseAccount; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.client.entities.app.StatusDraft; import app.fedilab.android.mastodon.exception.DBException; import app.fedilab.android.mastodon.helper.DividerDecorationSimple; @@ -120,26 +120,31 @@ public class ComposeActivity extends BaseActivity implements ComposeAdapter.Mana private final BroadcastReceiver imageReceiver = new BroadcastReceiver() { @Override public void onReceive(android.content.Context context, Intent intent) { - String imgpath = intent.getStringExtra("imgpath"); - float focusX = intent.getFloatExtra("focusX", -2); - float focusY = intent.getFloatExtra("focusY", -2); - if (imgpath != null) { - int position = 0; - for (Status status : statusList) { - if (status.media_attachments != null && status.media_attachments.size() > 0) { - for (Attachment attachment : status.media_attachments) { - if (attachment.local_path != null && attachment.local_path.equalsIgnoreCase(imgpath)) { - if (focusX != -2) { - attachment.focus = focusX + "," + focusY; + Bundle args = intent.getExtras(); + if (args != null) { + long bundleId = args.getLong(Helper.ARG_INTENT_ID, -1); + new CachedBundle(ComposeActivity.this).getBundle(bundleId, currentAccount, bundle -> { + String imgpath = bundle.getString("imgpath"); + float focusX = bundle.getFloat("focusX", -2); + float focusY = bundle.getFloat("focusY", -2); + if (imgpath != null) { + int position = 0; + for (Status status : statusList) { + if (status.media_attachments != null && status.media_attachments.size() > 0) { + for (Attachment attachment : status.media_attachments) { + if (attachment.local_path != null && attachment.local_path.equalsIgnoreCase(imgpath)) { + if (focusX != -2) { + attachment.focus = focusX + "," + focusY; + } + composeAdapter.notifyItemChanged(position); + break; + } } - - composeAdapter.notifyItemChanged(position); - break; } + position++; } } - position++; - } + }); } } }; @@ -485,259 +490,275 @@ public class ComposeActivity extends BaseActivity implements ComposeAdapter.Mana statusList = new ArrayList<>(); Bundle b = getIntent().getExtras(); if (b != null) { - statusReply = (Status) b.getSerializable(Helper.ARG_STATUS_REPLY); - statusQuoted = (Status) b.getSerializable(Helper.ARG_QUOTED_MESSAGE); - statusDraft = (StatusDraft) b.getSerializable(Helper.ARG_STATUS_DRAFT); - scheduledStatus = (ScheduledStatus) b.getSerializable(Helper.ARG_STATUS_SCHEDULED); - statusReplyId = b.getString(Helper.ARG_STATUS_REPLY_ID); - statusMention = (Status) b.getSerializable(Helper.ARG_STATUS_MENTION); - account = (BaseAccount) b.getSerializable(Helper.ARG_ACCOUNT); - if (account == null) { - account = currentAccount; - } - editMessageId = b.getString(Helper.ARG_EDIT_STATUS_ID, null); - instance = b.getString(Helper.ARG_INSTANCE, null); - token = b.getString(Helper.ARG_TOKEN, null); - visibility = b.getString(Helper.ARG_VISIBILITY, null); - if (visibility == null && statusReply != null) { - visibility = getVisibility(account, statusReply.visibility); - } else if (visibility == null && currentAccount != null && currentAccount.mastodon_account != null && currentAccount.mastodon_account.source != null) { - visibility = currentAccount.mastodon_account.source.privacy; + long bundleId = b.getLong(Helper.ARG_INTENT_ID, -1); + if (bundleId != -1) { + new CachedBundle(ComposeActivity.this).getBundle(bundleId, currentAccount, this::initializeAfterBundle); + } else { + initializeAfterBundle(b); } - mentionBooster = (Account) b.getSerializable(Helper.ARG_MENTION_BOOSTER); - accountMention = (Account) b.getSerializable(Helper.ARG_ACCOUNT_MENTION); - //Shared elements - sharedAttachments = (ArrayList) b.getSerializable(Helper.ARG_MEDIA_ATTACHMENTS); - sharedUrlMedia = b.getString(Helper.ARG_SHARE_URL_MEDIA); - sharedSubject = b.getString(Helper.ARG_SHARE_SUBJECT, null); - sharedContent = b.getString(Helper.ARG_SHARE_CONTENT, null); - sharedTitle = b.getString(Helper.ARG_SHARE_TITLE, null); - sharedDescription = b.getString(Helper.ARG_SHARE_DESCRIPTION, null); - shareURL = b.getString(Helper.ARG_SHARE_URL, null); + } else { + initializeAfterBundle(null); } + } - if (sharedContent != null && shareURL != null && sharedContent.compareTo(shareURL) == 0) { - sharedContent = ""; - } - if (sharedTitle != null && sharedSubject != null && sharedSubject.length() > sharedTitle.length()) { - sharedTitle = sharedSubject; - } - //Edit a scheduled status from server - if (scheduledStatus != null) { - statusDraft = new StatusDraft(); - List statuses = new ArrayList<>(); - Status status = new Status(); - status.id = Helper.generateIdString(); - status.text = scheduledStatus.params.text; - status.in_reply_to_id = scheduledStatus.params.in_reply_to_id; - status.poll = scheduledStatus.params.poll; - - if (scheduledStatus.params.media_ids != null && scheduledStatus.params.media_ids.size() > 0) { - status.media_attachments = new ArrayList<>(); - new Thread(() -> { - StatusesVM statusesVM = new ViewModelProvider(ComposeActivity.this).get(StatusesVM.class); - for (String attachmentId : scheduledStatus.params.media_ids) { - statusesVM.getAttachment(instance, token, attachmentId) - .observe(ComposeActivity.this, attachment -> status.media_attachments.add(attachment)); - } - }).start(); - } - status.sensitive = scheduledStatus.params.sensitive; - status.spoiler_text = scheduledStatus.params.spoiler_text; - status.visibility = scheduledStatus.params.visibility; - statusDraft.statusDraftList = statuses; - } - if (account == null) { - account = currentAccount; - } - if (account == null) { - Toasty.error(ComposeActivity.this, getString(R.string.toast_error), Toasty.LENGTH_SHORT).show(); - finish(); - return; - } - if (instance == null) { - instance = account.instance; - } - if (token == null) { - token = account.token; - } - if (emojis == null || !emojis.containsKey(instance)) { - new Thread(() -> { - try { - emojis.put(instance, new EmojiInstance(ComposeActivity.this).getEmojiList(instance)); - } catch (DBException e) { - e.printStackTrace(); + private void initializeAfterBundle(Bundle b) { + SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this); + new Thread(() -> { + if (b != null) { + statusReply = (Status) b.getSerializable(Helper.ARG_STATUS_REPLY); + statusQuoted = (Status) b.getSerializable(Helper.ARG_QUOTED_MESSAGE); + statusDraft = (StatusDraft) b.getSerializable(Helper.ARG_STATUS_DRAFT); + scheduledStatus = (ScheduledStatus) b.getSerializable(Helper.ARG_STATUS_SCHEDULED); + statusReplyId = b.getString(Helper.ARG_STATUS_REPLY_ID); + statusMention = (Status) b.getSerializable(Helper.ARG_STATUS_MENTION); + account = (BaseAccount) b.getSerializable(Helper.ARG_ACCOUNT); + if (account == null) { + account = currentAccount; } - }).start(); - } - if (MainActivity.instanceInfo == null) { - String instanceInfo = sharedpreferences.getString(getString(R.string.INSTANCE_INFO) + instance, null); - if (instanceInfo != null) { - MainActivity.instanceInfo = Instance.restore(instanceInfo); - } - } - - StatusesVM statusesVM = new ViewModelProvider(ComposeActivity.this).get(StatusesVM.class); - //Empty compose - List statusDraftList = new ArrayList<>(); - Status status = new Status(); - status.id = Helper.generateIdString(); - if (statusQuoted != null) { - status.quote_id = statusQuoted.id; - } - statusDraftList.add(status); - - if (statusReplyId != null && statusDraft != null) {//Delete and redraft - statusesVM.getStatus(currentInstance, BaseMainActivity.currentToken, statusReplyId) - .observe(ComposeActivity.this, status1 -> { - if (status1 != null) { - statusesVM.getContext(currentInstance, BaseMainActivity.currentToken, statusReplyId) - .observe(ComposeActivity.this, statusContext -> { - if (statusContext != null) { - initializeContextRedraftView(statusContext, status1); - } else { - Helper.sendToastMessage(getApplication(), Helper.RECEIVE_TOAST_TYPE_ERROR, getString(R.string.toast_error)); - } - }); - } else { - Helper.sendToastMessage(getApplication(), Helper.RECEIVE_TOAST_TYPE_ERROR, getString(R.string.toast_error)); - } - }); - } else if (statusDraft != null) {//Restore a draft with all messages - restoredDraft = true; - if (statusDraft.statusReplyList != null) { - statusList.addAll(statusDraft.statusReplyList); - binding.recyclerView.addItemDecoration(new DividerDecorationSimple(ComposeActivity.this, statusList)); - } - int statusCount = statusList.size(); - statusList.addAll(statusDraft.statusDraftList); - composeAdapter = new ComposeAdapter(statusList, statusCount, account, accountMention, visibility, editMessageId); - composeAdapter.mediaDescriptionCallBack = this; - composeAdapter.manageDrafts = this; - composeAdapter.promptDraftListener = this; - LinearLayoutManager mLayoutManager = new LinearLayoutManager(ComposeActivity.this); - binding.recyclerView.setLayoutManager(mLayoutManager); - binding.recyclerView.setAdapter(composeAdapter); - binding.recyclerView.scrollToPosition(composeAdapter.getItemCount() - 1); - - } else if (statusReply != null) { - statusList.add(statusReply); - int statusCount = statusList.size(); - statusDraftList.get(0).in_reply_to_id = statusReply.id; - //We change order for mentions - //At first place the account that has been mentioned if it's not our - statusDraftList.get(0).mentions = new ArrayList<>(); - if (statusReply.account.acct != null && account.mastodon_account != null && !statusReply.account.acct.equalsIgnoreCase(account.mastodon_account.acct)) { - Mention mention = new Mention(); - mention.acct = "@" + statusReply.account.acct; - mention.url = statusReply.account.url; - mention.username = statusReply.account.username; - statusDraftList.get(0).mentions.add(mention); - } - - - //There are other mentions to - if (statusReply.mentions != null && statusReply.mentions.size() > 0) { - for (Mention mentionTmp : statusReply.mentions) { - if (statusReply.account.acct != null && !mentionTmp.acct.equalsIgnoreCase(statusReply.account.acct) && account.mastodon_account != null && !mentionTmp.acct.equalsIgnoreCase(account.mastodon_account.acct)) { - statusDraftList.get(0).mentions.add(mentionTmp); - } + editMessageId = b.getString(Helper.ARG_EDIT_STATUS_ID, null); + instance = b.getString(Helper.ARG_INSTANCE, null); + token = b.getString(Helper.ARG_TOKEN, null); + visibility = b.getString(Helper.ARG_VISIBILITY, null); + if (visibility == null && statusReply != null) { + visibility = getVisibility(account, statusReply.visibility); + } else if (visibility == null && currentAccount != null && currentAccount.mastodon_account != null && currentAccount.mastodon_account.source != null) { + visibility = currentAccount.mastodon_account.source.privacy; } + mentionBooster = (Account) b.getSerializable(Helper.ARG_MENTION_BOOSTER); + accountMention = (Account) b.getSerializable(Helper.ARG_ACCOUNT_MENTION); + //Shared elements + sharedAttachments = (ArrayList) b.getSerializable(Helper.ARG_MEDIA_ATTACHMENTS); + sharedUrlMedia = b.getString(Helper.ARG_SHARE_URL_MEDIA); + sharedSubject = b.getString(Helper.ARG_SHARE_SUBJECT, null); + sharedContent = b.getString(Helper.ARG_SHARE_CONTENT, null); + sharedTitle = b.getString(Helper.ARG_SHARE_TITLE, null); + sharedDescription = b.getString(Helper.ARG_SHARE_DESCRIPTION, null); + shareURL = b.getString(Helper.ARG_SHARE_URL, null); } - if (mentionBooster != null) { - Mention mention = new Mention(); - mention.acct = mentionBooster.acct; - mention.url = mentionBooster.url; - mention.username = mentionBooster.username; - boolean present = false; - for (Mention mentionTmp : statusDraftList.get(0).mentions) { - if (mentionTmp.acct.equalsIgnoreCase(mentionBooster.acct)) { - present = true; - break; + Handler mainHandler = new Handler(Looper.getMainLooper()); + Runnable myRunnable = () -> { + if (sharedContent != null && shareURL != null && sharedContent.compareTo(shareURL) == 0) { + sharedContent = ""; + } + if (sharedTitle != null && sharedSubject != null && sharedSubject.length() > sharedTitle.length()) { + sharedTitle = sharedSubject; + } + //Edit a scheduled status from server + if (scheduledStatus != null) { + statusDraft = new StatusDraft(); + List statuses = new ArrayList<>(); + Status status = new Status(); + status.id = Helper.generateIdString(); + status.text = scheduledStatus.params.text; + status.in_reply_to_id = scheduledStatus.params.in_reply_to_id; + status.poll = scheduledStatus.params.poll; + + if (scheduledStatus.params.media_ids != null && scheduledStatus.params.media_ids.size() > 0) { + status.media_attachments = new ArrayList<>(); + new Thread(() -> { + StatusesVM statusesVM = new ViewModelProvider(ComposeActivity.this).get(StatusesVM.class); + for (String attachmentId : scheduledStatus.params.media_ids) { + statusesVM.getAttachment(instance, token, attachmentId) + .observe(ComposeActivity.this, attachment -> status.media_attachments.add(attachment)); + } + }).start(); } + status.sensitive = scheduledStatus.params.sensitive; + status.spoiler_text = scheduledStatus.params.spoiler_text; + status.visibility = scheduledStatus.params.visibility; + statusDraft.statusDraftList = statuses; } - if (!present) { - statusDraftList.get(0).mentions.add(mention); + if (account == null) { + account = currentAccount; } - } - if (statusReply.spoiler_text != null) { - statusDraftList.get(0).spoiler_text = statusReply.spoiler_text; - if (statusReply.spoiler_text.trim().length() > 0) { - statusDraftList.get(0).spoilerChecked = true; + if (account == null) { + Toasty.error(ComposeActivity.this, getString(R.string.toast_error), Toasty.LENGTH_SHORT).show(); + finish(); + return; } - } - if (statusReply.language != null && !statusReply.language.isEmpty()) { - Set storedLanguages = sharedpreferences.getStringSet(getString(R.string.SET_SELECTED_LANGUAGE), null); - if (storedLanguages == null || storedLanguages.size() == 0) { - statusDraftList.get(0).language = statusReply.language; - } else { - if (storedLanguages.contains(statusReply.language)) { - statusDraftList.get(0).language = statusReply.language; - } else { - String currentCode = sharedpreferences.getString(getString(R.string.SET_COMPOSE_LANGUAGE) + account.user_id + account.instance, Locale.getDefault().getLanguage()); - if (currentCode.isEmpty()) { - currentCode = "EN"; + if (instance == null) { + instance = account.instance; + } + if (token == null) { + token = account.token; + } + if (emojis == null || !emojis.containsKey(instance)) { + new Thread(() -> { + try { + emojis.put(instance, new EmojiInstance(ComposeActivity.this).getEmojiList(instance)); + } catch (DBException e) { + e.printStackTrace(); } - statusDraftList.get(0).language = currentCode; + }).start(); + } + if (MainActivity.instanceInfo == null) { + String instanceInfo = sharedpreferences.getString(getString(R.string.INSTANCE_INFO) + instance, null); + if (instanceInfo != null) { + MainActivity.instanceInfo = Instance.restore(instanceInfo); } } - } - //StatusDraftList at this point should only have one element - statusList.addAll(statusDraftList); - composeAdapter = new ComposeAdapter(statusList, statusCount, account, accountMention, visibility, editMessageId); - composeAdapter.mediaDescriptionCallBack = this; - composeAdapter.manageDrafts = this; - composeAdapter.promptDraftListener = this; - LinearLayoutManager mLayoutManager = new LinearLayoutManager(ComposeActivity.this); - binding.recyclerView.setLayoutManager(mLayoutManager); - binding.recyclerView.setAdapter(composeAdapter); - statusesVM.getContext(currentInstance, BaseMainActivity.currentToken, statusReply.id) - .observe(ComposeActivity.this, this::initializeContextView); - } else if (statusQuoted != null) { - statusList.add(statusQuoted); - int statusCount = statusList.size(); - statusDraftList.get(0).quote_id = statusQuoted.id; - //StatusDraftList at this point should only have one element - statusList.addAll(statusDraftList); - composeAdapter = new ComposeAdapter(statusList, statusCount, account, accountMention, visibility, editMessageId); - composeAdapter.mediaDescriptionCallBack = this; - composeAdapter.manageDrafts = this; - composeAdapter.promptDraftListener = this; - LinearLayoutManager mLayoutManager = new LinearLayoutManager(ComposeActivity.this); - binding.recyclerView.setLayoutManager(mLayoutManager); - binding.recyclerView.setAdapter(composeAdapter); - } else { - //Compose without replying - statusList.addAll(statusDraftList); - composeAdapter = new ComposeAdapter(statusList, 0, account, accountMention, visibility, editMessageId); - composeAdapter.mediaDescriptionCallBack = this; - composeAdapter.manageDrafts = this; - composeAdapter.promptDraftListener = this; - LinearLayoutManager mLayoutManager = new LinearLayoutManager(ComposeActivity.this); - binding.recyclerView.setLayoutManager(mLayoutManager); - binding.recyclerView.setAdapter(composeAdapter); - if (statusMention != null) { - composeAdapter.loadMentions(statusMention); - } - } - MastodonHelper.loadPPMastodon(binding.profilePicture, account.mastodon_account); - ContextCompat.registerReceiver(ComposeActivity.this, imageReceiver, new IntentFilter(Helper.INTENT_SEND_MODIFIED_IMAGE), ContextCompat.RECEIVER_NOT_EXPORTED); - if (timer != null) { - timer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - if (promptSaveDraft) { - storeDraft(false); + + StatusesVM statusesVM = new ViewModelProvider(ComposeActivity.this).get(StatusesVM.class); + //Empty compose + List statusDraftList = new ArrayList<>(); + Status status = new Status(); + status.id = Helper.generateIdString(); + if (statusQuoted != null) { + status.quote_id = statusQuoted.id; + } + statusDraftList.add(status); + + if (statusReplyId != null && statusDraft != null) {//Delete and redraft + statusesVM.getStatus(currentInstance, BaseMainActivity.currentToken, statusReplyId) + .observe(ComposeActivity.this, status1 -> { + if (status1 != null) { + statusesVM.getContext(currentInstance, BaseMainActivity.currentToken, statusReplyId) + .observe(ComposeActivity.this, statusContext -> { + if (statusContext != null) { + initializeContextRedraftView(statusContext, status1); + } else { + Helper.sendToastMessage(getApplication(), Helper.RECEIVE_TOAST_TYPE_ERROR, getString(R.string.toast_error)); + } + }); + } else { + Helper.sendToastMessage(getApplication(), Helper.RECEIVE_TOAST_TYPE_ERROR, getString(R.string.toast_error)); + } + }); + } else if (statusDraft != null) {//Restore a draft with all messages + restoredDraft = true; + if (statusDraft.statusReplyList != null) { + statusList.addAll(statusDraft.statusReplyList); + binding.recyclerView.addItemDecoration(new DividerDecorationSimple(ComposeActivity.this, statusList)); + } + int statusCount = statusList.size(); + statusList.addAll(statusDraft.statusDraftList); + composeAdapter = new ComposeAdapter(statusList, statusCount, account, accountMention, visibility, editMessageId); + composeAdapter.mediaDescriptionCallBack = this; + composeAdapter.manageDrafts = this; + composeAdapter.promptDraftListener = this; + LinearLayoutManager mLayoutManager = new LinearLayoutManager(ComposeActivity.this); + binding.recyclerView.setLayoutManager(mLayoutManager); + binding.recyclerView.setAdapter(composeAdapter); + binding.recyclerView.scrollToPosition(composeAdapter.getItemCount() - 1); + + } else if (statusReply != null) { + statusList.add(statusReply); + int statusCount = statusList.size(); + statusDraftList.get(0).in_reply_to_id = statusReply.id; + //We change order for mentions + //At first place the account that has been mentioned if it's not our + statusDraftList.get(0).mentions = new ArrayList<>(); + if (statusReply.account.acct != null && account.mastodon_account != null && !statusReply.account.acct.equalsIgnoreCase(account.mastodon_account.acct)) { + Mention mention = new Mention(); + mention.acct = "@" + statusReply.account.acct; + mention.url = statusReply.account.url; + mention.username = statusReply.account.username; + statusDraftList.get(0).mentions.add(mention); + } + + + //There are other mentions to + if (statusReply.mentions != null && statusReply.mentions.size() > 0) { + for (Mention mentionTmp : statusReply.mentions) { + if (statusReply.account.acct != null && !mentionTmp.acct.equalsIgnoreCase(statusReply.account.acct) && account.mastodon_account != null && !mentionTmp.acct.equalsIgnoreCase(account.mastodon_account.acct)) { + statusDraftList.get(0).mentions.add(mentionTmp); + } + } + } + if (mentionBooster != null) { + Mention mention = new Mention(); + mention.acct = mentionBooster.acct; + mention.url = mentionBooster.url; + mention.username = mentionBooster.username; + boolean present = false; + for (Mention mentionTmp : statusDraftList.get(0).mentions) { + if (mentionTmp.acct.equalsIgnoreCase(mentionBooster.acct)) { + present = true; + break; + } + } + if (!present) { + statusDraftList.get(0).mentions.add(mention); + } + } + if (statusReply.spoiler_text != null) { + statusDraftList.get(0).spoiler_text = statusReply.spoiler_text; + if (statusReply.spoiler_text.trim().length() > 0) { + statusDraftList.get(0).spoilerChecked = true; + } + } + if (statusReply.language != null && !statusReply.language.isEmpty()) { + Set storedLanguages = sharedpreferences.getStringSet(getString(R.string.SET_SELECTED_LANGUAGE), null); + if (storedLanguages == null || storedLanguages.size() == 0) { + statusDraftList.get(0).language = statusReply.language; + } else { + if (storedLanguages.contains(statusReply.language)) { + statusDraftList.get(0).language = statusReply.language; + } else { + String currentCode = sharedpreferences.getString(getString(R.string.SET_COMPOSE_LANGUAGE) + account.user_id + account.instance, Locale.getDefault().getLanguage()); + if (currentCode.isEmpty()) { + currentCode = "EN"; + } + statusDraftList.get(0).language = currentCode; + } + } + } + //StatusDraftList at this point should only have one element + statusList.addAll(statusDraftList); + composeAdapter = new ComposeAdapter(statusList, statusCount, account, accountMention, visibility, editMessageId); + composeAdapter.mediaDescriptionCallBack = this; + composeAdapter.manageDrafts = this; + composeAdapter.promptDraftListener = this; + LinearLayoutManager mLayoutManager = new LinearLayoutManager(ComposeActivity.this); + binding.recyclerView.setLayoutManager(mLayoutManager); + binding.recyclerView.setAdapter(composeAdapter); + statusesVM.getContext(currentInstance, BaseMainActivity.currentToken, statusReply.id) + .observe(ComposeActivity.this, this::initializeContextView); + } else if (statusQuoted != null) { + statusList.add(statusQuoted); + int statusCount = statusList.size(); + statusDraftList.get(0).quote_id = statusQuoted.id; + //StatusDraftList at this point should only have one element + statusList.addAll(statusDraftList); + composeAdapter = new ComposeAdapter(statusList, statusCount, account, accountMention, visibility, editMessageId); + composeAdapter.mediaDescriptionCallBack = this; + composeAdapter.manageDrafts = this; + composeAdapter.promptDraftListener = this; + LinearLayoutManager mLayoutManager = new LinearLayoutManager(ComposeActivity.this); + binding.recyclerView.setLayoutManager(mLayoutManager); + binding.recyclerView.setAdapter(composeAdapter); + } else { + //Compose without replying + statusList.addAll(statusDraftList); + composeAdapter = new ComposeAdapter(statusList, 0, account, accountMention, visibility, editMessageId); + composeAdapter.mediaDescriptionCallBack = this; + composeAdapter.manageDrafts = this; + composeAdapter.promptDraftListener = this; + LinearLayoutManager mLayoutManager = new LinearLayoutManager(ComposeActivity.this); + binding.recyclerView.setLayoutManager(mLayoutManager); + binding.recyclerView.setAdapter(composeAdapter); + if (statusMention != null) { + composeAdapter.loadMentions(statusMention); } } - }, 0, 10000); - } + MastodonHelper.loadPPMastodon(binding.profilePicture, account.mastodon_account); + ContextCompat.registerReceiver(ComposeActivity.this, imageReceiver, new IntentFilter(Helper.INTENT_SEND_MODIFIED_IMAGE), ContextCompat.RECEIVER_NOT_EXPORTED); + if (timer != null) { + timer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + if (promptSaveDraft) { + storeDraft(false); + } + } + }, 0, 10000); + } - if (sharedAttachments != null && sharedAttachments.size() > 0) { - for (Attachment attachment : sharedAttachments) { - composeAdapter.addAttachment(-1, attachment); - } - } /*else if (sharedUri != null && !sharedUri.toString().startsWith("http")) { + if (sharedAttachments != null && sharedAttachments.size() > 0) { + for (Attachment attachment : sharedAttachments) { + composeAdapter.addAttachment(-1, attachment); + } + } /*else if (sharedUri != null && !sharedUri.toString().startsWith("http")) { List uris = new ArrayList<>(); uris.add(sharedUri); Helper.createAttachmentFromUri(ComposeActivity.this, uris, attachments -> { @@ -747,35 +768,39 @@ public class ComposeActivity extends BaseActivity implements ComposeAdapter.Mana }); } */ else if (shareURL != null) { - Helper.download(ComposeActivity.this, sharedUrlMedia, new OnDownloadInterface() { - @Override - public void onDownloaded(String saveFilePath, String downloadUrl, Error error) { - - composeAdapter.addSharing(shareURL, sharedTitle, sharedDescription, sharedSubject, sharedContent, saveFilePath); - } + Helper.download(ComposeActivity.this, sharedUrlMedia, new OnDownloadInterface() { + @Override + public void onDownloaded(String saveFilePath, String downloadUrl, Error error) { - @Override - public void onUpdateProgress(int progress) { + composeAdapter.addSharing(shareURL, sharedTitle, sharedDescription, sharedSubject, sharedContent, saveFilePath); + } - } - }); + @Override + public void onUpdateProgress(int progress) { - } else { - if (composeAdapter != null) { - composeAdapter.addSharing(null, null, sharedDescription, null, sharedContent, null); - } - } + } + }); - getOnBackPressedDispatcher().addCallback(new OnBackPressedCallback(true) { - @Override - public void handleOnBackPressed() { - if (binding.recyclerView.getVisibility() == View.VISIBLE) { - storeDraftWarning(); + } else { + if (composeAdapter != null) { + composeAdapter.addSharing(null, null, sharedDescription, null, sharedContent, null); + } } - } - }); + + getOnBackPressedDispatcher().addCallback(new OnBackPressedCallback(true) { + @Override + public void handleOnBackPressed() { + if (binding.recyclerView.getVisibility() == View.VISIBLE) { + storeDraftWarning(); + } + } + }); + }; + mainHandler.post(myRunnable); + }).start(); } + @Override public void onItemDraftAdded(int position, String initialContent) { Status status = new Status(); @@ -783,7 +808,7 @@ public class ComposeActivity extends BaseActivity implements ComposeAdapter.Mana status.id = Helper.generateIdString(); status.mentions = statusList.get(position - 1).mentions; status.visibility = statusList.get(position - 1).visibility; - if(initialContent != null) { + if (initialContent != null) { status.text = initialContent; } final SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(ComposeActivity.this); diff --git a/app/src/main/java/app/fedilab/android/mastodon/activities/ContextActivity.java b/app/src/main/java/app/fedilab/android/mastodon/activities/ContextActivity.java index a166587f..d97ab67f 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/activities/ContextActivity.java +++ b/app/src/main/java/app/fedilab/android/mastodon/activities/ContextActivity.java @@ -30,10 +30,13 @@ import android.view.MenuItem; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBar; +import androidx.appcompat.widget.Toolbar; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import androidx.preference.PreferenceManager; +import com.google.android.material.appbar.AppBarLayout; + import java.net.MalformedURLException; import java.net.URL; import java.util.regex.Matcher; @@ -44,6 +47,7 @@ import app.fedilab.android.R; import app.fedilab.android.activities.MainActivity; import app.fedilab.android.databinding.ActivityConversationBinding; import app.fedilab.android.mastodon.client.entities.api.Status; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.client.entities.app.StatusCache; import app.fedilab.android.mastodon.exception.DBException; import app.fedilab.android.mastodon.helper.Helper; @@ -64,12 +68,13 @@ public class ContextActivity extends BaseActivity implements FragmentMastodonCon private Status focusedStatus; private String focusedStatusURI; private boolean checkRemotely; + private ActivityConversationBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - ActivityConversationBinding binding = ActivityConversationBinding.inflate(getLayoutInflater()); + binding = ActivityConversationBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); setSupportActionBar(binding.toolbar); ActionBar actionBar = getSupportActionBar(); @@ -86,14 +91,25 @@ public class ContextActivity extends BaseActivity implements FragmentMastodonCon getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); } - Bundle b = getIntent().getExtras(); + manageTopBarScrolling(binding.toolbar, sharedpreferences); displayCW = sharedpreferences.getBoolean(getString(R.string.SET_EXPAND_CW), false); focusedStatus = null; // or other values - if (b != null) { - focusedStatus = (Status) b.getSerializable(Helper.ARG_STATUS); - remote_instance = b.getString(Helper.ARG_REMOTE_INSTANCE, null); - focusedStatusURI = b.getString(Helper.ARG_FOCUSED_STATUS_URI, null); + + Bundle args = getIntent().getExtras(); + if (args != null) { + long bundleId = args.getLong(Helper.ARG_INTENT_ID, -1); + new CachedBundle(ContextActivity.this).getBundle(bundleId, currentAccount, this::initializeAfterBundle); + } else { + initializeAfterBundle(null); + } + } + + private void initializeAfterBundle(Bundle bundle) { + if (bundle != null) { + focusedStatus = (Status) bundle.getSerializable(Helper.ARG_STATUS); + remote_instance = bundle.getString(Helper.ARG_REMOTE_INSTANCE, null); + focusedStatusURI = bundle.getString(Helper.ARG_FOCUSED_STATUS_URI, null); } if (focusedStatus == null || currentAccount == null || currentAccount.mastodon_account == null) { finish(); @@ -102,7 +118,7 @@ public class ContextActivity extends BaseActivity implements FragmentMastodonCon if (focusedStatusURI == null && remote_instance == null) { focusedStatusURI = focusedStatus.uri; } - MastodonHelper.loadPPMastodon(binding.profilePicture, currentAccount.mastodon_account); + SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this); checkRemotely = sharedpreferences.getBoolean(getString(R.string.SET_CONVERSATION_REMOTELY), false); if (!checkRemotely) { @@ -111,46 +127,70 @@ public class ContextActivity extends BaseActivity implements FragmentMastodonCon loadRemotelyConversation(true); invalidateOptionsMenu(); } + if(currentAccount != null) { + MastodonHelper.loadPPMastodon(binding.profilePicture, currentAccount.mastodon_account); + } } + @Override protected void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); outState.clear(); } - private void loadLocalConversation() { - Bundle bundle = new Bundle(); - bundle.putSerializable(Helper.ARG_STATUS, focusedStatus); - bundle.putString(Helper.ARG_REMOTE_INSTANCE, remote_instance); - FragmentMastodonContext fragmentMastodonContext = new FragmentMastodonContext(); - fragmentMastodonContext.firstMessage = this; - currentFragment = Helper.addFragment(getSupportFragmentManager(), R.id.nav_host_fragment_content_main, fragmentMastodonContext, bundle, null, null); - //Update the status - if (remote_instance == null) { - StatusesVM timelinesVM = new ViewModelProvider(ContextActivity.this).get(StatusesVM.class); - timelinesVM.getStatus(BaseMainActivity.currentInstance, BaseMainActivity.currentToken, focusedStatus.id).observe(ContextActivity.this, status -> { - if (status != null) { - StatusCache statusCache = new StatusCache(); - statusCache.instance = BaseMainActivity.currentInstance; - statusCache.user_id = BaseMainActivity.currentUserID; - statusCache.status = status; - statusCache.status_id = status.id; - //Update cache - new Thread(() -> { - try { - new StatusCache(getApplication()).updateIfExists(statusCache); - Handler mainHandler = new Handler(Looper.getMainLooper()); - //Update UI - Runnable myRunnable = () -> StatusAdapter.sendAction(ContextActivity.this, Helper.ARG_STATUS_ACTION, status, null); - mainHandler.post(myRunnable); - } catch (DBException e) { - e.printStackTrace(); - } - }).start(); - } - }); + private void manageTopBarScrolling(Toolbar toolbar, SharedPreferences sharedpreferences) { + final boolean topBarScrolling = !sharedpreferences.getBoolean(getString(R.string.SET_DISABLE_TOPBAR_SCROLLING), false); + + final AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams(); + + int scrollFlags = toolbarLayoutParams.getScrollFlags(); + + if (topBarScrolling) { + scrollFlags |= AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL; + + } else { + scrollFlags &= ~AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL; } + toolbarLayoutParams.setScrollFlags(scrollFlags); + } + + private void loadLocalConversation() { + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS, focusedStatus); + args.putString(Helper.ARG_REMOTE_INSTANCE, remote_instance); + new CachedBundle(ContextActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + FragmentMastodonContext fragmentMastodonContext = new FragmentMastodonContext(); + fragmentMastodonContext.firstMessage = this; + currentFragment = Helper.addFragment(getSupportFragmentManager(), R.id.nav_host_fragment_content_main, fragmentMastodonContext, bundle, null, null); + //Update the status + if (remote_instance == null) { + StatusesVM timelinesVM = new ViewModelProvider(ContextActivity.this).get(StatusesVM.class); + timelinesVM.getStatus(BaseMainActivity.currentInstance, BaseMainActivity.currentToken, focusedStatus.id).observe(ContextActivity.this, status -> { + if (status != null) { + StatusCache statusCache = new StatusCache(); + statusCache.instance = BaseMainActivity.currentInstance; + statusCache.user_id = BaseMainActivity.currentUserID; + statusCache.status = status; + statusCache.status_id = status.id; + //Update cache + new Thread(() -> { + try { + new StatusCache(getApplication()).updateIfExists(statusCache); + Handler mainHandler = new Handler(Looper.getMainLooper()); + //Update UI + Runnable myRunnable = () -> StatusAdapter.sendAction(ContextActivity.this, Helper.ARG_STATUS_ACTION, status, null); + mainHandler.post(myRunnable); + } catch (DBException e) { + e.printStackTrace(); + } + }).start(); + } + }); + } + }); } @Override @@ -245,13 +285,17 @@ public class ContextActivity extends BaseActivity implements FragmentMastodonCon String finalInstance = instance; statusesVM.getStatus(instance, null, remoteId).observe(ContextActivity.this, status -> { if (status != null) { - Bundle bundle = new Bundle(); - bundle.putSerializable(Helper.ARG_STATUS, status); - bundle.putString(Helper.ARG_REMOTE_INSTANCE, finalInstance); - bundle.putString(Helper.ARG_FOCUSED_STATUS_URI, focusedStatusURI); - FragmentMastodonContext fragmentMastodonContext = new FragmentMastodonContext(); - fragmentMastodonContext.firstMessage = ContextActivity.this; - currentFragment = Helper.addFragment(getSupportFragmentManager(), R.id.nav_host_fragment_content_main, fragmentMastodonContext, bundle, null, null); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS, status); + args.putString(Helper.ARG_REMOTE_INSTANCE, finalInstance); + args.putString(Helper.ARG_FOCUSED_STATUS_URI, focusedStatusURI); + new CachedBundle(ContextActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + FragmentMastodonContext fragmentMastodonContext = new FragmentMastodonContext(); + fragmentMastodonContext.firstMessage = ContextActivity.this; + currentFragment = Helper.addFragment(getSupportFragmentManager(), R.id.nav_host_fragment_content_main, fragmentMastodonContext, bundle, null, null); + }); } else { loadLocalConversation(); } @@ -293,11 +337,17 @@ public class ContextActivity extends BaseActivity implements FragmentMastodonCon statusesVM.getStatus(instance, null, remoteId).observe(ContextActivity.this, status -> { if (status != null) { Intent intentContext = new Intent(ContextActivity.this, ContextActivity.class); - intentContext.putExtra(Helper.ARG_STATUS, status); - intentContext.putExtra(Helper.ARG_FOCUSED_STATUS_URI, focusedStatusURI); - intentContext.putExtra(Helper.ARG_REMOTE_INSTANCE, finalInstance); - intentContext.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intentContext); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS, status); + args.putString(Helper.ARG_FOCUSED_STATUS_URI, focusedStatusURI); + args.putString(Helper.ARG_REMOTE_INSTANCE, finalInstance); + new CachedBundle(ContextActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intentContext.putExtras(bundle); + intentContext.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(intentContext); + }); } else { Toasty.warning(ContextActivity.this, getString(R.string.toast_error_fetch_message), Toasty.LENGTH_SHORT).show(); } diff --git a/app/src/main/java/app/fedilab/android/mastodon/activities/CustomSharingActivity.java b/app/src/main/java/app/fedilab/android/mastodon/activities/CustomSharingActivity.java index ea3d11b1..ee3cf8b8 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/activities/CustomSharingActivity.java +++ b/app/src/main/java/app/fedilab/android/mastodon/activities/CustomSharingActivity.java @@ -37,6 +37,7 @@ import app.fedilab.android.mastodon.client.entities.api.Attachment; import app.fedilab.android.mastodon.client.entities.api.Emoji; import app.fedilab.android.mastodon.client.entities.api.Status; import app.fedilab.android.mastodon.client.entities.api.Tag; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.helper.customsharing.CustomSharingAsyncTask; import app.fedilab.android.mastodon.helper.customsharing.CustomSharingResponse; @@ -65,23 +66,34 @@ public class CustomSharingActivity extends BaseBarActivity implements OnCustomSh protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(CustomSharingActivity.this); + binding = ActivityCustomSharingBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); } - Bundle b = getIntent().getExtras(); + Bundle args = getIntent().getExtras(); status = null; - if (b != null) { - status = (Status) b.getSerializable(Helper.ARG_STATUS); + if (args != null) { + long bundleId = args.getLong(Helper.ARG_INTENT_ID, -1); + new CachedBundle(CustomSharingActivity.this).getBundle(bundleId, currentAccount, this::initializeAfterBundle); + } else { + initializeAfterBundle(null); + } + + } + + private void initializeAfterBundle(Bundle bundle) { + + if (bundle != null) { + status = (Status) bundle.getSerializable(Helper.ARG_STATUS); } if (status == null) { finish(); return; } - + SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(CustomSharingActivity.this); bundle_creator = status.account.acct; bundle_url = status.url; bundle_id = status.uri; diff --git a/app/src/main/java/app/fedilab/android/mastodon/activities/DirectMessageActivity.java b/app/src/main/java/app/fedilab/android/mastodon/activities/DirectMessageActivity.java index 7d63ccb7..8994618f 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/activities/DirectMessageActivity.java +++ b/app/src/main/java/app/fedilab/android/mastodon/activities/DirectMessageActivity.java @@ -39,6 +39,7 @@ import app.fedilab.android.BaseMainActivity; import app.fedilab.android.R; import app.fedilab.android.databinding.ActivityDirectMessageBinding; import app.fedilab.android.mastodon.client.entities.api.Status; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.client.entities.app.StatusCache; import app.fedilab.android.mastodon.exception.DBException; import app.fedilab.android.mastodon.helper.Helper; @@ -71,53 +72,71 @@ public class DirectMessageActivity extends BaseActivity implements FragmentMasto SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this); float scale = sharedpreferences.getFloat(getString(R.string.SET_FONT_SCALE), 1.1f); binding.title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18 * 1.1f / scale); - + MastodonHelper.loadPPMastodon(binding.profilePicture, currentAccount.mastodon_account); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); } - Bundle b = getIntent().getExtras(); + Bundle args = getIntent().getExtras(); displayCW = sharedpreferences.getBoolean(getString(R.string.SET_EXPAND_CW), false); + + if (args != null) { + long bundleId = args.getLong(Helper.ARG_INTENT_ID, -1); + new CachedBundle(DirectMessageActivity.this).getBundle(bundleId, currentAccount, this::initializeAfterBundle); + } else { + initializeAfterBundle(null); + } + + + } + + private void initializeAfterBundle(Bundle bundle) { Status focusedStatus = null; // or other values - if (b != null) { - focusedStatus = (Status) b.getSerializable(Helper.ARG_STATUS); - remote_instance = b.getString(Helper.ARG_REMOTE_INSTANCE, null); + if (bundle != null) { + focusedStatus = (Status) bundle.getSerializable(Helper.ARG_STATUS); + remote_instance = bundle.getString(Helper.ARG_REMOTE_INSTANCE, null); } + if (focusedStatus == null || currentAccount == null || currentAccount.mastodon_account == null) { finish(); return; } - MastodonHelper.loadPPMastodon(binding.profilePicture, currentAccount.mastodon_account); - Bundle bundle = new Bundle(); - bundle.putSerializable(Helper.ARG_STATUS, focusedStatus); - bundle.putString(Helper.ARG_REMOTE_INSTANCE, remote_instance); - FragmentMastodonDirectMessage FragmentMastodonDirectMessage = new FragmentMastodonDirectMessage(); - FragmentMastodonDirectMessage.firstMessage = this; - currentFragment = (FragmentMastodonDirectMessage) Helper.addFragment(getSupportFragmentManager(), R.id.nav_host_fragment_content_main, FragmentMastodonDirectMessage, bundle, null, null); - StatusesVM timelinesVM = new ViewModelProvider(DirectMessageActivity.this).get(StatusesVM.class); - timelinesVM.getStatus(BaseMainActivity.currentInstance, BaseMainActivity.currentToken, focusedStatus.id).observe(DirectMessageActivity.this, status -> { - if (status != null) { - StatusCache statusCache = new StatusCache(); - statusCache.instance = BaseMainActivity.currentInstance; - statusCache.user_id = BaseMainActivity.currentUserID; - statusCache.status = status; - statusCache.status_id = status.id; - //Update cache - new Thread(() -> { - try { - new StatusCache(getApplication()).updateIfExists(statusCache); - Handler mainHandler = new Handler(Looper.getMainLooper()); - //Update UI - Runnable myRunnable = () -> StatusAdapter.sendAction(DirectMessageActivity.this, Helper.ARG_STATUS_ACTION, status, null); - mainHandler.post(myRunnable); - } catch (DBException e) { - e.printStackTrace(); - } - }).start(); - } + + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS, focusedStatus); + args.putString(Helper.ARG_REMOTE_INSTANCE, remote_instance); + Status finalFocusedStatus = focusedStatus; + new CachedBundle(DirectMessageActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle args2 = new Bundle(); + args2.putLong(Helper.ARG_INTENT_ID, bundleId); + FragmentMastodonDirectMessage FragmentMastodonDirectMessage = new FragmentMastodonDirectMessage(); + FragmentMastodonDirectMessage.firstMessage = this; + currentFragment = (FragmentMastodonDirectMessage) Helper.addFragment(getSupportFragmentManager(), R.id.nav_host_fragment_content_main, FragmentMastodonDirectMessage, args2, null, null); + StatusesVM timelinesVM = new ViewModelProvider(DirectMessageActivity.this).get(StatusesVM.class); + timelinesVM.getStatus(BaseMainActivity.currentInstance, BaseMainActivity.currentToken, finalFocusedStatus.id).observe(DirectMessageActivity.this, status -> { + if (status != null) { + StatusCache statusCache = new StatusCache(); + statusCache.instance = BaseMainActivity.currentInstance; + statusCache.user_id = BaseMainActivity.currentUserID; + statusCache.status = status; + statusCache.status_id = status.id; + //Update cache + new Thread(() -> { + try { + new StatusCache(getApplication()).updateIfExists(statusCache); + Handler mainHandler = new Handler(Looper.getMainLooper()); + //Update UI + Runnable myRunnable = () -> StatusAdapter.sendAction(DirectMessageActivity.this, Helper.ARG_STATUS_ACTION, status, null); + mainHandler.post(myRunnable); + } catch (DBException e) { + e.printStackTrace(); + } + }).start(); + } + }); }); - } + } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { diff --git a/app/src/main/java/app/fedilab/android/mastodon/activities/EditProfileActivity.java b/app/src/main/java/app/fedilab/android/mastodon/activities/EditProfileActivity.java index 2b59df22..8d5a49f5 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/activities/EditProfileActivity.java +++ b/app/src/main/java/app/fedilab/android/mastodon/activities/EditProfileActivity.java @@ -33,7 +33,6 @@ import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.lifecycle.ViewModelProvider; - import com.bumptech.glide.Glide; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.textfield.TextInputEditText; @@ -50,6 +49,7 @@ import app.fedilab.android.databinding.AccountFieldItemBinding; import app.fedilab.android.databinding.ActivityEditProfileBinding; import app.fedilab.android.mastodon.client.entities.api.Account; import app.fedilab.android.mastodon.client.entities.api.Field; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.exception.DBException; import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.helper.MastodonHelper; @@ -259,13 +259,18 @@ public class EditProfileActivity extends BaseBarActivity { } private void sendBroadCast(Account account) { - Bundle b = new Bundle(); - b.putBoolean(Helper.RECEIVE_REDRAW_PROFILE, true); - b.putSerializable(Helper.ARG_ACCOUNT, account); - Intent intentBD = new Intent(Helper.BROADCAST_DATA); - intentBD.putExtras(b); - intentBD.setPackage(BuildConfig.APPLICATION_ID); - sendBroadcast(intentBD); + Bundle args = new Bundle(); + args.putBoolean(Helper.RECEIVE_REDRAW_PROFILE, true); + args.putSerializable(Helper.ARG_ACCOUNT, account); + new CachedBundle(EditProfileActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + Intent intentBD = new Intent(Helper.BROADCAST_DATA); + intentBD.putExtras(bundle); + intentBD.setPackage(BuildConfig.APPLICATION_ID); + sendBroadcast(intentBD); + }); + } private Intent prepareIntent() { diff --git a/app/src/main/java/app/fedilab/android/mastodon/activities/FollowedTagActivity.java b/app/src/main/java/app/fedilab/android/mastodon/activities/FollowedTagActivity.java index 9b75fe47..badd5898 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/activities/FollowedTagActivity.java +++ b/app/src/main/java/app/fedilab/android/mastodon/activities/FollowedTagActivity.java @@ -40,7 +40,6 @@ import app.fedilab.android.BaseMainActivity; import app.fedilab.android.R; import app.fedilab.android.databinding.ActivityFollowedTagsBinding; import app.fedilab.android.databinding.PopupAddFollowedTagtBinding; -import app.fedilab.android.mastodon.client.entities.api.MastodonList; import app.fedilab.android.mastodon.client.entities.api.Tag; import app.fedilab.android.mastodon.client.entities.app.Timeline; import app.fedilab.android.mastodon.helper.Helper; @@ -151,7 +150,7 @@ public class FollowedTagActivity extends BaseBarActivity implements FollowedTagA popupAddFollowedTagtBinding.addTag.setFilters(new InputFilter[]{new InputFilter.LengthFilter(255)}); dialogBuilder.setPositiveButton(R.string.validate, (dialog, id) -> { String name = Objects.requireNonNull(popupAddFollowedTagtBinding.addTag.getText()).toString().trim(); - if(tagList.contains(new Tag(name))) { + if (tagList.contains(new Tag(name))) { Toasty.error(FollowedTagActivity.this, getString(R.string.tag_already_followed), Toasty.LENGTH_LONG).show(); return; } diff --git a/app/src/main/java/app/fedilab/android/mastodon/activities/HashTagActivity.java b/app/src/main/java/app/fedilab/android/mastodon/activities/HashTagActivity.java index 83ac74a5..db07020a 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/activities/HashTagActivity.java +++ b/app/src/main/java/app/fedilab/android/mastodon/activities/HashTagActivity.java @@ -29,7 +29,6 @@ import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AlertDialog; import androidx.lifecycle.ViewModelProvider; - import com.google.android.material.dialog.MaterialAlertDialogBuilder; import java.util.ArrayList; @@ -42,6 +41,7 @@ import app.fedilab.android.activities.MainActivity; import app.fedilab.android.databinding.ActivityHashtagBinding; import app.fedilab.android.mastodon.client.entities.api.Filter; import app.fedilab.android.mastodon.client.entities.api.Status; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.client.entities.app.Pinned; import app.fedilab.android.mastodon.client.entities.app.PinnedTimeline; import app.fedilab.android.mastodon.client.entities.app.StatusDraft; @@ -70,20 +70,31 @@ public class HashTagActivity extends BaseActivity { private Filter.KeywordsAttributes keyword; private PinnedTimeline pinnedTimeline; private Pinned pinned; + private ActivityHashtagBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - ActivityHashtagBinding binding = ActivityHashtagBinding.inflate(getLayoutInflater()); - + binding = ActivityHashtagBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); - Bundle b = getIntent().getExtras(); - if (b != null) { - tag = b.getString(Helper.ARG_SEARCH_KEYWORD, null); + Bundle args = getIntent().getExtras(); + if (args != null) { + long bundleId = args.getLong(Helper.ARG_INTENT_ID, -1); + new CachedBundle(HashTagActivity.this).getBundle(bundleId, currentAccount, this::initializeAfterBundle); + } else { + initializeAfterBundle(null); + } + } + + private void initializeAfterBundle(Bundle bundle) { + if( bundle != null) { + tag = bundle.getString(Helper.ARG_SEARCH_KEYWORD, null); } - if (tag == null) + if (tag == null) { finish(); + return; + } pinnedTag = null; followedTag = null; mutedTag = null; @@ -147,10 +158,10 @@ public class HashTagActivity extends BaseActivity { invalidateOptionsMenu(); } - Bundle bundle = new Bundle(); - bundle.putSerializable(Helper.ARG_TIMELINE_TYPE, Timeline.TimeLineEnum.TAG); - bundle.putString(Helper.ARG_SEARCH_KEYWORD, tag); - Helper.addFragment(getSupportFragmentManager(), R.id.nav_host_fragment_tags, new FragmentMastodonTimeline(), bundle, null, null); + Bundle bundleFragment = new Bundle(); + bundleFragment.putSerializable(Helper.ARG_TIMELINE_TYPE, Timeline.TimeLineEnum.TAG); + bundleFragment.putString(Helper.ARG_SEARCH_KEYWORD, tag); + Helper.addFragment(getSupportFragmentManager(), R.id.nav_host_fragment_tags, new FragmentMastodonTimeline(), bundleFragment, null, null); binding.compose.setOnClickListener(v -> { Intent intentToot = new Intent(HashTagActivity.this, ComposeActivity.class); StatusDraft statusDraft = new StatusDraft(); @@ -159,10 +170,14 @@ public class HashTagActivity extends BaseActivity { List statuses = new ArrayList<>(); statuses.add(status); statusDraft.statusDraftList = statuses; - Bundle _b = new Bundle(); - _b.putSerializable(Helper.ARG_STATUS_DRAFT, statusDraft); - intentToot.putExtras(_b); - startActivity(intentToot); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS_DRAFT, statusDraft); + new CachedBundle(HashTagActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundleCached = new Bundle(); + bundleCached.putLong(Helper.ARG_INTENT_ID, bundleId); + intentToot.putExtras(bundleCached); + startActivity(intentToot); + }); }); } @@ -189,13 +204,18 @@ public class HashTagActivity extends BaseActivity { } pinnedTag = false; invalidateOptionsMenu(); - Bundle b = new Bundle(); - b.putBoolean(Helper.RECEIVE_REDRAW_TOPBAR, true); + Bundle args = new Bundle(); + args.putBoolean(Helper.RECEIVE_REDRAW_TOPBAR, true); Intent intentBD = new Intent(Helper.BROADCAST_DATA); - intentBD.putExtras(b); - intentBD.setPackage(BuildConfig.APPLICATION_ID); - sendBroadcast(intentBD); - dialog.dismiss(); + new CachedBundle(HashTagActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intentBD.putExtras(bundle); + intentBD.setPackage(BuildConfig.APPLICATION_ID); + sendBroadcast(intentBD); + dialog.dismiss(); + }); + }); unpinConfirm.show(); } else { @@ -244,12 +264,16 @@ public class HashTagActivity extends BaseActivity { } else { new Pinned(HashTagActivity.this).insertPinned(pinned); } - Bundle b = new Bundle(); - b.putBoolean(Helper.RECEIVE_REDRAW_TOPBAR, true); + Bundle args = new Bundle(); + args.putBoolean(Helper.RECEIVE_REDRAW_TOPBAR, true); Intent intentBD = new Intent(Helper.BROADCAST_DATA); - intentBD.putExtras(b); - intentBD.setPackage(BuildConfig.APPLICATION_ID); - sendBroadcast(intentBD); + new CachedBundle(HashTagActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intentBD.putExtras(bundle); + intentBD.setPackage(BuildConfig.APPLICATION_ID); + sendBroadcast(intentBD); + }); pinnedTag = true; invalidateOptionsMenu(); } catch (DBException e) { diff --git a/app/src/main/java/app/fedilab/android/mastodon/activities/InstanceHealthActivity.kt b/app/src/main/java/app/fedilab/android/mastodon/activities/InstanceHealthActivity.kt index a0290ba9..1a0bd5c5 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/activities/InstanceHealthActivity.kt +++ b/app/src/main/java/app/fedilab/android/mastodon/activities/InstanceHealthActivity.kt @@ -60,63 +60,63 @@ class InstanceHealthActivity : DialogFragment() { private fun checkInstance() { val instanceSocialVM = - ViewModelProvider(this@InstanceHealthActivity)[InstanceSocialVM::class.java] + ViewModelProvider(this@InstanceHealthActivity)[InstanceSocialVM::class.java] instanceSocialVM.getInstances(BaseMainActivity.currentInstance.trim { it <= ' ' }) - .observe(this@InstanceHealthActivity) { instanceSocialList: InstanceSocial? -> - val instance = instanceSocialList?.instances?.firstOrNull { instance -> - instance.name.equals( - BaseMainActivity.currentInstance.trim { it <= ' ' }, - ignoreCase = true - ) - } - if (instance != null) { - instance.thumbnail?.takeIf { it != "null" }?.let { thumbnail -> - Glide.with(this@InstanceHealthActivity) - .asBitmap() - .placeholder(R.drawable.default_banner) - .load(thumbnail) - .into(binding.backgroundImage) + .observe(this@InstanceHealthActivity) { instanceSocialList: InstanceSocial? -> + val instance = instanceSocialList?.instances?.firstOrNull { instance -> + instance.name.equals( + BaseMainActivity.currentInstance.trim { it <= ' ' }, + ignoreCase = true + ) } - binding.name.text = instance.name - if (instance.up) { - binding.up.setText(R.string.is_up) - binding.up.setTextColor( - ThemeHelper.getAttColor( - requireContext(), - R.attr.colorPrimary + if (instance != null) { + instance.thumbnail?.takeIf { it != "null" }?.let { thumbnail -> + Glide.with(this@InstanceHealthActivity) + .asBitmap() + .placeholder(R.drawable.default_banner) + .load(thumbnail) + .into(binding.backgroundImage) + } + binding.name.text = instance.name + if (instance.up) { + binding.up.setText(R.string.is_up) + binding.up.setTextColor( + ThemeHelper.getAttColor( + requireContext(), + R.attr.colorPrimary + ) ) - ) - } else { - binding.up.setText(R.string.is_down) - binding.up.setTextColor( - ThemeHelper.getAttColor( - requireContext(), - R.attr.colorError + } else { + binding.up.setText(R.string.is_down) + binding.up.setTextColor( + ThemeHelper.getAttColor( + requireContext(), + R.attr.colorError + ) ) + } + binding.uptime.text = getString( + R.string.instance_health_uptime, + instance.uptime * 100 ) + if (instance.checked_at != null) + binding.checkedAt.text = + getString( + R.string.instance_health_checkedat, + Helper.dateToString(instance.checked_at) + ) + binding.values.text = getString( + R.string.instance_health_indication, + instance.version, + Helper.withSuffix(instance.active_users.toLong()), + Helper.withSuffix(instance.statuses.toLong()) + ) + } else { + binding.instanceData.isVisible = false + binding.noInstance.isVisible = true } - binding.uptime.text = getString( - R.string.instance_health_uptime, - instance.uptime * 100 - ) - if (instance.checked_at != null) - binding.checkedAt.text = - getString( - R.string.instance_health_checkedat, - Helper.dateToString(instance.checked_at) - ) - binding.values.text = getString( - R.string.instance_health_indication, - instance.version, - Helper.withSuffix(instance.active_users.toLong()), - Helper.withSuffix(instance.statuses.toLong()) - ) - } else { - binding.instanceData.isVisible = false - binding.noInstance.isVisible = true + binding.loader.isVisible = false } - binding.loader.isVisible = false - } } override fun onDestroyView() { diff --git a/app/src/main/java/app/fedilab/android/mastodon/activities/MastodonListActivity.java b/app/src/main/java/app/fedilab/android/mastodon/activities/MastodonListActivity.java index 0be0a8ca..929b8038 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/activities/MastodonListActivity.java +++ b/app/src/main/java/app/fedilab/android/mastodon/activities/MastodonListActivity.java @@ -15,6 +15,8 @@ package app.fedilab.android.mastodon.activities; * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; + import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; @@ -32,7 +34,6 @@ import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import androidx.lifecycle.ViewModelProvider; - import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; @@ -46,12 +47,12 @@ import java.util.Objects; import app.fedilab.android.BaseMainActivity; import app.fedilab.android.BuildConfig; import app.fedilab.android.R; -import app.fedilab.android.activities.MainActivity; import app.fedilab.android.databinding.ActivityListBinding; import app.fedilab.android.databinding.PopupAddListBinding; import app.fedilab.android.databinding.PopupManageAccountsListBinding; import app.fedilab.android.mastodon.client.entities.api.Account; import app.fedilab.android.mastodon.client.entities.api.MastodonList; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.client.entities.app.Pinned; import app.fedilab.android.mastodon.client.entities.app.PinnedTimeline; import app.fedilab.android.mastodon.client.entities.app.Timeline; @@ -176,7 +177,7 @@ public class MastodonListActivity extends BaseBarActivity implements MastodonLis timelinesVM.getAccountsInList(BaseMainActivity.currentInstance, BaseMainActivity.currentToken, mastodonList.id, null, null, 0) .observe(MastodonListActivity.this, accounts -> { if (accounts != null && accounts.size() > 0) { - accountsVM.muteAccountsHome(MainActivity.currentAccount, accounts); + accountsVM.muteAccountsHome(currentAccount, accounts); } }); dialog.dismiss(); @@ -308,13 +309,17 @@ public class MastodonListActivity extends BaseBarActivity implements MastodonLis } else { binding.notContent.setVisibility(View.GONE); } - Bundle b = new Bundle(); - b.putBoolean(Helper.RECEIVE_REDRAW_TOPBAR, true); + Bundle args = new Bundle(); + args.putBoolean(Helper.RECEIVE_REDRAW_TOPBAR, true); Intent intentBD = new Intent(Helper.BROADCAST_DATA); - b.putSerializable(Helper.RECEIVE_MASTODON_LIST, mastodonListList); - intentBD.putExtras(b); - intentBD.setPackage(BuildConfig.APPLICATION_ID); - sendBroadcast(intentBD); + args.putSerializable(Helper.RECEIVE_MASTODON_LIST, mastodonListList); + new CachedBundle(MastodonListActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intentBD.putExtras(bundle); + intentBD.setPackage(BuildConfig.APPLICATION_ID); + sendBroadcast(intentBD); + }); }); alt_bld.setNegativeButton(R.string.cancel, (dialog, id) -> dialog.dismiss()); AlertDialog alert = alt_bld.create(); @@ -344,13 +349,17 @@ public class MastodonListActivity extends BaseBarActivity implements MastodonLis } else { Toasty.error(MastodonListActivity.this, getString(R.string.toast_error), Toasty.LENGTH_LONG).show(); } - Bundle b = new Bundle(); - b.putBoolean(Helper.RECEIVE_REDRAW_TOPBAR, true); + Bundle args = new Bundle(); + args.putBoolean(Helper.RECEIVE_REDRAW_TOPBAR, true); Intent intentBD = new Intent(Helper.BROADCAST_DATA); - b.putSerializable(Helper.RECEIVE_MASTODON_LIST, mastodonListList); - intentBD.putExtras(b); - intentBD.setPackage(BuildConfig.APPLICATION_ID); - sendBroadcast(intentBD); + args.putSerializable(Helper.RECEIVE_MASTODON_LIST, mastodonListList); + new CachedBundle(MastodonListActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intentBD.putExtras(bundle); + intentBD.setPackage(BuildConfig.APPLICATION_ID); + sendBroadcast(intentBD); + }); }); dialog.dismiss(); } else { @@ -393,12 +402,16 @@ public class MastodonListActivity extends BaseBarActivity implements MastodonLis new Thread(() -> { try { new Pinned(MastodonListActivity.this).updatePinned(pinned); - Bundle b = new Bundle(); - b.putBoolean(Helper.RECEIVE_REDRAW_TOPBAR, true); + Bundle args = new Bundle(); + args.putBoolean(Helper.RECEIVE_REDRAW_TOPBAR, true); Intent intentBD = new Intent(Helper.BROADCAST_DATA); - intentBD.putExtras(b); - intentBD.setPackage(BuildConfig.APPLICATION_ID); - sendBroadcast(intentBD); + new CachedBundle(MastodonListActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intentBD.putExtras(bundle); + intentBD.setPackage(BuildConfig.APPLICATION_ID); + sendBroadcast(intentBD); + }); } catch ( DBException e) { e.printStackTrace(); diff --git a/app/src/main/java/app/fedilab/android/mastodon/activities/MediaActivity.java b/app/src/main/java/app/fedilab/android/mastodon/activities/MediaActivity.java index 39da1713..8c9dae7f 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/activities/MediaActivity.java +++ b/app/src/main/java/app/fedilab/android/mastodon/activities/MediaActivity.java @@ -15,6 +15,7 @@ package app.fedilab.android.mastodon.activities; * see . */ import static android.util.Patterns.WEB_URL; +import static app.fedilab.android.BaseMainActivity.currentAccount; import android.Manifest; import android.app.DownloadManager; @@ -63,6 +64,7 @@ import app.fedilab.android.R; import app.fedilab.android.databinding.ActivityMediaPagerBinding; import app.fedilab.android.mastodon.client.entities.api.Attachment; import app.fedilab.android.mastodon.client.entities.api.Status; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.helper.MediaHelper; import app.fedilab.android.mastodon.helper.TranslateHelper; @@ -82,10 +84,10 @@ public class MediaActivity extends BaseTransparentActivity implements OnDownload private final BroadcastReceiver onDownloadComplete = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { + long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1); if (downloadID == id) { DownloadManager manager = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE); - assert manager != null; Uri uri = manager.getUriForDownloadedFile(downloadID); Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_STREAM, uri); @@ -124,13 +126,26 @@ public class MediaActivity extends BaseTransparentActivity implements OnDownload fullscreen = false; flags = getWindow().getDecorView().getSystemUiVisibility(); - Bundle b = getIntent().getExtras(); - if (b != null) { - mediaPosition = b.getInt(Helper.ARG_MEDIA_POSITION, 1); - attachments = (ArrayList) b.getSerializable(Helper.ARG_MEDIA_ARRAY); - mediaFromProfile = b.getBoolean(Helper.ARG_MEDIA_ARRAY_PROFILE, false); - status = (Status) b.getSerializable(Helper.ARG_STATUS); + Bundle args = getIntent().getExtras(); + if (args != null) { + long bundleId = args.getLong(Helper.ARG_INTENT_ID, -1); + new CachedBundle(MediaActivity.this).getBundle(bundleId, currentAccount, this::initializeAfterBundle); + } else { + initializeAfterBundle(null); + } + + + } + + private void initializeAfterBundle(Bundle bundle) { + + if (bundle != null) { + mediaPosition = bundle.getInt(Helper.ARG_MEDIA_POSITION, 1); + attachments = (ArrayList) bundle.getSerializable(Helper.ARG_MEDIA_ARRAY); + mediaFromProfile = bundle.getBoolean(Helper.ARG_MEDIA_ARRAY_PROFILE, false); + status = (Status) bundle.getSerializable(Helper.ARG_STATUS); } + if (mediaFromProfile && FragmentMediaProfile.mediaAttachmentProfile != null) { attachments = new ArrayList<>(); attachments.addAll(FragmentMediaProfile.mediaAttachmentProfile); @@ -146,7 +161,6 @@ public class MediaActivity extends BaseTransparentActivity implements OnDownload } setTitle(""); - ScreenSlidePagerAdapter mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager()); binding.mediaViewpager.setAdapter(mPagerAdapter); binding.mediaViewpager.setSaveEnabled(false); @@ -239,8 +253,9 @@ public class MediaActivity extends BaseTransparentActivity implements OnDownload setFullscreen(true); } + private Spannable linkify(Context context, String content) { - if(content == null) { + if (content == null) { return new SpannableString(""); } Matcher matcher = WEB_URL.matcher(content); @@ -263,7 +278,7 @@ public class MediaActivity extends BaseTransparentActivity implements OnDownload @Override public void updateDrawState(@NonNull TextPaint ds) { super.updateDrawState(ds); - if(!underlineLinks) { + if (!underlineLinks) { ds.setUnderlineText(status != null && status.underlined); } } @@ -300,7 +315,8 @@ public class MediaActivity extends BaseTransparentActivity implements OnDownload finish(); try { ActivityCompat.finishAfterTransition(MediaActivity.this); - }catch (Exception ignored){} + } catch (Exception ignored) { + } return true; } else if (item.getItemId() == R.id.action_save) { int position = binding.mediaViewpager.getCurrentItem(); diff --git a/app/src/main/java/app/fedilab/android/mastodon/activities/PartnerShipActivity.java b/app/src/main/java/app/fedilab/android/mastodon/activities/PartnerShipActivity.java index 24b5a3ea..f171923c 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/activities/PartnerShipActivity.java +++ b/app/src/main/java/app/fedilab/android/mastodon/activities/PartnerShipActivity.java @@ -15,6 +15,8 @@ package app.fedilab.android.mastodon.activities; * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; + import android.content.Intent; import android.net.Uri; import android.os.Bundle; @@ -23,7 +25,6 @@ import android.view.MenuItem; import android.view.View; import android.widget.TextView; -import androidx.core.app.ActivityOptionsCompat; import androidx.lifecycle.ViewModelProvider; import java.util.ArrayList; @@ -34,6 +35,7 @@ import app.fedilab.android.R; import app.fedilab.android.databinding.ActivityPartnershipBinding; import app.fedilab.android.mastodon.client.entities.api.Account; import app.fedilab.android.mastodon.client.entities.api.Status; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.helper.CrossActionHelper; import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.helper.MastodonHelper; @@ -78,10 +80,14 @@ public class PartnerShipActivity extends BaseBarActivity { binding.accountUn.setText(account.acct); binding.accountPp.setOnClickListener(v -> { Intent intent = new Intent(PartnerShipActivity.this, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, account); - intent.putExtras(b); - startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, account); + new CachedBundle(PartnerShipActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + startActivity(intent); + }); }); AccountsVM accountsVM = new ViewModelProvider(PartnerShipActivity.this).get(AccountsVM.class); List ids = new ArrayList<>(); diff --git a/app/src/main/java/app/fedilab/android/mastodon/activities/ProfileActivity.java b/app/src/main/java/app/fedilab/android/mastodon/activities/ProfileActivity.java index 336f47c5..a1a83bd1 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/activities/ProfileActivity.java +++ b/app/src/main/java/app/fedilab/android/mastodon/activities/ProfileActivity.java @@ -51,11 +51,9 @@ import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AlertDialog; -import androidx.core.app.ActivityCompat; import androidx.core.app.ActivityOptionsCompat; import androidx.core.content.ContextCompat; import androidx.lifecycle.ViewModelProvider; - import androidx.preference.PreferenceManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; @@ -90,6 +88,7 @@ import app.fedilab.android.mastodon.client.entities.api.Field; import app.fedilab.android.mastodon.client.entities.api.IdentityProof; import app.fedilab.android.mastodon.client.entities.api.MastodonList; import app.fedilab.android.mastodon.client.entities.api.RelationShip; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.client.entities.app.Languages; import app.fedilab.android.mastodon.client.entities.app.Pinned; import app.fedilab.android.mastodon.client.entities.app.PinnedTimeline; @@ -133,14 +132,17 @@ public class ProfileActivity extends BaseActivity { private final BroadcastReceiver broadcast_data = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { - Bundle b = intent.getExtras(); - if (b != null) { - Account accountReceived = (Account) b.getSerializable(Helper.ARG_ACCOUNT); - if (b.getBoolean(Helper.RECEIVE_REDRAW_PROFILE, false) && accountReceived != null) { - if (account != null && accountReceived.id != null && account.id != null && accountReceived.id.equalsIgnoreCase(account.id)) { - initializeView(accountReceived); + Bundle args = intent.getExtras(); + if (args != null) { + long bundleId = args.getLong(Helper.ARG_INTENT_ID, -1); + new CachedBundle(ProfileActivity.this).getBundle(bundleId, currentAccount, bundle -> { + Account accountReceived = (Account) bundle.getSerializable(Helper.ARG_ACCOUNT); + if (bundle.getBoolean(Helper.RECEIVE_REDRAW_PROFILE, false) && accountReceived != null) { + if (account != null && accountReceived.id != null && account.id != null && accountReceived.id.equalsIgnoreCase(account.id)) { + initializeView(accountReceived); + } } - } + }); } } }; @@ -154,17 +156,11 @@ public class ProfileActivity extends BaseActivity { setContentView(binding.getRoot()); setSupportActionBar(binding.toolbar); ActionBar actionBar = getSupportActionBar(); - Bundle b = getIntent().getExtras(); + Bundle args = getIntent().getExtras(); binding.accountFollow.setEnabled(false); checkRemotely = false; SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this); - homeMuted = false; - if (b != null) { - account = (Account) b.getSerializable(Helper.ARG_ACCOUNT); - account_id = b.getString(Helper.ARG_USER_ID, null); - mention_str = b.getString(Helper.ARG_MENTION, null); - checkRemotely = b.getBoolean(Helper.ARG_CHECK_REMOTELY, false); - } + if (!checkRemotely) { checkRemotely = sharedpreferences.getBoolean(getString(R.string.SET_PROFILE_REMOTELY), false); } @@ -181,6 +177,22 @@ public class ProfileActivity extends BaseActivity { float scale = sharedpreferences.getFloat(getString(R.string.SET_FONT_SCALE), 1.1f); binding.title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18 * 1.1f / scale); accountsVM = new ViewModelProvider(ProfileActivity.this).get(AccountsVM.class); + homeMuted = false; + if (args != null) { + long bundleId = args.getLong(Helper.ARG_INTENT_ID, -1); + new CachedBundle(ProfileActivity.this).getBundle(bundleId, currentAccount, this::initializeAfterBundle); + } else { + initializeAfterBundle(null); + } + } + + private void initializeAfterBundle(Bundle bundle) { + if (bundle != null) { + account = (Account) bundle.getSerializable(Helper.ARG_ACCOUNT); + account_id = bundle.getString(Helper.ARG_USER_ID, null); + mention_str = bundle.getString(Helper.ARG_MENTION, null); + checkRemotely = bundle.getBoolean(Helper.ARG_CHECK_REMOTELY, false); + } if (account != null) { initializeView(account); } else if (account_id != null) { @@ -443,12 +455,16 @@ public class ProfileActivity extends BaseActivity { } binding.openRemoteProfile.setOnClickListener(v -> { Intent intent = new Intent(ProfileActivity.this, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, account); - b.putSerializable(Helper.ARG_CHECK_REMOTELY, true); - intent.putExtras(b); - startActivity(intent); - finish(); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, account); + args.putSerializable(Helper.ARG_CHECK_REMOTELY, true); + new CachedBundle(ProfileActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + startActivity(intent); + finish(); + }); }); //Fields for profile List fields = account.fields; @@ -484,7 +500,7 @@ public class ProfileActivity extends BaseActivity { binding.accountPp.setOnClickListener(v -> { Intent intent = new Intent(ProfileActivity.this, MediaActivity.class); - Bundle b = new Bundle(); + Bundle args = new Bundle(); Attachment attachment = new Attachment(); attachment.description = account.acct; attachment.preview_url = account.avatar; @@ -493,13 +509,17 @@ public class ProfileActivity extends BaseActivity { attachment.type = "image"; ArrayList attachments = new ArrayList<>(); attachments.add(attachment); - b.putSerializable(Helper.ARG_MEDIA_ARRAY, attachments); - b.putInt(Helper.ARG_MEDIA_POSITION, 1); - intent.putExtras(b); - ActivityOptionsCompat options = ActivityOptionsCompat - .makeSceneTransitionAnimation(ProfileActivity.this, binding.accountPp, attachment.url); - // start the new activity - startActivity(intent, options.toBundle()); + args.putSerializable(Helper.ARG_MEDIA_ARRAY, attachments); + args.putInt(Helper.ARG_MEDIA_POSITION, 1); + new CachedBundle(ProfileActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + ActivityOptionsCompat options = ActivityOptionsCompat + .makeSceneTransitionAnimation(ProfileActivity.this, binding.accountPp, attachment.url); + // start the new activity + startActivity(intent, options.toBundle()); + }); }); @@ -627,11 +647,15 @@ public class ProfileActivity extends BaseActivity { notificationsRelatedAccountsBinding.acc.setText(account.username); notificationsRelatedAccountsBinding.relatedAccountContainer.setOnClickListener(v -> { Intent intent = new Intent(ProfileActivity.this, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, account); - intent.putExtras(b); - // start the new activity - startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, account); + new CachedBundle(ProfileActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + startActivity(intent); + }); + }); binding.relatedAccounts.addView(notificationsRelatedAccountsBinding.getRoot()); } @@ -897,12 +921,16 @@ public class ProfileActivity extends BaseActivity { new Pinned(ProfileActivity.this).insertPinned(finalPinned); } runOnUiThread(() -> { - Bundle b = new Bundle(); - b.putBoolean(Helper.RECEIVE_REDRAW_TOPBAR, true); + Bundle args = new Bundle(); + args.putBoolean(Helper.RECEIVE_REDRAW_TOPBAR, true); Intent intentBD = new Intent(Helper.BROADCAST_DATA); - intentBD.putExtras(b); - intentBD.setPackage(BuildConfig.APPLICATION_ID); - sendBroadcast(intentBD); + new CachedBundle(ProfileActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intentBD.putExtras(bundle); + intentBD.setPackage(BuildConfig.APPLICATION_ID); + sendBroadcast(intentBD); + }); }); } catch (DBException e) { e.printStackTrace(); @@ -1022,11 +1050,15 @@ public class ProfileActivity extends BaseActivity { return true; } else if (itemId == R.id.action_direct_message) { Intent intent = new Intent(ProfileActivity.this, ComposeActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT_MENTION, account); - b.putString(Helper.ARG_VISIBILITY, "direct"); - intent.putExtras(b); - startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT_MENTION, account); + args.putString(Helper.ARG_VISIBILITY, "direct"); + new CachedBundle(ProfileActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + startActivity(intent); + }); return true; } else if (itemId == R.id.action_add_to_list) { TimelinesVM timelinesVM = new ViewModelProvider(ProfileActivity.this).get(TimelinesVM.class); @@ -1109,12 +1141,15 @@ public class ProfileActivity extends BaseActivity { return true; } else if (itemId == R.id.action_mention) { Intent intent; - Bundle b; intent = new Intent(ProfileActivity.this, ComposeActivity.class); - b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT_MENTION, account); - intent.putExtras(b); - startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT_MENTION, account); + new CachedBundle(ProfileActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + startActivity(intent); + }); return true; } else if (itemId == R.id.action_mute) { AlertDialog.Builder builderInner; diff --git a/app/src/main/java/app/fedilab/android/mastodon/activities/ReorderTimelinesActivity.java b/app/src/main/java/app/fedilab/android/mastodon/activities/ReorderTimelinesActivity.java index a0cdd267..b298ea21 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/activities/ReorderTimelinesActivity.java +++ b/app/src/main/java/app/fedilab/android/mastodon/activities/ReorderTimelinesActivity.java @@ -15,6 +15,8 @@ package app.fedilab.android.mastodon.activities; * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; + import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; @@ -31,7 +33,6 @@ import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.lifecycle.ViewModelProvider; - import androidx.preference.PreferenceManager; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.LinearLayoutManager; @@ -49,6 +50,7 @@ import app.fedilab.android.activities.MainActivity; import app.fedilab.android.databinding.ActivityReorderTabsBinding; import app.fedilab.android.databinding.PopupSearchInstanceBinding; import app.fedilab.android.mastodon.client.entities.app.BottomMenu; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.client.entities.app.InstanceSocial; import app.fedilab.android.mastodon.client.entities.app.Pinned; import app.fedilab.android.mastodon.client.entities.app.PinnedTimeline; @@ -285,12 +287,16 @@ public class ReorderTimelinesActivity extends BaseBarActivity implements OnStart } } reorderTabAdapter.notifyItemInserted(pinned.pinnedTimelines.size()); - Bundle b = new Bundle(); - b.putBoolean(Helper.RECEIVE_REDRAW_TOPBAR, true); + Bundle args = new Bundle(); + args.putBoolean(Helper.RECEIVE_REDRAW_TOPBAR, true); Intent intentBD = new Intent(Helper.BROADCAST_DATA); - intentBD.putExtras(b); - intentBD.setPackage(BuildConfig.APPLICATION_ID); - sendBroadcast(intentBD); + new CachedBundle(ReorderTimelinesActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intentBD.putExtras(bundle); + intentBD.setPackage(BuildConfig.APPLICATION_ID); + sendBroadcast(intentBD); + }); }); } else { runOnUiThread(() -> Toasty.warning(ReorderTimelinesActivity.this, getString(R.string.toast_instance_unavailable), Toast.LENGTH_LONG).show()); @@ -374,20 +380,29 @@ public class ReorderTimelinesActivity extends BaseBarActivity implements OnStart super.onPause(); if (changes) { //Update menu - Bundle b = new Bundle(); - b.putBoolean(Helper.RECEIVE_REDRAW_TOPBAR, true); + Bundle args = new Bundle(); + args.putBoolean(Helper.RECEIVE_REDRAW_TOPBAR, true); Intent intentBD = new Intent(Helper.BROADCAST_DATA); - intentBD.putExtras(b); - intentBD.setPackage(BuildConfig.APPLICATION_ID); - sendBroadcast(intentBD); + new CachedBundle(ReorderTimelinesActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intentBD.putExtras(bundle); + intentBD.setPackage(BuildConfig.APPLICATION_ID); + sendBroadcast(intentBD); + }); + } if (bottomChanges) { - Bundle b = new Bundle(); - b.putBoolean(Helper.RECEIVE_REDRAW_BOTTOM, true); + Bundle args = new Bundle(); + args.putBoolean(Helper.RECEIVE_REDRAW_BOTTOM, true); Intent intentBD = new Intent(Helper.BROADCAST_DATA); - intentBD.putExtras(b); - intentBD.setPackage(BuildConfig.APPLICATION_ID); - sendBroadcast(intentBD); + new CachedBundle(ReorderTimelinesActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intentBD.putExtras(bundle); + intentBD.setPackage(BuildConfig.APPLICATION_ID); + sendBroadcast(intentBD); + }); } } diff --git a/app/src/main/java/app/fedilab/android/mastodon/activities/ReportActivity.java b/app/src/main/java/app/fedilab/android/mastodon/activities/ReportActivity.java index fb718c08..146f9bd0 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/activities/ReportActivity.java +++ b/app/src/main/java/app/fedilab/android/mastodon/activities/ReportActivity.java @@ -14,6 +14,8 @@ package app.fedilab.android.mastodon.activities; * You should have received a copy of the GNU General Public License along with Fedilab; if not, * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; + import android.os.Bundle; import android.view.MenuItem; import android.view.View; @@ -36,6 +38,7 @@ import app.fedilab.android.databinding.ActivityReportBinding; import app.fedilab.android.mastodon.client.entities.api.Account; import app.fedilab.android.mastodon.client.entities.api.RelationShip; import app.fedilab.android.mastodon.client.entities.api.Status; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.client.entities.app.Timeline; import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.ui.drawer.RulesAdapter; @@ -70,11 +73,21 @@ public class ReportActivity extends BaseBarActivity { if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } + Bundle args = getIntent().getExtras(); + if (args != null) { + long bundleId = args.getLong(Helper.ARG_INTENT_ID, -1); + if (bundleId != -1) { + new CachedBundle(ReportActivity.this).getBundle(bundleId, currentAccount, this::initializeAfterBundle); + } else { + initializeAfterBundle(args); + } + } + } - Bundle b = getIntent().getExtras(); - if (b != null) { - status = (Status) b.getSerializable(Helper.ARG_STATUS); - account = (Account) b.getSerializable(Helper.ARG_ACCOUNT); + private void initializeAfterBundle(Bundle bundle) { + if (bundle != null) { + status = (Status) bundle.getSerializable(Helper.ARG_STATUS); + account = (Account) bundle.getSerializable(Helper.ARG_ACCOUNT); } if (account == null && status != null) { account = status.account; @@ -139,7 +152,6 @@ public class ReportActivity extends BaseBarActivity { }); } - @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { @@ -222,21 +234,25 @@ public class ReportActivity extends BaseBarActivity { private void switchToSpam() { fragment = new FragmentMastodonTimeline(); - Bundle bundle = new Bundle(); - bundle.putSerializable(Helper.ARG_TIMELINE_TYPE, Timeline.TimeLineEnum.ACCOUNT_TIMELINE); - bundle.putSerializable(Helper.ARG_ACCOUNT, account); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_TIMELINE_TYPE, Timeline.TimeLineEnum.ACCOUNT_TIMELINE); + args.putSerializable(Helper.ARG_ACCOUNT, account); //Set to display statuses with less options - bundle.putBoolean(Helper.ARG_MINIFIED, true); + args.putBoolean(Helper.ARG_MINIFIED, true); if (status != null) { status.isChecked = true; - bundle.putSerializable(Helper.ARG_STATUS_REPORT, status); + args.putSerializable(Helper.ARG_STATUS_REPORT, status); } - fragment.setArguments(bundle); - FragmentManager fragmentManager = getSupportFragmentManager(); - FragmentTransaction fragmentTransaction = - fragmentManager.beginTransaction(); - fragmentTransaction.replace(R.id.fram_spam_container, fragment); - fragmentTransaction.commit(); + new CachedBundle(ReportActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + fragment.setArguments(bundle); + FragmentManager fragmentManager = getSupportFragmentManager(); + FragmentTransaction fragmentTransaction = + fragmentManager.beginTransaction(); + fragmentTransaction.replace(R.id.fram_spam_container, fragment); + fragmentTransaction.commit(); + }); binding.actionButton.setText(R.string.next); binding.actionButton.setOnClickListener(v -> { @@ -248,22 +264,25 @@ public class ReportActivity extends BaseBarActivity { private void switchToSomethingElse() { fragment = new FragmentMastodonTimeline(); - Bundle bundle = new Bundle(); - bundle.putSerializable(Helper.ARG_TIMELINE_TYPE, Timeline.TimeLineEnum.ACCOUNT_TIMELINE); - bundle.putSerializable(Helper.ARG_ACCOUNT, account); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_TIMELINE_TYPE, Timeline.TimeLineEnum.ACCOUNT_TIMELINE); + args.putSerializable(Helper.ARG_ACCOUNT, account); //Set to display statuses with less options - bundle.putBoolean(Helper.ARG_MINIFIED, true); + args.putBoolean(Helper.ARG_MINIFIED, true); if (status != null) { status.isChecked = true; - bundle.putSerializable(Helper.ARG_STATUS_REPORT, status); + args.putSerializable(Helper.ARG_STATUS_REPORT, status); } - fragment.setArguments(bundle); - FragmentManager fragmentManager = getSupportFragmentManager(); - FragmentTransaction fragmentTransaction = - fragmentManager.beginTransaction(); - fragmentTransaction.replace(R.id.fram_se_container, fragment); - fragmentTransaction.commit(); - + new CachedBundle(ReportActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + fragment.setArguments(bundle); + FragmentManager fragmentManager = getSupportFragmentManager(); + FragmentTransaction fragmentTransaction = + fragmentManager.beginTransaction(); + fragmentTransaction.replace(R.id.fram_se_container, fragment); + fragmentTransaction.commit(); + }); binding.actionButton.setText(R.string.next); binding.actionButton.setOnClickListener(v -> { if (category == null) { diff --git a/app/src/main/java/app/fedilab/android/mastodon/activities/SearchResultTabActivity.java b/app/src/main/java/app/fedilab/android/mastodon/activities/SearchResultTabActivity.java index 06be2592..50a8ec4d 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/activities/SearchResultTabActivity.java +++ b/app/src/main/java/app/fedilab/android/mastodon/activities/SearchResultTabActivity.java @@ -114,14 +114,11 @@ public class SearchResultTabActivity extends BaseBarActivity { Fragment fragment; if (binding.searchViewpager.getAdapter() != null) { fragment = (Fragment) binding.searchViewpager.getAdapter().instantiateItem(binding.searchViewpager, tab.getPosition()); - if (fragment instanceof FragmentMastodonAccount) { - FragmentMastodonAccount fragmentMastodonAccount = ((FragmentMastodonAccount) fragment); + if (fragment instanceof FragmentMastodonAccount fragmentMastodonAccount) { fragmentMastodonAccount.scrollToTop(); - } else if (fragment instanceof FragmentMastodonTimeline) { - FragmentMastodonTimeline fragmentMastodonTimeline = ((FragmentMastodonTimeline) fragment); + } else if (fragment instanceof FragmentMastodonTimeline fragmentMastodonTimeline) { fragmentMastodonTimeline.scrollToTop(); - } else if (fragment instanceof FragmentMastodonTag) { - FragmentMastodonTag fragmentMastodonTag = ((FragmentMastodonTag) fragment); + } else if (fragment instanceof FragmentMastodonTag fragmentMastodonTag) { fragmentMastodonTag.scrollToTop(); } } @@ -136,6 +133,9 @@ public class SearchResultTabActivity extends BaseBarActivity { inflater.inflate(R.menu.menu_search, menu); SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView(); + if(searchView == null) { + return true; + } if (search != null) { searchView.setQuery(search, false); } @@ -302,27 +302,32 @@ public class SearchResultTabActivity extends BaseBarActivity { @Override public Fragment getItem(int position) { Bundle bundle = new Bundle(); + FragmentMastodonTimeline fragmentMastodonTimeline; switch (position) { - case 0: + case 0 -> { FragmentMastodonTag fragmentMastodonTag = new FragmentMastodonTag(); bundle.putString(Helper.ARG_SEARCH_KEYWORD, search); fragmentMastodonTag.setArguments(bundle); return fragmentMastodonTag; - case 1: + } + case 1 -> { FragmentMastodonAccount fragmentMastodonAccount = new FragmentMastodonAccount(); bundle.putString(Helper.ARG_SEARCH_KEYWORD, search); fragmentMastodonAccount.setArguments(bundle); return fragmentMastodonAccount; - case 2: - FragmentMastodonTimeline fragmentMastodonTimeline = new FragmentMastodonTimeline(); + } + case 2 -> { + fragmentMastodonTimeline = new FragmentMastodonTimeline(); bundle.putString(Helper.ARG_SEARCH_KEYWORD, search); fragmentMastodonTimeline.setArguments(bundle); return fragmentMastodonTimeline; - default: + } + default -> { fragmentMastodonTimeline = new FragmentMastodonTimeline(); bundle.putString(Helper.ARG_SEARCH_KEYWORD_CACHE, search); fragmentMastodonTimeline.setArguments(bundle); return fragmentMastodonTimeline; + } } } diff --git a/app/src/main/java/app/fedilab/android/mastodon/activities/StatusInfoActivity.java b/app/src/main/java/app/fedilab/android/mastodon/activities/StatusInfoActivity.java index 7d81d5ab..6f952a93 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/activities/StatusInfoActivity.java +++ b/app/src/main/java/app/fedilab/android/mastodon/activities/StatusInfoActivity.java @@ -15,6 +15,7 @@ package app.fedilab.android.mastodon.activities; * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; import static app.fedilab.android.BaseMainActivity.currentInstance; import static app.fedilab.android.BaseMainActivity.currentToken; @@ -38,6 +39,7 @@ import app.fedilab.android.mastodon.client.entities.api.Account; import app.fedilab.android.mastodon.client.entities.api.Accounts; import app.fedilab.android.mastodon.client.entities.api.RelationShip; import app.fedilab.android.mastodon.client.entities.api.Status; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.ui.drawer.AccountAdapter; import app.fedilab.android.mastodon.viewmodel.mastodon.AccountsVM; @@ -70,12 +72,23 @@ public class StatusInfoActivity extends BaseActivity { } accountList = new ArrayList<>(); checkRemotely = false; - Bundle b = getIntent().getExtras(); - if (b != null) { - type = (typeOfInfo) b.getSerializable(Helper.ARG_TYPE_OF_INFO); - status = (Status) b.getSerializable(Helper.ARG_STATUS); - checkRemotely = b.getBoolean(Helper.ARG_CHECK_REMOTELY, false); + Bundle args = getIntent().getExtras(); + if (args != null) { + long bundleId = args.getLong(Helper.ARG_INTENT_ID, -1); + new CachedBundle(StatusInfoActivity.this).getBundle(bundleId, currentAccount, this::initializeAfterBundle); + } else { + initializeAfterBundle(null); } + } + + private void initializeAfterBundle(Bundle bundle) { + + if (bundle != null) { + type = (typeOfInfo) bundle.getSerializable(Helper.ARG_TYPE_OF_INFO); + status = (Status) bundle.getSerializable(Helper.ARG_STATUS); + checkRemotely = bundle.getBoolean(Helper.ARG_CHECK_REMOTELY, false); + } + if (type == null || status == null) { finish(); return; @@ -138,6 +151,7 @@ public class StatusInfoActivity extends BaseActivity { } } + private void manageView(Accounts accounts) { binding.loadingNextAccounts.setVisibility(View.GONE); if (accountList != null && accounts != null && accounts.accounts != null) { diff --git a/app/src/main/java/app/fedilab/android/mastodon/activities/TimelineActivity.java b/app/src/main/java/app/fedilab/android/mastodon/activities/TimelineActivity.java index 6686f207..3b67773f 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/activities/TimelineActivity.java +++ b/app/src/main/java/app/fedilab/android/mastodon/activities/TimelineActivity.java @@ -14,6 +14,8 @@ package app.fedilab.android.mastodon.activities; * You should have received a copy of the GNU General Public License along with Fedilab; if not, * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; + import android.os.Bundle; import android.view.MenuItem; @@ -22,6 +24,7 @@ import org.jetbrains.annotations.NotNull; import app.fedilab.android.R; import app.fedilab.android.databinding.ActivityTimelineBinding; import app.fedilab.android.mastodon.client.entities.api.Status; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.client.entities.app.PinnedTimeline; import app.fedilab.android.mastodon.client.entities.app.Timeline; import app.fedilab.android.mastodon.helper.Helper; @@ -42,32 +45,44 @@ public class TimelineActivity extends BaseBarActivity { if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } - Bundle b = getIntent().getExtras(); + Bundle args = getIntent().getExtras(); + if (args != null) { + long bundleId = args.getLong(Helper.ARG_INTENT_ID, -1); + new CachedBundle(TimelineActivity.this).getBundle(bundleId, currentAccount, this::initializeAfterBundle); + } else { + initializeAfterBundle(null); + } + } + + private void initializeAfterBundle(Bundle bundle) { Timeline.TimeLineEnum timelineType = null; String lemmy_post_id = null; PinnedTimeline pinnedTimeline = null; Status status = null; - if (b != null) { - timelineType = (Timeline.TimeLineEnum) b.get(Helper.ARG_TIMELINE_TYPE); - lemmy_post_id = b.getString(Helper.ARG_LEMMY_POST_ID, null); - pinnedTimeline = (PinnedTimeline) b.getSerializable(Helper.ARG_REMOTE_INSTANCE); - status = (Status) b.getSerializable(Helper.ARG_STATUS); + if (bundle != null) { + timelineType = (Timeline.TimeLineEnum) bundle.get(Helper.ARG_TIMELINE_TYPE); + lemmy_post_id = bundle.getString(Helper.ARG_LEMMY_POST_ID, null); + pinnedTimeline = (PinnedTimeline) bundle.getSerializable(Helper.ARG_REMOTE_INSTANCE); + status = (Status) bundle.getSerializable(Helper.ARG_STATUS); } if (pinnedTimeline != null && pinnedTimeline.remoteInstance != null) { setTitle(pinnedTimeline.remoteInstance.host); } FragmentMastodonTimeline fragmentMastodonTimeline = new FragmentMastodonTimeline(); - Bundle bundle = new Bundle(); - bundle.putSerializable(Helper.ARG_TIMELINE_TYPE, timelineType); - bundle.putSerializable(Helper.ARG_REMOTE_INSTANCE, pinnedTimeline); - bundle.putSerializable(Helper.ARG_LEMMY_POST_ID, lemmy_post_id); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_TIMELINE_TYPE, timelineType); + args.putSerializable(Helper.ARG_REMOTE_INSTANCE, pinnedTimeline); + args.putSerializable(Helper.ARG_LEMMY_POST_ID, lemmy_post_id); if (status != null) { - bundle.putSerializable(Helper.ARG_STATUS, status); + args.putSerializable(Helper.ARG_STATUS, status); } - fragmentMastodonTimeline.setArguments(bundle); - - getSupportFragmentManager().beginTransaction() - .add(R.id.fragment_container_view, fragmentMastodonTimeline).commit(); + new CachedBundle(TimelineActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle1 = new Bundle(); + bundle1.putLong(Helper.ARG_INTENT_ID, bundleId); + fragmentMastodonTimeline.setArguments(bundle1); + getSupportFragmentManager().beginTransaction() + .add(R.id.fragment_container_view, fragmentMastodonTimeline).commit(); + }); } diff --git a/app/src/main/java/app/fedilab/android/mastodon/activities/admin/AdminAccountActivity.java b/app/src/main/java/app/fedilab/android/mastodon/activities/admin/AdminAccountActivity.java index f78e0af6..de8c7ba0 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/activities/admin/AdminAccountActivity.java +++ b/app/src/main/java/app/fedilab/android/mastodon/activities/admin/AdminAccountActivity.java @@ -15,6 +15,8 @@ package app.fedilab.android.mastodon.activities.admin; * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; + import android.content.ClipData; import android.content.ClipboardManager; import android.content.Intent; @@ -61,6 +63,7 @@ import app.fedilab.android.mastodon.activities.MediaActivity; import app.fedilab.android.mastodon.client.entities.api.Attachment; import app.fedilab.android.mastodon.client.entities.api.admin.AdminAccount; import app.fedilab.android.mastodon.client.entities.api.admin.AdminIp; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.helper.MastodonHelper; import app.fedilab.android.mastodon.helper.SpannableHelper; @@ -87,18 +90,32 @@ public class AdminAccountActivity extends BaseActivity { setContentView(binding.getRoot()); setSupportActionBar(binding.toolbar); ActionBar actionBar = getSupportActionBar(); - Bundle b = getIntent().getExtras(); + Bundle args = getIntent().getExtras(); adminAccount = null; - if (b != null) { - adminAccount = (AdminAccount) b.getSerializable(Helper.ARG_ACCOUNT); - account_id = b.getString(Helper.ARG_ACCOUNT_ID, null); - } postponeEnterTransition(); //Remove title if (actionBar != null) { actionBar.setDisplayShowTitleEnabled(false); } + + if (args != null) { + long bundleId = args.getLong(Helper.ARG_INTENT_ID, -1); + new CachedBundle(AdminAccountActivity.this).getBundle(bundleId, currentAccount, this::initializeAfterBundle); + } else { + initializeAfterBundle(null); + } + + + } + + + private void initializeAfterBundle(Bundle bundle) { + + if (bundle != null) { + adminAccount = (AdminAccount) bundle.getSerializable(Helper.ARG_ACCOUNT); + account_id = bundle.getString(Helper.ARG_ACCOUNT_ID, null); + } SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this); float scale = sharedpreferences.getFloat(getString(R.string.SET_FONT_SCALE), 1.1f); binding.title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18 * 1.1f / scale); @@ -175,8 +192,6 @@ public class AdminAccountActivity extends BaseActivity { initializeView(adminAccount); } }); - - } private void initializeView(AdminAccount adminAccount) { @@ -329,7 +344,7 @@ public class AdminAccountActivity extends BaseActivity { MastodonHelper.loadPPMastodon(binding.accountPp, adminAccount.account); binding.accountPp.setOnClickListener(v -> { Intent intent = new Intent(AdminAccountActivity.this, MediaActivity.class); - Bundle b = new Bundle(); + Bundle args = new Bundle(); Attachment attachment = new Attachment(); attachment.description = adminAccount.account.acct; attachment.preview_url = adminAccount.account.avatar; @@ -338,13 +353,17 @@ public class AdminAccountActivity extends BaseActivity { attachment.type = "image"; ArrayList attachments = new ArrayList<>(); attachments.add(attachment); - b.putSerializable(Helper.ARG_MEDIA_ARRAY, attachments); - b.putInt(Helper.ARG_MEDIA_POSITION, 1); - intent.putExtras(b); - ActivityOptionsCompat options = ActivityOptionsCompat - .makeSceneTransitionAnimation(AdminAccountActivity.this, binding.accountPp, attachment.url); - // start the new activity - startActivity(intent, options.toBundle()); + args.putSerializable(Helper.ARG_MEDIA_ARRAY, attachments); + args.putInt(Helper.ARG_MEDIA_POSITION, 1); + new CachedBundle(AdminAccountActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + ActivityOptionsCompat options = ActivityOptionsCompat + .makeSceneTransitionAnimation(AdminAccountActivity.this, binding.accountPp, attachment.url); + // start the new activity + startActivity(intent, options.toBundle()); + }); }); diff --git a/app/src/main/java/app/fedilab/android/mastodon/activities/admin/AdminActionActivity.java b/app/src/main/java/app/fedilab/android/mastodon/activities/admin/AdminActionActivity.java index b84354b9..d78d756d 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/activities/admin/AdminActionActivity.java +++ b/app/src/main/java/app/fedilab/android/mastodon/activities/admin/AdminActionActivity.java @@ -14,6 +14,7 @@ package app.fedilab.android.mastodon.activities.admin; * You should have received a copy of the GNU General Public License along with Fedilab; if not, * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; import static app.fedilab.android.mastodon.activities.admin.AdminActionActivity.AdminEnum.ACCOUNT; import static app.fedilab.android.mastodon.activities.admin.AdminActionActivity.AdminEnum.DOMAIN; import static app.fedilab.android.mastodon.activities.admin.AdminActionActivity.AdminEnum.REPORT; @@ -43,6 +44,7 @@ import app.fedilab.android.databinding.PopupAdminFilterAccountsBinding; import app.fedilab.android.databinding.PopupAdminFilterReportsBinding; import app.fedilab.android.mastodon.activities.BaseBarActivity; import app.fedilab.android.mastodon.client.entities.api.admin.AdminDomainBlock; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.helper.ThemeHelper; import app.fedilab.android.mastodon.ui.fragment.admin.FragmentAdminAccount; @@ -63,18 +65,21 @@ public class AdminActionActivity extends BaseBarActivity { private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { - Bundle b = intent.getExtras(); - if (b != null) { - AdminDomainBlock adminDomainBlock = (AdminDomainBlock) b.getSerializable(Helper.ARG_ADMIN_DOMAINBLOCK); - AdminDomainBlock adminDomainBlockDelete = (AdminDomainBlock) b.getSerializable(Helper.ARG_ADMIN_DOMAINBLOCK_DELETE); - if (adminDomainBlock != null && adminDomainBlock.domain != null && fragmentAdminDomain != null) { - fragmentAdminDomain.update(adminDomainBlock); - } - if (adminDomainBlockDelete != null && fragmentAdminDomain != null) { - fragmentAdminDomain.delete(adminDomainBlockDelete); - } - } + Bundle args = intent.getExtras(); + if (args != null) { + long bundleId = args.getLong(Helper.ARG_INTENT_ID, -1); + new CachedBundle(AdminActionActivity.this).getBundle(bundleId, currentAccount, bundle -> { + AdminDomainBlock adminDomainBlock = (AdminDomainBlock) bundle.getSerializable(Helper.ARG_ADMIN_DOMAINBLOCK); + AdminDomainBlock adminDomainBlockDelete = (AdminDomainBlock) bundle.getSerializable(Helper.ARG_ADMIN_DOMAINBLOCK_DELETE); + if (adminDomainBlock != null && adminDomainBlock.domain != null && fragmentAdminDomain != null) { + fragmentAdminDomain.update(adminDomainBlock); + } + if (adminDomainBlockDelete != null && fragmentAdminDomain != null) { + fragmentAdminDomain.delete(adminDomainBlockDelete); + } + }); + } } }; diff --git a/app/src/main/java/app/fedilab/android/mastodon/activities/admin/AdminDomainBlockActivity.java b/app/src/main/java/app/fedilab/android/mastodon/activities/admin/AdminDomainBlockActivity.java index a032d163..d99f20a0 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/activities/admin/AdminDomainBlockActivity.java +++ b/app/src/main/java/app/fedilab/android/mastodon/activities/admin/AdminDomainBlockActivity.java @@ -15,6 +15,8 @@ package app.fedilab.android.mastodon.activities.admin; * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; + import android.content.Intent; import android.os.Bundle; import android.view.Menu; @@ -27,7 +29,6 @@ import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.lifecycle.ViewModelProvider; - import com.google.android.material.dialog.MaterialAlertDialogBuilder; import java.util.Objects; @@ -38,6 +39,7 @@ import app.fedilab.android.activities.MainActivity; import app.fedilab.android.databinding.ActivityAdminDomainblockBinding; import app.fedilab.android.mastodon.activities.BaseBarActivity; import app.fedilab.android.mastodon.client.entities.api.admin.AdminDomainBlock; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.viewmodel.mastodon.AdminVM; import es.dmoral.toasty.Toasty; @@ -110,10 +112,17 @@ public class AdminDomainBlockActivity extends BaseBarActivity { } else { Toasty.error(AdminDomainBlockActivity.this, getString(R.string.toast_error), Toasty.LENGTH_SHORT).show(); } - Intent intent = new Intent(Helper.BROADCAST_DATA).putExtra(Helper.ARG_ADMIN_DOMAINBLOCK, adminDomainBlockResult); - intent.setPackage(BuildConfig.APPLICATION_ID); - sendBroadcast(intent); - finish(); + Intent intent = new Intent(Helper.BROADCAST_DATA); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ADMIN_DOMAINBLOCK, adminDomainBlockResult); + new CachedBundle(AdminDomainBlockActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + intent.setPackage(BuildConfig.APPLICATION_ID); + sendBroadcast(intent); + finish(); + }); } ); }); @@ -139,10 +148,18 @@ public class AdminDomainBlockActivity extends BaseBarActivity { .setPositiveButton(R.string.unblock_domain, (dialog, which) -> { adminVM.deleteDomain(MainActivity.currentInstance, MainActivity.currentToken, adminDomainBlock.id) .observe(AdminDomainBlockActivity.this, adminDomainBlockResult -> { - Intent intent = new Intent(Helper.BROADCAST_DATA).putExtra(Helper.ARG_ADMIN_DOMAINBLOCK_DELETE, adminDomainBlock); - intent.setPackage(BuildConfig.APPLICATION_ID); - sendBroadcast(intent); - finish(); + Intent intent = new Intent(Helper.BROADCAST_DATA); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ADMIN_DOMAINBLOCK_DELETE, adminDomainBlock); + new CachedBundle(AdminDomainBlockActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + intent.setPackage(BuildConfig.APPLICATION_ID); + sendBroadcast(intent); + finish(); + }); + } ); dialog.dismiss(); diff --git a/app/src/main/java/app/fedilab/android/mastodon/activities/admin/AdminReportActivity.java b/app/src/main/java/app/fedilab/android/mastodon/activities/admin/AdminReportActivity.java index 2680275a..01a5ba73 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/activities/admin/AdminReportActivity.java +++ b/app/src/main/java/app/fedilab/android/mastodon/activities/admin/AdminReportActivity.java @@ -15,6 +15,8 @@ package app.fedilab.android.mastodon.activities.admin; * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; + import android.content.ClipData; import android.content.ClipboardManager; import android.content.Intent; @@ -46,7 +48,6 @@ import com.bumptech.glide.request.transition.Transition; import java.lang.ref.WeakReference; import java.util.ArrayList; -import java.util.List; import java.util.Locale; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; @@ -62,6 +63,7 @@ import app.fedilab.android.mastodon.client.entities.api.Account; import app.fedilab.android.mastodon.client.entities.api.Attachment; import app.fedilab.android.mastodon.client.entities.api.admin.AdminAccount; import app.fedilab.android.mastodon.client.entities.api.admin.AdminIp; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.helper.MastodonHelper; import app.fedilab.android.mastodon.helper.SpannableHelper; @@ -87,19 +89,8 @@ public class AdminReportActivity extends BaseBarActivity { setContentView(binding.getRoot()); setSupportActionBar(binding.toolbar); ActionBar actionBar = getSupportActionBar(); - Bundle b = getIntent().getExtras(); - if (b != null) { - adminAccount = (AdminAccount) b.getSerializable(Helper.ARG_ACCOUNT); - if (adminAccount != null) { - account = adminAccount.account; - } - } + Bundle args = getIntent().getExtras(); postponeEnterTransition(); - - //Remove title - if (actionBar != null) { - actionBar.setDisplayShowTitleEnabled(false); - } SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this); float scale = sharedpreferences.getFloat(getString(R.string.SET_FONT_SCALE), 1.1f); binding.title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18 * 1.1f / scale); @@ -107,6 +98,28 @@ public class AdminReportActivity extends BaseBarActivity { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); } + + //Remove title + if (actionBar != null) { + actionBar.setDisplayShowTitleEnabled(false); + } + + if (args != null) { + long bundleId = args.getLong(Helper.ARG_INTENT_ID, -1); + new CachedBundle(AdminReportActivity.this).getBundle(bundleId, currentAccount, this::initializeAfterBundle); + } else { + initializeAfterBundle(null); + } + } + + + private void initializeAfterBundle(Bundle bundle) { + if (bundle != null) { + adminAccount = (AdminAccount) bundle.getSerializable(Helper.ARG_ACCOUNT); + if (adminAccount != null) { + account = adminAccount.account; + } + } if (account != null) { initializeView(account); } else { @@ -344,7 +357,7 @@ public class AdminReportActivity extends BaseBarActivity { MastodonHelper.loadPPMastodon(binding.accountPp, account); binding.accountPp.setOnClickListener(v -> { Intent intent = new Intent(AdminReportActivity.this, MediaActivity.class); - Bundle b = new Bundle(); + Bundle args = new Bundle(); Attachment attachment = new Attachment(); attachment.description = account.acct; attachment.preview_url = account.avatar; @@ -353,13 +366,16 @@ public class AdminReportActivity extends BaseBarActivity { attachment.type = "image"; ArrayList attachments = new ArrayList<>(); attachments.add(attachment); - b.putSerializable(Helper.ARG_MEDIA_ARRAY, attachments); - b.putInt(Helper.ARG_MEDIA_POSITION, 1); - intent.putExtras(b); - ActivityOptionsCompat options = ActivityOptionsCompat - .makeSceneTransitionAnimation(AdminReportActivity.this, binding.accountPp, attachment.url); - // start the new activity - startActivity(intent, options.toBundle()); + args.putSerializable(Helper.ARG_MEDIA_ARRAY, attachments); + args.putInt(Helper.ARG_MEDIA_POSITION, 1); + new CachedBundle(AdminReportActivity.this).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + ActivityOptionsCompat options = ActivityOptionsCompat + .makeSceneTransitionAnimation(AdminReportActivity.this, binding.accountPp, attachment.url); + startActivity(intent, options.toBundle()); + }); }); diff --git a/app/src/main/java/app/fedilab/android/mastodon/client/entities/api/EmojiInstance.java b/app/src/main/java/app/fedilab/android/mastodon/client/entities/api/EmojiInstance.java index ce672178..a64b092f 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/client/entities/api/EmojiInstance.java +++ b/app/src/main/java/app/fedilab/android/mastodon/client/entities/api/EmojiInstance.java @@ -19,16 +19,13 @@ import static app.fedilab.android.BaseMainActivity.emojis; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; -import android.database.sqlite.SQLiteBlobTooBigException; import android.database.sqlite.SQLiteDatabase; import android.os.Handler; import android.os.Looper; import androidx.annotation.NonNull; -import androidx.lifecycle.ViewModelProvider; import com.google.gson.Gson; -import com.google.gson.GsonBuilder; import com.google.gson.annotations.SerializedName; import com.google.gson.reflect.TypeToken; @@ -41,7 +38,6 @@ import app.fedilab.android.BaseMainActivity; import app.fedilab.android.mastodon.client.endpoints.MastodonInstanceService; import app.fedilab.android.mastodon.exception.DBException; import app.fedilab.android.mastodon.helper.Helper; -import app.fedilab.android.mastodon.viewmodel.mastodon.InstancesVM; import app.fedilab.android.sqlite.Sqlite; import okhttp3.OkHttpClient; import retrofit2.Call; @@ -230,17 +226,12 @@ public class EmojiInstance implements Serializable { } } - public interface EmojiFilteredCallBack{ - void get(List emojiList); - } - /** * Returns the emojis for an instance * * @param instance String - * @param filter String + * @param filter String * @param callBack EmojiFilteredCallBack - Get filtered emojis - * * @return List - List of {@link Emoji} */ public void getEmojiListFiltered(@NonNull String instance, @NonNull String filter, EmojiFilteredCallBack callBack) throws DBException { @@ -248,12 +239,12 @@ public class EmojiInstance implements Serializable { throw new DBException("db is null. Wrong initialization."); } new Thread(() -> { - List emojiArrayList= new ArrayList<>(); - List emojiFiltered= new ArrayList<>(); + List emojiArrayList = new ArrayList<>(); + List emojiFiltered = new ArrayList<>(); if (emojis == null || !emojis.containsKey(BaseMainActivity.currentInstance) || emojis.get(BaseMainActivity.currentInstance) == null) { try { Cursor c = db.query(Sqlite.TABLE_EMOJI_INSTANCE, null, Sqlite.COL_INSTANCE + " = '" + instance + "'", null, null, null, null, "1"); - emojiArrayList = cursorToEmojiList(c); + emojiArrayList = cursorToEmojiList(c); } catch (Exception e) { MastodonInstanceService mastodonInstanceService = init(instance); Call> emojiCall = mastodonInstanceService.customEmoji(); @@ -271,9 +262,9 @@ public class EmojiInstance implements Serializable { } else { emojiArrayList = emojis.get(instance); } - if(emojiArrayList != null && emojiArrayList.size() > 0 ) { - for(Emoji emoji: emojiArrayList) { - if(emoji.shortcode.contains(filter)) { + if (emojiArrayList != null && emojiArrayList.size() > 0) { + for (Emoji emoji : emojiArrayList) { + if (emoji.shortcode.contains(filter)) { emojiFiltered.add(emoji); } } @@ -311,4 +302,8 @@ public class EmojiInstance implements Serializable { } return filteredEmojis; } + + public interface EmojiFilteredCallBack { + void get(List emojiList); + } } diff --git a/app/src/main/java/app/fedilab/android/mastodon/client/entities/api/Tag.java b/app/src/main/java/app/fedilab/android/mastodon/client/entities/api/Tag.java index 5b2a5bbe..ac59de9e 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/client/entities/api/Tag.java +++ b/app/src/main/java/app/fedilab/android/mastodon/client/entities/api/Tag.java @@ -32,7 +32,8 @@ public class Tag implements Serializable { @SerializedName("following") public boolean following = false; - public Tag() {} + public Tag() { + } public Tag(String name) { this.name = name; diff --git a/app/src/main/java/app/fedilab/android/mastodon/client/entities/app/CachedBundle.java b/app/src/main/java/app/fedilab/android/mastodon/client/entities/app/CachedBundle.java new file mode 100644 index 00000000..d414269c --- /dev/null +++ b/app/src/main/java/app/fedilab/android/mastodon/client/entities/app/CachedBundle.java @@ -0,0 +1,413 @@ +package app.fedilab.android.mastodon.client.entities.app; +/* Copyright 2024 Thomas Schneider + * + * This file is a part of Fedilab + * + * This program is free software; you can redistribute it and/or modify it under the terms of the + * GNU General Public License as published by the Free Software Foundation; either version 3 of the + * License, or (at your option) any later version. + * + * Fedilab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even + * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General + * Public License for more details. + * + * You should have received a copy of the GNU General Public License along with Fedilab; if not, + * see . */ + +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; +import android.os.Parcel; +import android.util.Base64; + +import com.google.gson.annotations.SerializedName; + +import java.io.BufferedOutputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Calendar; +import java.util.Date; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +import app.fedilab.android.mastodon.client.entities.api.Account; +import app.fedilab.android.mastodon.client.entities.api.Status; +import app.fedilab.android.mastodon.exception.DBException; +import app.fedilab.android.mastodon.helper.Helper; +import app.fedilab.android.sqlite.Sqlite; + +/** + * Class that manages Bundle of Intent from database + */ +public class CachedBundle { + + public String id; + public Bundle bundle; + public CacheType cacheType; + public String instance; + public String user_id; + public String target_id; + public Date created_at; + + private SQLiteDatabase db; + + private transient Context context; + + public CachedBundle() { + } + + public CachedBundle(Context context) { + //Creation of the DB with tables + this.context = context; + this.db = Sqlite.getInstance(context.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); + } + + + public void insertAccountBundle(Account account, BaseAccount currentUser) throws DBException { + if (db == null) { + throw new DBException("db is null. Wrong initialization."); + } + ContentValues valuesAccount = new ContentValues(); + Bundle bundleAccount = new Bundle(); + if (account != null) { + bundleAccount.putSerializable(Helper.ARG_ACCOUNT, account); + valuesAccount.put(Sqlite.COL_BUNDLE, serializeBundle(bundleAccount)); + valuesAccount.put(Sqlite.COL_CREATED_AT, Helper.dateToString(new Date())); + valuesAccount.put(Sqlite.COL_TARGET_ID, account.id); + valuesAccount.put(Sqlite.COL_USER_ID, currentUser.user_id); + valuesAccount.put(Sqlite.COL_INSTANCE, currentUser.instance); + valuesAccount.put(Sqlite.COL_TYPE, CacheType.ACCOUNT.getValue()); + removeIntent(currentUser, account.id); + db.insertOrThrow(Sqlite.TABLE_INTENT, null, valuesAccount); + } + } + + /** + * Insert a bundle in db + * + * @param bundle {@link Bundle} + * @return long - db id + * @throws DBException exception with database + */ + private long insertIntent(Bundle bundle, BaseAccount currentUser) throws DBException { + if (db == null) { + throw new DBException("db is null. Wrong initialization."); + } + ContentValues values = new ContentValues(); + values.put(Sqlite.COL_BUNDLE, serializeBundle(bundle)); + values.put(Sqlite.COL_CREATED_AT, Helper.dateToString(new Date())); + values.put(Sqlite.COL_TYPE, CacheType.ARGS.getValue()); + if (bundle.containsKey(Helper.ARG_ACCOUNT) && currentUser != null) { + ContentValues valuesAccount = new ContentValues(); + Bundle bundleAccount = new Bundle(); + Account account = null; + try { + account = (Account) bundle.getSerializable(Helper.ARG_ACCOUNT); + }catch (ClassCastException ignored){} + if (account != null) { + bundleAccount.putSerializable(Helper.ARG_ACCOUNT, account); + valuesAccount.put(Sqlite.COL_BUNDLE, serializeBundle(bundleAccount)); + valuesAccount.put(Sqlite.COL_CREATED_AT, Helper.dateToString(new Date())); + valuesAccount.put(Sqlite.COL_TARGET_ID, account.id); + valuesAccount.put(Sqlite.COL_USER_ID, currentUser.user_id); + valuesAccount.put(Sqlite.COL_INSTANCE, currentUser.instance); + valuesAccount.put(Sqlite.COL_TYPE, CacheType.ACCOUNT.getValue()); + removeIntent(currentUser, account.id); + db.insertOrThrow(Sqlite.TABLE_INTENT, null, valuesAccount); + } + } + if (bundle.containsKey(Helper.ARG_STATUS) && currentUser != null) { + ContentValues valuesAccount = new ContentValues(); + Bundle bundleStatus = new Bundle(); + Status status = null; + try { + status = (Status) bundle.getSerializable(Helper.ARG_STATUS); + }catch (ClassCastException ignored){} + if (status != null) { + bundleStatus.putSerializable(Helper.ARG_STATUS, status); + valuesAccount.put(Sqlite.COL_BUNDLE, serializeBundle(bundleStatus)); + valuesAccount.put(Sqlite.COL_CREATED_AT, Helper.dateToString(new Date())); + valuesAccount.put(Sqlite.COL_TARGET_ID, status.id); + valuesAccount.put(Sqlite.COL_USER_ID, currentUser.user_id); + valuesAccount.put(Sqlite.COL_INSTANCE, currentUser.instance); + valuesAccount.put(Sqlite.COL_TYPE, CacheType.STATUS.getValue()); + removeIntent(currentUser, status.id); + db.insertOrThrow(Sqlite.TABLE_INTENT, null, valuesAccount); + } + } + try { + return db.insertOrThrow(Sqlite.TABLE_INTENT, null, values); + } catch (Exception e) { + e.printStackTrace(); + return -1; + } + } + + public void getBundle(long id, BaseAccount Account, BundleCallback callback) { + new Thread(() -> { + Bundle bundle = null; + try { + CachedBundle cachedBundle = getCachedBundle(String.valueOf(id)); + if (cachedBundle != null) { + bundle = cachedBundle.bundle; + if (bundle != null && bundle.containsKey(Helper.ARG_CACHED_ACCOUNT_ID)) { + Account cachedAccount = getCachedAccount(Account, bundle.getString(Helper.ARG_CACHED_ACCOUNT_ID)); + if (cachedAccount != null) { + bundle.putSerializable(Helper.ARG_ACCOUNT, cachedAccount); + } + } + if (bundle != null && bundle.containsKey(Helper.ARG_CACHED_STATUS_ID)) { + Status cachedStatus = getCachedStatus(Account, bundle.getString(Helper.ARG_CACHED_STATUS_ID)); + if (cachedStatus != null) { + bundle.putSerializable(Helper.ARG_STATUS, cachedStatus); + } + } + } + } catch (DBException ignored) { + } + if( bundle == null) { + bundle = new Bundle(); + } + Handler mainHandler = new Handler(Looper.getMainLooper()); + Bundle finalBundle = bundle; + Runnable myRunnable = () -> callback.get(finalBundle); + mainHandler.post(myRunnable); + }).start(); + } + + public void insertBundle(Bundle bundle, BaseAccount Account, BundleInsertCallback callback) { + new Thread(() -> { + long dbBundleId = -1; + try { + dbBundleId = insertIntent(bundle, Account); + } catch (DBException ignored) { + } + Handler mainHandler = new Handler(Looper.getMainLooper()); + long finalDbBundleId = dbBundleId; + Runnable myRunnable = () -> callback.inserted(finalDbBundleId); + mainHandler.post(myRunnable); + }).start(); + } + + /** + * Returns a bundle by targeted account id + * + * @param target_id String + * @return Account {@link Account} + */ + public Account getCachedAccount(BaseAccount account, String target_id) throws DBException { + if (db == null) { + throw new DBException("db is null. Wrong initialization."); + } + if (account == null || target_id == null) { + return null; + } + try { + Cursor c = db.query(Sqlite.TABLE_INTENT, null, Sqlite.COL_USER_ID + " = '" + account.user_id + "' AND " + + Sqlite.COL_INSTANCE + " = '" + account.instance + "' AND " + + Sqlite.COL_TYPE + " = '" + CacheType.ACCOUNT.getValue() + "' AND " + + Sqlite.COL_TARGET_ID + " = '" + target_id + "'", null, null, null, null, "1"); + CachedBundle cachedBundle = cursorToCachedBundle(c); + if (cachedBundle != null && cachedBundle.bundle.containsKey(Helper.ARG_ACCOUNT)) { + return (Account) cachedBundle.bundle.getSerializable(Helper.ARG_ACCOUNT); + } + } catch (Exception e) { + e.printStackTrace(); + return null; + } + return null; + } + + /** + * Returns a bundle by targeted status id + * + * @param target_id String + * @return Status {@link Status} + */ + private Status getCachedStatus(BaseAccount account, String target_id) throws DBException { + if (db == null) { + throw new DBException("db is null. Wrong initialization."); + } + if (account == null || target_id == null) { + return null; + } + try { + Cursor c = db.query(Sqlite.TABLE_INTENT, null, Sqlite.COL_USER_ID + " = '" + account.user_id + "' AND " + + Sqlite.COL_INSTANCE + " = '" + account.instance + "' AND " + + Sqlite.COL_TYPE + " = '" + CacheType.STATUS.getValue() + "' AND " + + Sqlite.COL_TARGET_ID + " = '" + target_id + "'", null, null, null, null, "1"); + CachedBundle cachedBundle = cursorToCachedBundle(c); + if (cachedBundle != null && cachedBundle.bundle.containsKey(Helper.ARG_STATUS)) { + return (Status) cachedBundle.bundle.getSerializable(Helper.ARG_STATUS); + } + } catch (Exception e) { + return null; + } + return null; + } + + /** + * Returns a bundle by its ID + * + * @param id String + * @return CachedBundle {@link CachedBundle} + */ + private CachedBundle getCachedBundle(String id) throws DBException { + if (db == null) { + throw new DBException("db is null. Wrong initialization."); + } + try { + Cursor c = db.query(Sqlite.TABLE_INTENT, null, Sqlite.COL_ID + " = \"" + id + "\"", null, null, null, null, "1"); + return cursorToCachedBundle(c); + } catch (Exception e) { + return null; + } + } + + /** + * Remove a bundle from db + */ + public void deleteOldIntent() throws DBException { + if (db == null) { + throw new DBException("db is null. Wrong initialization."); + } + Calendar cal = Calendar.getInstance(); + cal.setTime(new Date()); + cal.add(Calendar.DATE, -1); + Date date = cal.getTime(); + String dateStr = Helper.dateToString(date); + try { + db.delete(Sqlite.TABLE_INTENT, Sqlite.COL_CREATED_AT + " < ?", new String[]{dateStr}); + }catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * Remove a bundle from db + */ + private void removeIntent(BaseAccount account, String target_id) throws DBException { + if (db == null) { + throw new DBException("db is null. Wrong initialization."); + } + if (account == null || target_id == null) { + return; + } + db.delete(Sqlite.TABLE_INTENT, Sqlite.COL_USER_ID + " = '" + account.user_id + "' AND " + + Sqlite.COL_INSTANCE + " = '" + account.instance + "' AND " + + Sqlite.COL_TARGET_ID + " = '" + target_id + "'", null); + } + + /*** + * Method to hydrate an CachedBundle from database + * @param c Cursor + * @return CachedBundle {@link CachedBundle} + */ + private CachedBundle cursorToCachedBundle(Cursor c) { + //No element found + if (c.getCount() == 0) { + c.close(); + return null; + } + //Take the first element + c.moveToFirst(); + //New user + CachedBundle account = convertCursorToCachedBundle(c); + //Close the cursor + c.close(); + return account; + } + + /** + * Read cursor and hydrate without closing it + * + * @param c - Cursor + * @return Account + */ + private CachedBundle convertCursorToCachedBundle(Cursor c) { + CachedBundle cachedBundle = new CachedBundle(); + cachedBundle.id = c.getString(c.getColumnIndexOrThrow(Sqlite.COL_ID)); + cachedBundle.bundle = deserializeBundle(c.getString(c.getColumnIndexOrThrow(Sqlite.COL_BUNDLE))); + cachedBundle.user_id = c.getString(c.getColumnIndexOrThrow(Sqlite.COL_USER_ID)); + cachedBundle.instance = c.getString(c.getColumnIndexOrThrow(Sqlite.COL_INSTANCE)); + cachedBundle.target_id = c.getString(c.getColumnIndexOrThrow(Sqlite.COL_TARGET_ID)); + cachedBundle.cacheType = CacheType.valueOf(c.getString(c.getColumnIndexOrThrow(Sqlite.COL_TYPE))); + cachedBundle.created_at = Helper.stringToDate(context, c.getString(c.getColumnIndexOrThrow(Sqlite.COL_CREATED_AT))); + return cachedBundle; + } + + private String serializeBundle(final Bundle bundle) { + String base64 = null; + final Parcel parcel = Parcel.obtain(); + try { + parcel.writeBundle(bundle); + final ByteArrayOutputStream bos = new ByteArrayOutputStream(); + final GZIPOutputStream zos = new GZIPOutputStream(new BufferedOutputStream(bos)); + zos.write(parcel.marshall()); + zos.close(); + base64 = Base64.encodeToString(bos.toByteArray(), 0); + } catch (IOException e) { + e.printStackTrace(); + } finally { + parcel.recycle(); + } + return base64; + } + + private Bundle deserializeBundle(final String base64) { + Bundle bundle = null; + final Parcel parcel = Parcel.obtain(); + try { + final ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); + final byte[] buffer = new byte[1024]; + final GZIPInputStream zis = new GZIPInputStream(new ByteArrayInputStream(Base64.decode(base64, 0))); + int len; + while ((len = zis.read(buffer)) != -1) { + byteBuffer.write(buffer, 0, len); + } + zis.close(); + parcel.unmarshall(byteBuffer.toByteArray(), 0, byteBuffer.size()); + parcel.setDataPosition(0); + bundle = parcel.readBundle(getClass().getClassLoader()); + } catch (IOException e) { + e.printStackTrace(); + } finally { + parcel.recycle(); + } + return bundle; + } + + public enum CacheType { + @SerializedName("ARGS") + ARGS("ARGS"), + @SerializedName("ACCOUNT") + ACCOUNT("ACCOUNT"), + @SerializedName("STATUS") + STATUS("STATUS"); + + private final String value; + + CacheType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + } + + public interface BundleCallback { + void get(Bundle bundle); + } + + + public interface BundleInsertCallback { + void inserted(long bundleId); + } + +} diff --git a/app/src/main/java/app/fedilab/android/mastodon/helper/BlurHashDecoder.kt b/app/src/main/java/app/fedilab/android/mastodon/helper/BlurHashDecoder.kt index e192239f..9cc73818 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/helper/BlurHashDecoder.kt +++ b/app/src/main/java/app/fedilab/android/mastodon/helper/BlurHashDecoder.kt @@ -69,20 +69,20 @@ class BlurHashDecoder { val g = (value / 19) % 19 val b = value % 19 return floatArrayOf( - signedPow2((r - 9) / 9.0f) * maxAc, - signedPow2((g - 9) / 9.0f) * maxAc, - signedPow2((b - 9) / 9.0f) * maxAc + signedPow2((r - 9) / 9.0f) * maxAc, + signedPow2((g - 9) / 9.0f) * maxAc, + signedPow2((b - 9) / 9.0f) * maxAc ) } private fun signedPow2(value: Float) = value.pow(2f).withSign(value) private fun composeBitmap( - width: Int, - height: Int, - numCompX: Int, - numCompY: Int, - colors: Array + width: Int, + height: Int, + numCompX: Int, + numCompY: Int, + colors: Array ): Bitmap { val imageArray = IntArray(width * height) for (y in 0 until height) { @@ -100,7 +100,7 @@ class BlurHashDecoder { } } imageArray[x + width * y] = - Color.rgb(linearToSrgb(r), linearToSrgb(g), linearToSrgb(b)) + Color.rgb(linearToSrgb(r), linearToSrgb(g), linearToSrgb(b)) } } return Bitmap.createBitmap(imageArray, width, height, Bitmap.Config.ARGB_8888) @@ -116,12 +116,12 @@ class BlurHashDecoder { } private val charMap = listOf( - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', - 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', - 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', - 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '#', '$', '%', '*', '+', ',', - '-', '.', ':', ';', '=', '?', '@', '[', ']', '^', '_', '{', '|', '}', '~' + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', + 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', + 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', + 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '#', '$', '%', '*', '+', ',', + '-', '.', ':', ';', '=', '?', '@', '[', ']', '^', '_', '{', '|', '}', '~' ) - .mapIndexed { i, c -> c to i } - .toMap() + .mapIndexed { i, c -> c to i } + .toMap() } \ No newline at end of file diff --git a/app/src/main/java/app/fedilab/android/mastodon/helper/ComposeHelper.java b/app/src/main/java/app/fedilab/android/mastodon/helper/ComposeHelper.java index 57de14a3..dc275254 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/helper/ComposeHelper.java +++ b/app/src/main/java/app/fedilab/android/mastodon/helper/ComposeHelper.java @@ -23,7 +23,6 @@ import java.util.ArrayList; import java.util.regex.Matcher; - public class ComposeHelper { @@ -44,13 +43,13 @@ public class ComposeHelper { Matcher matcher = mentionPatternALL.matcher(content); while (matcher.find()) { String mentionLong = matcher.group(1); - if(mentionLong != null) { + if (mentionLong != null) { if (!mentions.contains(mentionLong)) { mentions.add(mentionLong); } } String mentionShort = matcher.group(2); - if(mentionShort != null) { + if (mentionShort != null) { if (!mentions.contains(mentionShort)) { mentions.add(mentionShort); } diff --git a/app/src/main/java/app/fedilab/android/mastodon/helper/CrossActionHelper.java b/app/src/main/java/app/fedilab/android/mastodon/helper/CrossActionHelper.java index 49b525c4..35a236ac 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/helper/CrossActionHelper.java +++ b/app/src/main/java/app/fedilab/android/mastodon/helper/CrossActionHelper.java @@ -14,6 +14,8 @@ package app.fedilab.android.mastodon.helper; * You should have received a copy of the GNU General Public License along with Fedilab; if not, * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; + import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; @@ -44,6 +46,7 @@ import app.fedilab.android.mastodon.client.entities.api.Results; import app.fedilab.android.mastodon.client.entities.api.Status; import app.fedilab.android.mastodon.client.entities.app.Account; import app.fedilab.android.mastodon.client.entities.app.BaseAccount; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.exception.DBException; import app.fedilab.android.mastodon.ui.drawer.AccountsSearchAdapter; import app.fedilab.android.mastodon.viewmodel.mastodon.AccountsVM; @@ -183,77 +186,89 @@ public class CrossActionHelper { statusesVM = new ViewModelProvider((ViewModelStoreOwner) context).get("crossactions", StatusesVM.class); } switch (actionType) { - case MUTE_ACTION: + case MUTE_ACTION -> { assert accountsVM != null; accountsVM.mute(ownerAccount.instance, ownerAccount.token, targetedAccount.id, true, 0) .observe((LifecycleOwner) context, relationShip -> Toasty.info(context, context.getString(R.string.toast_mute), Toasty.LENGTH_SHORT).show()); - break; - case UNMUTE_ACTION: + } + case UNMUTE_ACTION -> { assert accountsVM != null; accountsVM.unmute(ownerAccount.instance, ownerAccount.token, targetedAccount.id) .observe((LifecycleOwner) context, relationShip -> Toasty.info(context, context.getString(R.string.toast_unmute), Toasty.LENGTH_SHORT).show()); - break; - case BLOCK_ACTION: + } + case BLOCK_ACTION -> { assert accountsVM != null; accountsVM.block(ownerAccount.instance, ownerAccount.token, targetedAccount.id) .observe((LifecycleOwner) context, relationShip -> Toasty.info(context, context.getString(R.string.toast_block), Toasty.LENGTH_SHORT).show()); - break; - case UNBLOCK_ACTION: + } + case UNBLOCK_ACTION -> { assert accountsVM != null; accountsVM.unblock(ownerAccount.instance, ownerAccount.token, targetedAccount.id) .observe((LifecycleOwner) context, relationShip -> Toasty.info(context, context.getString(R.string.toast_unblock), Toasty.LENGTH_SHORT).show()); - break; - case FOLLOW_ACTION: + } + case FOLLOW_ACTION -> { assert accountsVM != null; accountsVM.follow(ownerAccount.instance, ownerAccount.token, targetedAccount.id, true, false, null) .observe((LifecycleOwner) context, relationShip -> Toasty.info(context, context.getString(R.string.toast_follow), Toasty.LENGTH_SHORT).show()); - break; - case UNFOLLOW_ACTION: + } + case UNFOLLOW_ACTION -> { assert accountsVM != null; accountsVM.unfollow(ownerAccount.instance, ownerAccount.token, targetedAccount.id) .observe((LifecycleOwner) context, relationShip -> Toasty.info(context, context.getString(R.string.toast_unfollow), Toasty.LENGTH_SHORT).show()); - break; - case FAVOURITE_ACTION: + } + case FAVOURITE_ACTION -> { assert statusesVM != null; statusesVM.favourite(ownerAccount.instance, ownerAccount.token, targetedStatus.id) .observe((LifecycleOwner) context, status -> Toasty.info(context, context.getString(R.string.toast_favourite), Toasty.LENGTH_SHORT).show()); - break; - case UNFAVOURITE_ACTION: + } + case UNFAVOURITE_ACTION -> { assert statusesVM != null; statusesVM.unFavourite(ownerAccount.instance, ownerAccount.token, targetedStatus.id) .observe((LifecycleOwner) context, status -> Toasty.info(context, context.getString(R.string.toast_unfavourite), Toasty.LENGTH_SHORT).show()); - break; - case BOOKMARK_ACTION: + } + case BOOKMARK_ACTION -> { assert statusesVM != null; statusesVM.bookmark(ownerAccount.instance, ownerAccount.token, targetedStatus.id) .observe((LifecycleOwner) context, status -> Toasty.info(context, context.getString(R.string.toast_bookmark), Toasty.LENGTH_SHORT).show()); - break; - case UNBOOKMARK_ACTION: + } + case UNBOOKMARK_ACTION -> { assert statusesVM != null; statusesVM.unBookmark(ownerAccount.instance, ownerAccount.token, targetedStatus.id) .observe((LifecycleOwner) context, status -> Toasty.info(context, context.getString(R.string.toast_unbookmark), Toasty.LENGTH_SHORT).show()); - break; - case REBLOG_ACTION: + } + case REBLOG_ACTION -> { assert statusesVM != null; statusesVM.reblog(ownerAccount.instance, ownerAccount.token, targetedStatus.id, null) .observe((LifecycleOwner) context, status -> Toasty.info(context, context.getString(R.string.toast_reblog), Toasty.LENGTH_SHORT).show()); - break; - case UNREBLOG_ACTION: + } + case UNREBLOG_ACTION -> { assert statusesVM != null; statusesVM.unReblog(ownerAccount.instance, ownerAccount.token, targetedStatus.id) .observe((LifecycleOwner) context, status -> Toasty.info(context, context.getString(R.string.toast_unreblog), Toasty.LENGTH_SHORT).show()); - break; - case REPLY_ACTION: + } + case REPLY_ACTION -> { Intent intent = new Intent(context, ComposeActivity.class); - intent.putExtra(Helper.ARG_STATUS_REPLY, targetedStatus); - intent.putExtra(Helper.ARG_ACCOUNT, ownerAccount); - context.startActivity(intent); - break; - case COMPOSE: + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS_REPLY, targetedStatus); + args.putSerializable(Helper.ARG_ACCOUNT, ownerAccount); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); + } + case COMPOSE -> { Intent intentCompose = new Intent(context, ComposeActivity.class); - intentCompose.putExtra(Helper.ARG_ACCOUNT, ownerAccount); - context.startActivity(intentCompose); - break; + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, ownerAccount); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intentCompose.putExtras(bundle); + context.startActivity(intentCompose); + }); + } } } @@ -430,10 +445,15 @@ public class CrossActionHelper { final BaseAccount account = accountArray[which]; Intent intentToot = new Intent(context, ComposeActivity.class); bundle.putSerializable(Helper.ARG_ACCOUNT, account); - intentToot.putExtras(bundle); - context.startActivity(intentToot); - ((BaseActivity) context).finish(); - dialog.dismiss(); + new CachedBundle(context).insertBundle(bundle, currentAccount, bundleId -> { + Bundle bundleCached = new Bundle(); + bundleCached.putLong(Helper.ARG_INTENT_ID, bundleId); + intentToot.putExtras(bundleCached); + context.startActivity(intentToot); + ((BaseActivity) context).finish(); + dialog.dismiss(); + }); + }); builderSingle.show(); } diff --git a/app/src/main/java/app/fedilab/android/mastodon/helper/Helper.java b/app/src/main/java/app/fedilab/android/mastodon/helper/Helper.java index b2069db7..fa445643 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/helper/Helper.java +++ b/app/src/main/java/app/fedilab/android/mastodon/helper/Helper.java @@ -78,7 +78,6 @@ import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.browser.customtabs.CustomTabColorSchemeParams; import androidx.browser.customtabs.CustomTabsIntent; -import androidx.core.app.ActivityOptionsCompat; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import androidx.core.content.ContextCompat; @@ -89,7 +88,6 @@ import androidx.fragment.app.FragmentTransaction; import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.ViewModelProvider; import androidx.lifecycle.ViewModelStoreOwner; - import androidx.preference.PreferenceManager; import androidx.recyclerview.widget.LinearLayoutManager; @@ -157,6 +155,7 @@ import app.fedilab.android.mastodon.client.entities.api.Attachment; import app.fedilab.android.mastodon.client.entities.api.Status; import app.fedilab.android.mastodon.client.entities.app.Account; import app.fedilab.android.mastodon.client.entities.app.BaseAccount; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.client.entities.app.ReleaseNote; import app.fedilab.android.mastodon.client.entities.app.Timeline; import app.fedilab.android.mastodon.exception.DBException; @@ -210,6 +209,8 @@ public class Helper { public static final String RECEIVE_REDRAW_PROFILE = "RECEIVE_REDRAW_PROFILE"; public static final String ARG_TIMELINE_TYPE = "ARG_TIMELINE_TYPE"; + + public static final String ARG_INTENT_ID = "ARG_INTENT_ID"; public static final String ARG_PEERTUBE_NAV_REMOTE = "ARG_PEERTUBE_NAV_REMOTE"; public static final String ARG_REMOTE_INSTANCE_STRING = "ARG_REMOTE_INSTANCE_STRING"; @@ -241,6 +242,8 @@ public class Helper { public static final String ARG_STATUS_REPLY_ID = "ARG_STATUS_REPLY_ID"; public static final String ARG_ACCOUNT = "ARG_ACCOUNT"; public static final String ARG_ACCOUNT_ID = "ARG_ACCOUNT_ID"; + public static final String ARG_CACHED_ACCOUNT_ID = "ARG_CACHED_ACCOUNT_ID"; + public static final String ARG_CACHED_STATUS_ID = "ARG_CACHED_STATUS_ID"; public static final String ARG_ADMIN_DOMAINBLOCK = "ARG_ADMIN_DOMAINBLOCK"; public static final String ARG_ADMIN_DOMAINBLOCK_DELETE = "ARG_ADMIN_DOMAINBLOCK_DELETE"; public static final String FEDILAB_MUTED_HASHTAGS = "Fedilab muted hashtags"; @@ -843,7 +846,7 @@ public class Helper { @SuppressLint("DefaultLocale") public static String withSuffix(long count) { - if (count < 1000) return "" + count; + if (count < 1000) return String.valueOf(count); int exp = (int) (Math.log(count) / Math.log(1000)); Locale locale = null; try { @@ -869,13 +872,17 @@ public class Helper { */ public static void sendToastMessage(Context context, String type, String content) { Intent intentBC = new Intent(context, ToastMessage.class); - Bundle b = new Bundle(); - b.putString(RECEIVE_TOAST_TYPE, type); - b.putString(RECEIVE_TOAST_CONTENT, content); + Bundle args = new Bundle(); + args.putString(RECEIVE_TOAST_TYPE, type); + args.putString(RECEIVE_TOAST_CONTENT, content); intentBC.setAction(Helper.RECEIVE_TOAST_MESSAGE); - intentBC.putExtras(b); - intentBC.setPackage(BuildConfig.APPLICATION_ID); - context.sendBroadcast(intentBC); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intentBC.putExtras(bundle); + intentBC.setPackage(BuildConfig.APPLICATION_ID); + context.sendBroadcast(intentBC); + }); } /** @@ -995,8 +1002,7 @@ public class Helper { if (context == null) { return false; } - if (context instanceof Activity) { - final Activity activity = (Activity) context; + if (context instanceof Activity activity) { return !activity.isDestroyed() && !activity.isFinishing(); } return true; @@ -1512,12 +1518,16 @@ public class Helper { * @param activity - Activity */ public static void recreateMainActivity(Activity activity) { - Bundle b = new Bundle(); - b.putBoolean(Helper.RECEIVE_RECREATE_ACTIVITY, true); + Bundle args = new Bundle(); + args.putBoolean(Helper.RECEIVE_RECREATE_ACTIVITY, true); Intent intentBD = new Intent(Helper.BROADCAST_DATA); - intentBD.putExtras(b); - intentBD.setPackage(BuildConfig.APPLICATION_ID); - activity.sendBroadcast(intentBD); + new CachedBundle(activity).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intentBD.putExtras(bundle); + intentBD.setPackage(BuildConfig.APPLICATION_ID); + activity.sendBroadcast(intentBD); + }); } public static void showKeyboard(Context context, View view) { @@ -1554,49 +1564,50 @@ public class Helper { String channelTitle; switch (notifType) { - case FAV: + case FAV -> { channelId = "channel_favourite"; channelTitle = context.getString(R.string.channel_notif_fav); - break; - case FOLLLOW: + } + case FOLLLOW -> { channelId = "channel_follow"; channelTitle = context.getString(R.string.channel_notif_follow); - break; - case MENTION: + } + case MENTION -> { channelId = "channel_mention"; channelTitle = context.getString(R.string.channel_notif_mention); - break; - case POLL: + } + case POLL -> { channelId = "channel_poll"; channelTitle = context.getString(R.string.channel_notif_poll); - break; - case BACKUP: + } + case BACKUP -> { channelId = "channel_backup"; channelTitle = context.getString(R.string.channel_notif_backup); - break; - case STORE: + } + case STORE -> { channelId = "channel_media"; channelTitle = context.getString(R.string.channel_notif_media); - break; - case TOOT: + } + case TOOT -> { channelId = "channel_status"; channelTitle = context.getString(R.string.channel_notif_status); - break; - case UPDATE: + } + case UPDATE -> { channelId = "channel_update"; channelTitle = context.getString(R.string.channel_notif_update); - break; - case SIGN_UP: + } + case SIGN_UP -> { channelId = "channel_signup"; channelTitle = context.getString(R.string.channel_notif_signup); - break; - case REPORT: + } + case REPORT -> { channelId = "channel_report"; channelTitle = context.getString(R.string.channel_notif_report); - break; - default: + } + default -> { channelId = "channel_boost"; channelTitle = context.getString(R.string.channel_notif_boost); + } } NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, channelId) .setSmallIcon(getNotificationIcon(context)).setTicker(message); @@ -1605,31 +1616,25 @@ public class Helper { message = message.substring(0, 499) + "…"; } }*/ - notificationBuilder.setGroup(account.mastodon_account != null ? account.mastodon_account.username + "@" + account.instance : "" + "@" + account.instance) + notificationBuilder.setGroup(account.mastodon_account != null ? account.mastodon_account.username + "@" + account.instance : "@" + account.instance) .setContentIntent(pIntent) .setContentText(message); int ledColour = Color.BLUE; int prefColor; prefColor = Integer.parseInt(sharedpreferences.getString(context.getString(R.string.SET_LED_COLOUR_VAL_N), String.valueOf(LED_COLOUR))); switch (prefColor) { - case 1: // CYAN - ledColour = Color.CYAN; - break; - case 2: // MAGENTA - ledColour = Color.MAGENTA; - break; - case 3: // GREEN - ledColour = Color.GREEN; - break; - case 4: // RED - ledColour = Color.RED; - break; - case 5: // YELLOW - ledColour = Color.YELLOW; - break; - case 6: // WHITE - ledColour = Color.WHITE; - break; + case 1 -> // CYAN + ledColour = Color.CYAN; + case 2 -> // MAGENTA + ledColour = Color.MAGENTA; + case 3 -> // GREEN + ledColour = Color.GREEN; + case 4 -> // RED + ledColour = Color.RED; + case 5 -> // YELLOW + ledColour = Color.YELLOW; + case 6 -> // WHITE + ledColour = Color.WHITE; } @@ -1673,7 +1678,7 @@ public class Helper { .setLargeIcon(icon) .setSmallIcon(getNotificationIcon(context)) .setStyle(new NotificationCompat.BigTextStyle().bigText(message)) - .setGroup(account.mastodon_account != null ? account.mastodon_account.username + "@" + account.instance : "" + "@" + account.instance) + .setGroup(account.mastodon_account != null ? account.mastodon_account.username + "@" + account.instance : "@" + account.instance) .setGroupSummary(true) .build(); @@ -1922,10 +1927,14 @@ public class Helper { binding.accountUn.setText(account.acct); binding.accountPp.setOnClickListener(v -> { Intent intent = new Intent(activity, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, account); - intent.putExtras(b); - activity.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, account); + new CachedBundle(activity).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + activity.startActivity(intent); + }); }); AccountsVM accountsVM = new ViewModelProvider((ViewModelStoreOwner) activity).get(AccountsVM.class); diff --git a/app/src/main/java/app/fedilab/android/mastodon/helper/PinnedTimelineHelper.java b/app/src/main/java/app/fedilab/android/mastodon/helper/PinnedTimelineHelper.java index 1722a8b4..d1b924b6 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/helper/PinnedTimelineHelper.java +++ b/app/src/main/java/app/fedilab/android/mastodon/helper/PinnedTimelineHelper.java @@ -679,8 +679,7 @@ public class PinnedTimelineHelper { popup.setOnDismissListener(menu1 -> { if (activityMainBinding.viewPager.getAdapter() != null && activityMainBinding.tabLayout.getSelectedTabPosition() != -1) { Fragment fragment = (Fragment) activityMainBinding.viewPager.getAdapter().instantiateItem(activityMainBinding.viewPager, activityMainBinding.tabLayout.getSelectedTabPosition()); - if (fragment instanceof FragmentMastodonTimeline && fragment.isVisible()) { - FragmentMastodonTimeline fragmentMastodonTimeline = ((FragmentMastodonTimeline) fragment); + if (fragment instanceof FragmentMastodonTimeline fragmentMastodonTimeline && fragment.isVisible()) { fragmentMastodonTimeline.refreshAllAdapters(); } } diff --git a/app/src/main/java/app/fedilab/android/mastodon/helper/SpannableHelper.java b/app/src/main/java/app/fedilab/android/mastodon/helper/SpannableHelper.java index de58d977..87cb773f 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/helper/SpannableHelper.java +++ b/app/src/main/java/app/fedilab/android/mastodon/helper/SpannableHelper.java @@ -86,6 +86,7 @@ import app.fedilab.android.mastodon.client.entities.api.Emoji; import app.fedilab.android.mastodon.client.entities.api.Filter; import app.fedilab.android.mastodon.client.entities.api.Mention; import app.fedilab.android.mastodon.client.entities.api.Status; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.client.entities.app.MarkdownConverter; import app.fedilab.android.mastodon.ui.drawer.StatusAdapter; import app.fedilab.android.mastodon.viewmodel.mastodon.FiltersVM; @@ -154,7 +155,7 @@ public class SpannableHelper { } else { initialContent = new SpannableString(text); } - boolean markdownSupport = sharedpreferences.getBoolean(context.getString(R.string.SET_MARKDOWN_SUPPORT), true); + boolean markdownSupport = sharedpreferences.getBoolean(context.getString(R.string.SET_MARKDOWN_SUPPORT), false); //Get all links SpannableStringBuilder content; if (markdownSupport && convertMarkdown) { @@ -278,19 +279,23 @@ public class SpannableHelper { public void onClick(@NonNull View textView) { textView.setTag(CLICKABLE_SPAN); Intent intent; - Bundle b; + Bundle args; if (word.startsWith("#")) { intent = new Intent(context, HashTagActivity.class); - b = new Bundle(); - b.putString(Helper.ARG_SEARCH_KEYWORD, word.trim()); - intent.putExtras(b); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(intent); + args = new Bundle(); + args.putString(Helper.ARG_SEARCH_KEYWORD, word.trim()); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(intent); + }); + } else if (word.startsWith("@")) { intent = new Intent(context, ProfileActivity.class); - b = new Bundle(); + args = new Bundle(); Mention targetedMention = null; - for (Mention mention : mentions) { if (word.compareToIgnoreCase("@" + mention.username) == 0) { targetedMention = mention; @@ -298,20 +303,24 @@ public class SpannableHelper { } } if (targetedMention != null) { - b.putString(Helper.ARG_USER_ID, targetedMention.id); + args.putString(Helper.ARG_USER_ID, targetedMention.id); } else { - b.putString(Helper.ARG_MENTION, word); + args.putString(Helper.ARG_MENTION, word); } - intent.putExtras(b); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(intent); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(intent); + }); } } @Override public void updateDrawState(@NonNull TextPaint ds) { super.updateDrawState(ds); - if(!underlineLinks) { + if (!underlineLinks) { ds.setUnderlineText(status != null && status.underlined); } if (linkColor != -1) { @@ -603,7 +612,7 @@ public class SpannableHelper { @Override public void updateDrawState(@NonNull TextPaint ds) { super.updateDrawState(ds); - if(!underlineLinks) { + if (!underlineLinks) { ds.setUnderlineText(status != null && status.underlined); } if (linkColor != -1) { @@ -626,9 +635,15 @@ public class SpannableHelper { @Override public void federatedStatus(Status status) { Intent intent = new Intent(context, ContextActivity.class); - intent.putExtra(Helper.ARG_STATUS, status); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS, status); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(intent); + }); } @Override @@ -644,11 +659,15 @@ public class SpannableHelper { @Override public void federatedAccount(Account account) { Intent intent = new Intent(context, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, account); - intent.putExtras(b); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, account); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(intent); + }); } }); } @@ -658,9 +677,15 @@ public class SpannableHelper { @Override public void federatedStatus(Status status) { Intent intent = new Intent(context, ContextActivity.class); - intent.putExtra(Helper.ARG_STATUS, status); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS, status); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(intent); + }); } @Override @@ -676,11 +701,15 @@ public class SpannableHelper { @Override public void federatedAccount(Account account) { Intent intent = new Intent(context, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, account); - intent.putExtras(b); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, account); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(intent); + }); } }); } @@ -690,9 +719,15 @@ public class SpannableHelper { @Override public void federatedStatus(Status status) { Intent intent = new Intent(context, ContextActivity.class); - intent.putExtra(Helper.ARG_STATUS, status); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS, status); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(intent); + }); } @Override @@ -708,11 +743,15 @@ public class SpannableHelper { @Override public void federatedAccount(Account account) { Intent intent = new Intent(context, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, account); - intent.putExtras(b); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, account); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(intent); + }); } }); } @@ -750,7 +789,7 @@ public class SpannableHelper { @Override public void updateDrawState(@NonNull TextPaint ds) { super.updateDrawState(ds); - if(!underlineLinks) { + if (!underlineLinks) { ds.setUnderlineText(status != null && status.underlined); } if (linkColor != -1) { @@ -890,16 +929,20 @@ public class SpannableHelper { @Override public void onClick(@NonNull View textView) { Intent intent = new Intent(context, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, account.moved); - intent.putExtras(b); - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, account.moved); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); } @Override public void updateDrawState(@NonNull TextPaint ds) { super.updateDrawState(ds); - if(!underlineLinks) { + if (!underlineLinks) { ds.setUnderlineText(false); } if (linkColor != -1) { diff --git a/app/src/main/java/app/fedilab/android/mastodon/helper/ThemeHelper.java b/app/src/main/java/app/fedilab/android/mastodon/helper/ThemeHelper.java index 51d1b8d0..460a9ff8 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/helper/ThemeHelper.java +++ b/app/src/main/java/app/fedilab/android/mastodon/helper/ThemeHelper.java @@ -176,12 +176,10 @@ public class ThemeHelper { String[] list; try { list = context.getAssets().list("themes/contributors"); - if (list.length > 0) { - for (String file : list) { - InputStream is = context.getAssets().open("themes/contributors/" + file); - LinkedHashMap data = readCSVFile(is); - linkedHashMaps.add(data); - } + for (String file : list) { + InputStream is = context.getAssets().open("themes/contributors/" + file); + LinkedHashMap data = readCSVFile(is); + linkedHashMaps.add(data); } } catch (IOException e) { e.printStackTrace(); diff --git a/app/src/main/java/app/fedilab/android/mastodon/helper/TranslateHelper.java b/app/src/main/java/app/fedilab/android/mastodon/helper/TranslateHelper.java index 0f159528..7f91a364 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/helper/TranslateHelper.java +++ b/app/src/main/java/app/fedilab/android/mastodon/helper/TranslateHelper.java @@ -81,7 +81,7 @@ public class TranslateHelper { String translate; if (translates == null || translates.size() <= 1) { translate = MyTransL.getLocale(); - if(translates != null && translates.size() == 1 ) { + if (translates != null && translates.size() == 1) { for (String val : translates) { translate = val; } diff --git a/app/src/main/java/app/fedilab/android/mastodon/helper/itemtouchhelper/SimpleItemTouchHelperCallback.java b/app/src/main/java/app/fedilab/android/mastodon/helper/itemtouchhelper/SimpleItemTouchHelperCallback.java index a43c817a..9548f6cb 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/helper/itemtouchhelper/SimpleItemTouchHelperCallback.java +++ b/app/src/main/java/app/fedilab/android/mastodon/helper/itemtouchhelper/SimpleItemTouchHelperCallback.java @@ -102,9 +102,8 @@ public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback { public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) { // We only want the active item to change if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) { - if (viewHolder instanceof ItemTouchHelperViewHolder) { + if (viewHolder instanceof ItemTouchHelperViewHolder itemViewHolder) { // Let the view holder know that this item is being moved or dragged - ItemTouchHelperViewHolder itemViewHolder = (ItemTouchHelperViewHolder) viewHolder; itemViewHolder.onItemSelected(); } } @@ -118,9 +117,8 @@ public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback { viewHolder.itemView.setAlpha(ALPHA_FULL); - if (viewHolder instanceof ItemTouchHelperViewHolder) { + if (viewHolder instanceof ItemTouchHelperViewHolder itemViewHolder) { // Tell the view holder it's time to restore the idle state - ItemTouchHelperViewHolder itemViewHolder = (ItemTouchHelperViewHolder) viewHolder; itemViewHolder.onItemClear(); } } diff --git a/app/src/main/java/app/fedilab/android/mastodon/helper/settings/TimePreferenceDialogFragment.java b/app/src/main/java/app/fedilab/android/mastodon/helper/settings/TimePreferenceDialogFragment.java index b7538565..4afa907a 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/helper/settings/TimePreferenceDialogFragment.java +++ b/app/src/main/java/app/fedilab/android/mastodon/helper/settings/TimePreferenceDialogFragment.java @@ -73,8 +73,7 @@ public class TimePreferenceDialogFragment extends PreferenceDialogFragmentCompat // Generate value to save String time = hour + ":" + minute; DialogPreference preference = getPreference(); - if (preference instanceof TimePreference) { - TimePreference timePreference = ((TimePreference) preference); + if (preference instanceof TimePreference timePreference) { if (timePreference.callChangeListener(time)) { timePreference.setTime(time); } diff --git a/app/src/main/java/app/fedilab/android/mastodon/imageeditor/EditImageActivity.java b/app/src/main/java/app/fedilab/android/mastodon/imageeditor/EditImageActivity.java index e97d8bf5..4d97631e 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/imageeditor/EditImageActivity.java +++ b/app/src/main/java/app/fedilab/android/mastodon/imageeditor/EditImageActivity.java @@ -1,6 +1,8 @@ package app.fedilab.android.mastodon.imageeditor; +import static app.fedilab.android.BaseMainActivity.currentAccount; + import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; @@ -22,7 +24,6 @@ import androidx.constraintlayout.widget.ConstraintSet; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.exifinterface.media.ExifInterface; - import androidx.recyclerview.widget.LinearLayoutManager; import androidx.transition.ChangeBounds; import androidx.transition.TransitionManager; @@ -42,6 +43,7 @@ import java.io.InputStream; import app.fedilab.android.BuildConfig; import app.fedilab.android.R; import app.fedilab.android.databinding.ActivityEditImageBinding; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.helper.CirclesDrawingView; import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.imageeditor.base.BaseActivity; @@ -284,7 +286,8 @@ public class EditImageActivity extends BaseActivity implements OnPhotoEditorList binding.photoEditorView.getSource().setImageURI(Uri.fromFile(new File(imagePath))); if (exit) { Intent intentImage = new Intent(Helper.INTENT_SEND_MODIFIED_IMAGE); - intentImage.putExtra("imgpath", imagePath); + Bundle args = new Bundle(); + args.putString("imgpath", imagePath); CirclesDrawingView.CircleArea circleArea = binding.focusCircle.getTouchedCircle(); if (circleArea != null) { //Dimension of the editor containing the image @@ -324,13 +327,16 @@ public class EditImageActivity extends BaseActivity implements OnPhotoEditorList } else if (focusY < -1) { focusY = -1; } - intentImage.putExtra("focusX", focusX); - intentImage.putExtra("focusY", focusY); - + args.putFloat("focusX", focusX); + args.putFloat("focusY", focusY); } - intentImage.setPackage(BuildConfig.APPLICATION_ID); - sendBroadcast(intentImage); - finish(); + new CachedBundle(EditImageActivity.this).insertBundle(args, currentAccount, bundleId -> { + intentImage.putExtras(args); + intentImage.setPackage(BuildConfig.APPLICATION_ID); + sendBroadcast(intentImage); + finish(); + }); + } } diff --git a/app/src/main/java/app/fedilab/android/mastodon/imageeditor/base/BaseActivity.java b/app/src/main/java/app/fedilab/android/mastodon/imageeditor/base/BaseActivity.java index 5d8f03f9..47acdfa3 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/imageeditor/base/BaseActivity.java +++ b/app/src/main/java/app/fedilab/android/mastodon/imageeditor/base/BaseActivity.java @@ -47,10 +47,8 @@ public class BaseActivity extends AppCompatActivity { @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); - switch (requestCode) { - case READ_WRITE_STORAGE: - isPermissionGranted(grantResults[0] == PackageManager.PERMISSION_GRANTED, permissions[0]); - break; + if (requestCode == READ_WRITE_STORAGE) { + isPermissionGranted(grantResults[0] == PackageManager.PERMISSION_GRANTED, permissions[0]); } } diff --git a/app/src/main/java/app/fedilab/android/mastodon/jobs/ComposeWorker.java b/app/src/main/java/app/fedilab/android/mastodon/jobs/ComposeWorker.java index 2a80e3af..e8ddb9d4 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/jobs/ComposeWorker.java +++ b/app/src/main/java/app/fedilab/android/mastodon/jobs/ComposeWorker.java @@ -32,7 +32,6 @@ import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.core.app.NotificationCompat; - import androidx.preference.PreferenceManager; import androidx.work.Data; import androidx.work.ForegroundInfo; @@ -61,6 +60,7 @@ import app.fedilab.android.mastodon.client.entities.api.ScheduledStatus; import app.fedilab.android.mastodon.client.entities.api.Status; import app.fedilab.android.mastodon.client.entities.app.Account; import app.fedilab.android.mastodon.client.entities.app.BaseAccount; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.client.entities.app.CamelTag; import app.fedilab.android.mastodon.client.entities.app.PostState; import app.fedilab.android.mastodon.client.entities.app.StatusDraft; @@ -224,14 +224,24 @@ public class ComposeWorker extends Worker { } Call statusCall; if (error) { - Bundle b = new Bundle(); - b.putBoolean(Helper.RECEIVE_COMPOSE_ERROR_MESSAGE, true); + Bundle args = new Bundle(); + args.putBoolean(Helper.RECEIVE_COMPOSE_ERROR_MESSAGE, true); Intent intentBD = new Intent(Helper.INTENT_COMPOSE_ERROR_MESSAGE); - b.putSerializable(Helper.RECEIVE_ERROR_MESSAGE, context.getString(R.string.media_cannot_be_uploaded)); - b.putSerializable(Helper.ARG_STATUS_DRAFT, dataPost.statusDraft); - intentBD.putExtras(b); - intentBD.setPackage(BuildConfig.APPLICATION_ID); - context.sendBroadcast(intentBD); + args.putSerializable(Helper.RECEIVE_ERROR_MESSAGE, context.getString(R.string.media_cannot_be_uploaded)); + args.putSerializable(Helper.ARG_STATUS_DRAFT, dataPost.statusDraft); + BaseAccount account = null; + try { + account = new Account(context).getAccountByToken(dataPost.token); + } catch (DBException e) { + e.printStackTrace(); + } + new CachedBundle(context).insertBundle(args, account, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intentBD.putExtras(bundle); + intentBD.setPackage(BuildConfig.APPLICATION_ID); + context.sendBroadcast(intentBD); + }); return; } if (statuses.get(i).local_only) { @@ -305,30 +315,51 @@ public class ComposeWorker extends Worker { } } } else if (statusResponse.errorBody() != null) { - Bundle b = new Bundle(); - b.putBoolean(Helper.RECEIVE_COMPOSE_ERROR_MESSAGE, true); + Bundle args = new Bundle(); + args.putBoolean(Helper.RECEIVE_COMPOSE_ERROR_MESSAGE, true); Intent intentBD = new Intent(Helper.INTENT_COMPOSE_ERROR_MESSAGE); - b.putSerializable(Helper.ARG_STATUS_DRAFT, dataPost.statusDraft); + args.putSerializable(Helper.ARG_STATUS_DRAFT, dataPost.statusDraft); String err = statusResponse.errorBody().string(); if (err.contains("{\"error\":\"")) { err = err.replaceAll("\\{\"error\":\"(.*)\"\\}", "$1"); } - b.putSerializable(Helper.RECEIVE_ERROR_MESSAGE, err); - intentBD.putExtras(b); - intentBD.setPackage(BuildConfig.APPLICATION_ID); - context.sendBroadcast(intentBD); + args.putSerializable(Helper.RECEIVE_ERROR_MESSAGE, err); + + BaseAccount account = null; + try { + account = new Account(context).getAccountByToken(dataPost.token); + } catch (DBException e) { + e.printStackTrace(); + } + new CachedBundle(context).insertBundle(args, account, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intentBD.putExtras(bundle); + intentBD.setPackage(BuildConfig.APPLICATION_ID); + context.sendBroadcast(intentBD); + }); return; } } catch (IOException e) { e.printStackTrace(); - Bundle b = new Bundle(); - b.putBoolean(Helper.RECEIVE_COMPOSE_ERROR_MESSAGE, true); - b.putSerializable(Helper.ARG_STATUS_DRAFT, dataPost.statusDraft); + Bundle args = new Bundle(); + args.putBoolean(Helper.RECEIVE_COMPOSE_ERROR_MESSAGE, true); + args.putSerializable(Helper.ARG_STATUS_DRAFT, dataPost.statusDraft); Intent intentBD = new Intent(Helper.INTENT_COMPOSE_ERROR_MESSAGE); - b.putSerializable(Helper.RECEIVE_ERROR_MESSAGE, e.getMessage()); - intentBD.putExtras(b); - intentBD.setPackage(BuildConfig.APPLICATION_ID); - context.sendBroadcast(intentBD); + args.putSerializable(Helper.RECEIVE_ERROR_MESSAGE, e.getMessage()); + BaseAccount account = null; + try { + account = new Account(context).getAccountByToken(dataPost.token); + } catch (DBException e2) { + e2.printStackTrace(); + } + new CachedBundle(context).insertBundle(args, account, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intentBD.putExtras(bundle); + intentBD.setPackage(BuildConfig.APPLICATION_ID); + context.sendBroadcast(intentBD); + }); return; } } else { @@ -376,14 +407,24 @@ public class ComposeWorker extends Worker { } if (dataPost.scheduledDate == null && dataPost.token != null && firstSendMessage != null) { - Bundle b = new Bundle(); - b.putBoolean(Helper.RECEIVE_NEW_MESSAGE, true); - b.putString(Helper.ARG_EDIT_STATUS_ID, dataPost.statusEditId); + Bundle args = new Bundle(); + args.putBoolean(Helper.RECEIVE_NEW_MESSAGE, true); + args.putString(Helper.ARG_EDIT_STATUS_ID, dataPost.statusEditId); Intent intentBD = new Intent(Helper.BROADCAST_DATA); - b.putSerializable(Helper.RECEIVE_STATUS_ACTION, firstSendMessage); - intentBD.putExtras(b); - intentBD.setPackage(BuildConfig.APPLICATION_ID); - context.sendBroadcast(intentBD); + args.putSerializable(Helper.RECEIVE_STATUS_ACTION, firstSendMessage); + BaseAccount account = null; + try { + account = new Account(context).getAccountByToken(dataPost.token); + } catch (DBException e2) { + e2.printStackTrace(); + } + new CachedBundle(context).insertBundle(args, account, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intentBD.putExtras(bundle); + intentBD.setPackage(BuildConfig.APPLICATION_ID); + context.sendBroadcast(intentBD); + }); } } diff --git a/app/src/main/java/app/fedilab/android/mastodon/services/CustomReceiver.java b/app/src/main/java/app/fedilab/android/mastodon/services/CustomReceiver.java index ab5fbc4c..e7c2b7cd 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/services/CustomReceiver.java +++ b/app/src/main/java/app/fedilab/android/mastodon/services/CustomReceiver.java @@ -66,14 +66,14 @@ public class CustomReceiver extends MessagingReceiver { @Override public void onNewEndpoint(@Nullable Context context, @NotNull String endpoint, @NotNull String slug) { if (context != null) { - synchronized(this) { + synchronized (this) { SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(context); - String storedEnpoint = sharedpreferences.getString(context.getString(R.string.SET_STORED_ENDPOINT)+slug, null); - if(storedEnpoint == null || !storedEnpoint.equals(endpoint)) { + String storedEnpoint = sharedpreferences.getString(context.getString(R.string.SET_STORED_ENDPOINT) + slug, null); + if (storedEnpoint == null || !storedEnpoint.equals(endpoint)) { PushNotifications .registerPushNotifications(context, endpoint, slug); SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putString(context.getString(R.string.SET_STORED_ENDPOINT)+slug, endpoint); + editor.putString(context.getString(R.string.SET_STORED_ENDPOINT) + slug, endpoint); editor.commit(); } } diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/AccountAdapter.java b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/AccountAdapter.java index 428048fa..10e470cc 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/AccountAdapter.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/AccountAdapter.java @@ -15,7 +15,8 @@ package app.fedilab.android.mastodon.ui.drawer; * see . */ -import android.app.Activity; +import static app.fedilab.android.BaseMainActivity.currentAccount; + import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; @@ -29,7 +30,6 @@ import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; -import androidx.core.app.ActivityOptionsCompat; import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.ViewModelProvider; import androidx.lifecycle.ViewModelStoreOwner; @@ -48,6 +48,7 @@ import app.fedilab.android.activities.MainActivity; import app.fedilab.android.databinding.DrawerAccountBinding; import app.fedilab.android.mastodon.activities.ProfileActivity; import app.fedilab.android.mastodon.client.entities.api.Account; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.helper.MastodonHelper; import app.fedilab.android.mastodon.helper.ThemeHelper; @@ -94,9 +95,9 @@ public class AccountAdapter extends RecyclerView.Adapter { if (muted) { - accountsVM.unmuteHome(MainActivity.currentAccount, account).observe((LifecycleOwner) context, account1 -> adapter.notifyItemChanged(accountViewHolder.getLayoutPosition())); + accountsVM.unmuteHome(currentAccount, account).observe((LifecycleOwner) context, account1 -> adapter.notifyItemChanged(accountViewHolder.getLayoutPosition())); } else { - accountsVM.muteHome(MainActivity.currentAccount, account).observe((LifecycleOwner) context, account1 -> adapter.notifyItemChanged(accountViewHolder.getLayoutPosition())); + accountsVM.muteHome(currentAccount, account).observe((LifecycleOwner) context, account1 -> adapter.notifyItemChanged(accountViewHolder.getLayoutPosition())); } }); } else { @@ -111,11 +112,14 @@ public class AccountAdapter extends RecyclerView.Adapter { if (remoteInstance == null) { Intent intent = new Intent(context, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, account); - intent.putExtras(b); - // start the new activity - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, account); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); } else { Toasty.info(context, context.getString(R.string.retrieve_remote_account), Toasty.LENGTH_SHORT).show(); SearchVM searchVM = new ViewModelProvider((ViewModelStoreOwner) context).get(SearchVM.class); @@ -124,11 +128,14 @@ public class AccountAdapter extends RecyclerView.Adapter 0) { Account accountSearch = results.accounts.get(0); Intent intent = new Intent(context, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, accountSearch); - intent.putExtras(b); - // start the new activity - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, accountSearch); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); } else { Toasty.info(context, context.getString(R.string.toast_error_search), Toasty.LENGTH_SHORT).show(); } diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/AccountFollowRequestAdapter.java b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/AccountFollowRequestAdapter.java index a765d851..537f1be3 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/AccountFollowRequestAdapter.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/AccountFollowRequestAdapter.java @@ -14,7 +14,8 @@ package app.fedilab.android.mastodon.ui.drawer; * You should have received a copy of the GNU General Public License along with Fedilab; if not, * see . */ -import android.app.Activity; +import static app.fedilab.android.BaseMainActivity.currentAccount; + import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; @@ -24,7 +25,6 @@ import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; -import androidx.core.app.ActivityOptionsCompat; import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.ViewModelProvider; import androidx.lifecycle.ViewModelStoreOwner; @@ -38,6 +38,7 @@ import app.fedilab.android.R; import app.fedilab.android.databinding.DrawerFollowBinding; import app.fedilab.android.mastodon.activities.ProfileActivity; import app.fedilab.android.mastodon.client.entities.api.Account; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.helper.MastodonHelper; import app.fedilab.android.mastodon.viewmodel.mastodon.AccountsVM; @@ -103,11 +104,14 @@ public class AccountFollowRequestAdapter extends RecyclerView.Adapter { Intent intent = new Intent(context, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, account); - intent.putExtras(b); - // start the new activity - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, account); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); }); } diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/AccountsSearchTopBarAdapter.java b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/AccountsSearchTopBarAdapter.java index 60eb910c..18f144d6 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/AccountsSearchTopBarAdapter.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/AccountsSearchTopBarAdapter.java @@ -14,7 +14,8 @@ package app.fedilab.android.mastodon.ui.drawer; * You should have received a copy of the GNU General Public License along with Fedilab; if not, * see . */ -import android.app.Activity; +import static app.fedilab.android.BaseMainActivity.currentAccount; + import android.content.Context; import android.content.Intent; import android.database.Cursor; @@ -22,10 +23,8 @@ import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; -import android.widget.ImageView; import androidx.appcompat.widget.LinearLayoutCompat; -import androidx.core.app.ActivityOptionsCompat; import androidx.cursoradapter.widget.SimpleCursorAdapter; import java.util.List; @@ -33,6 +32,7 @@ import java.util.List; import app.fedilab.android.R; import app.fedilab.android.mastodon.activities.ProfileActivity; import app.fedilab.android.mastodon.client.entities.api.Account; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.helper.Helper; @@ -61,16 +61,18 @@ public class AccountsSearchTopBarAdapter extends SimpleCursorAdapter { LinearLayoutCompat container = view.findViewById(R.id.account_container); container.setTag(cursor.getPosition()); - ImageView account_pp = view.findViewById(R.id.account_pp); container.setOnClickListener(v -> { int position = (int) v.getTag(); if (accountList != null && accountList.size() > position) { Intent intent = new Intent(context, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, accountList.get(position)); - intent.putExtras(b); - // start the new activity - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, accountList.get(position)); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); } }); } diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/ComposeAdapter.java b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/ComposeAdapter.java index 97bd72f2..38fd8a43 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/ComposeAdapter.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/ComposeAdapter.java @@ -51,7 +51,6 @@ import android.view.inputmethod.InputMethodManager; import android.webkit.URLUtil; import android.widget.ArrayAdapter; import android.widget.Button; -import android.widget.GridView; import android.widget.LinearLayout; import android.widget.TextView; @@ -110,7 +109,6 @@ import app.fedilab.android.databinding.DrawerStatusComposeBinding; import app.fedilab.android.databinding.DrawerStatusSimpleBinding; import app.fedilab.android.mastodon.activities.ComposeActivity; import app.fedilab.android.mastodon.activities.MediaActivity; -import app.fedilab.android.mastodon.activities.SearchResultTabActivity; import app.fedilab.android.mastodon.client.entities.api.Account; import app.fedilab.android.mastodon.client.entities.api.Attachment; import app.fedilab.android.mastodon.client.entities.api.Emoji; @@ -120,6 +118,7 @@ import app.fedilab.android.mastodon.client.entities.api.Poll; import app.fedilab.android.mastodon.client.entities.api.Status; import app.fedilab.android.mastodon.client.entities.api.Tag; import app.fedilab.android.mastodon.client.entities.app.BaseAccount; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.client.entities.app.CamelTag; import app.fedilab.android.mastodon.client.entities.app.Languages; import app.fedilab.android.mastodon.client.entities.app.Quotes; @@ -549,7 +548,7 @@ public class ComposeAdapter extends RecyclerView.Adapter splitText = ComposeHelper.splitToots(s.toString(), max_car); int statusListSize = statusList.size(); int i = 0; - for(String message: splitText) { - if(i==0) { + for (String message : splitText) { + if (i == 0) { i++; continue; } - manageDrafts.onItemDraftAdded(statusListSize+(i-1), message); + manageDrafts.onItemDraftAdded(statusListSize + (i - 1), message); buttonVisibility(holder); i++; } @@ -594,7 +593,7 @@ public class ComposeAdapter extends RecyclerView.Adapter splitText = ComposeHelper.splitToots(contentString, max_car); contentString = splitText.get(0); @@ -891,6 +890,13 @@ public class ComposeAdapter extends RecyclerView.Adapter 0 ) { + if (status.media_attachments != null && status.media_attachments.size() > 0) { holder.binding.simpleMedia.removeAllViews(); List attachmentList = statusList.get(position).media_attachments; - for(Attachment attachment: attachmentList) { + for (Attachment attachment : attachmentList) { DrawerMediaListBinding drawerMediaListBinding = DrawerMediaListBinding.inflate(LayoutInflater.from(context), holder.binding.simpleMedia, false); Glide.with(drawerMediaListBinding.media.getContext()) .load(attachment.preview_url) .into(drawerMediaListBinding.media); - if(attachment.filename != null) { + if (attachment.filename != null) { drawerMediaListBinding.mediaName.setText(attachment.filename); - } else if (attachment.preview_url != null){ + } else if (attachment.preview_url != null) { drawerMediaListBinding.mediaName.setText(URLUtil.guessFileName(attachment.preview_url, null, null)); } - drawerMediaListBinding.getRoot().setOnClickListener(v->{ + drawerMediaListBinding.getRoot().setOnClickListener(v -> { Intent mediaIntent = new Intent(context, MediaActivity.class); - Bundle b = new Bundle(); + Bundle args = new Bundle(); ArrayList attachments = new ArrayList<>(); attachments.add(attachment); - b.putSerializable(Helper.ARG_MEDIA_ARRAY, attachments); - mediaIntent.putExtras(b); - ActivityOptionsCompat options = ActivityOptionsCompat - .makeSceneTransitionAnimation((Activity) context, drawerMediaListBinding.media, attachment.url); - context.startActivity(mediaIntent, options.toBundle()); + args.putSerializable(Helper.ARG_MEDIA_ARRAY, attachments); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + mediaIntent.putExtras(bundle); + ActivityOptionsCompat options = ActivityOptionsCompat + .makeSceneTransitionAnimation((Activity) context, drawerMediaListBinding.media, attachment.url); + context.startActivity(mediaIntent, options.toBundle()); + }); }); holder.binding.simpleMedia.addView(drawerMediaListBinding.getRoot()); diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/ConversationAdapter.java b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/ConversationAdapter.java index 08a2b11a..fb35d988 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/ConversationAdapter.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/ConversationAdapter.java @@ -15,6 +15,7 @@ package app.fedilab.android.mastodon.ui.drawer; * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; import static app.fedilab.android.BaseMainActivity.currentNightMode; import android.annotation.SuppressLint; @@ -22,6 +23,7 @@ import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; +import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.view.LayoutInflater; @@ -54,6 +56,7 @@ import app.fedilab.android.mastodon.client.entities.api.Account; import app.fedilab.android.mastodon.client.entities.api.Attachment; import app.fedilab.android.mastodon.client.entities.api.Conversation; import app.fedilab.android.mastodon.client.entities.api.Status; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.helper.MastodonHelper; @@ -220,8 +223,14 @@ public class ConversationAdapter extends RecyclerView.Adapter { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); }); holder.binding.attachmentsListContainer.setOnTouchListener((v, event) -> { @@ -232,8 +241,14 @@ public class ConversationAdapter extends RecyclerView.Adapter { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); } return false; }); diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/ImageAdapter.java b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/ImageAdapter.java index 9b4304ed..817b79ed 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/ImageAdapter.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/ImageAdapter.java @@ -14,6 +14,8 @@ package app.fedilab.android.mastodon.ui.drawer; * You should have received a copy of the GNU General Public License along with Fedilab; if not, * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; + import android.app.Activity; import android.content.Context; import android.content.Intent; @@ -31,6 +33,7 @@ import app.fedilab.android.databinding.DrawerMediaBinding; import app.fedilab.android.mastodon.activities.ContextActivity; import app.fedilab.android.mastodon.activities.MediaActivity; import app.fedilab.android.mastodon.client.entities.api.Attachment; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.ui.fragment.media.FragmentMediaProfile; @@ -72,30 +75,37 @@ public class ImageAdapter extends RecyclerView.Adapter } holder.binding.media.setOnClickListener(v -> { Intent mediaIntent = new Intent(context, MediaActivity.class); - Bundle b = new Bundle(); - b.putInt(Helper.ARG_MEDIA_POSITION, position + 1); - b.putBoolean(Helper.ARG_MEDIA_ARRAY_PROFILE, true); - mediaIntent.putExtras(b); - ActivityOptionsCompat options = null; + Bundle args = new Bundle(); + args.putInt(Helper.ARG_MEDIA_POSITION, position + 1); + args.putBoolean(Helper.ARG_MEDIA_ARRAY_PROFILE, true); if (attachment != null) { - options = ActivityOptionsCompat - .makeSceneTransitionAnimation((Activity) context, holder.binding.media, attachment.url); - } else { - return; + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + mediaIntent.putExtras(bundle); + ActivityOptionsCompat options = null; + options = ActivityOptionsCompat + .makeSceneTransitionAnimation((Activity) context, holder.binding.media, attachment.url); + context.startActivity(mediaIntent, options.toBundle()); + }); } - // start the new activity - context.startActivity(mediaIntent, options.toBundle()); }); holder.binding.media.setOnLongClickListener(v -> { Intent intentContext = new Intent(context, ContextActivity.class); + Bundle args = new Bundle(); if (attachment != null) { - intentContext.putExtra(Helper.ARG_STATUS, attachment.status); + args.putSerializable(Helper.ARG_STATUS, attachment.status); } else { return false; } - intentContext.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(intentContext); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intentContext.putExtras(bundle); + intentContext.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(intentContext); + }); return false; }); } diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/NotificationAdapter.java b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/NotificationAdapter.java index d4f63e7e..e18cd9b1 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/NotificationAdapter.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/NotificationAdapter.java @@ -15,10 +15,10 @@ package app.fedilab.android.mastodon.ui.drawer; * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; import static app.fedilab.android.BaseMainActivity.currentNightMode; import static app.fedilab.android.mastodon.ui.drawer.StatusAdapter.statusManagement; -import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; @@ -30,7 +30,6 @@ import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; -import androidx.core.app.ActivityOptionsCompat; import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.ViewModelProvider; import androidx.lifecycle.ViewModelStoreOwner; @@ -50,6 +49,7 @@ import app.fedilab.android.databinding.DrawerStatusNotificationBinding; import app.fedilab.android.databinding.NotificationsRelatedAccountsBinding; import app.fedilab.android.mastodon.activities.ProfileActivity; import app.fedilab.android.mastodon.client.entities.api.Notification; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.client.entities.app.Timeline; import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.helper.MastodonHelper; @@ -272,11 +272,14 @@ public class NotificationAdapter extends RecyclerView.Adapter { Intent intent = new Intent(context, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, notification.account); - intent.putExtras(b); - // start the new activity - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, notification.account); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); }); if (notification.isFetchMore && fetchMoreCallBack != null) { holderFollow.binding.layoutFetchMore.fetchMoreContainer.setVisibility(View.VISIBLE); @@ -382,11 +385,14 @@ public class NotificationAdapter extends RecyclerView.Adapter { Intent intent = new Intent(context, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, notification.account); - intent.putExtras(b); - // start the new activity - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, notification.account); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); }); holderStatus.bindingNotification.status.mainContainer.setAlpha(.8f); } @@ -429,11 +435,14 @@ public class NotificationAdapter extends RecyclerView.Adapter { Intent intent = new Intent(context, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, relativeNotif.account); - intent.putExtras(b); - // start the new activity - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, relativeNotif.account); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); }); holderStatus.bindingNotification.relatedAccounts.addView(notificationsRelatedAccountsBinding.getRoot()); } @@ -443,21 +452,26 @@ public class NotificationAdapter extends RecyclerView.Adapter { Intent intent = new Intent(context, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, notification.account); - intent.putExtras(b); - // start the new activity - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, notification.account); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); }); holderStatus.bindingNotification.status.statusUserInfo.setOnClickListener(v -> { Intent intent = new Intent(context, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, notification.account); - intent.putExtras(b); - // start the new activity - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, notification.account); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); }); - holderStatus.bindingNotification.status.displayName.setText( notification.account.getSpanDisplayNameTitle(context, new WeakReference<>(holderStatus.bindingNotification.status.displayName), title), diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/SliderAdapter.java b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/SliderAdapter.java index 0cf829bd..69c2b2cd 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/SliderAdapter.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/SliderAdapter.java @@ -14,6 +14,8 @@ package app.fedilab.android.mastodon.ui.drawer; * You should have received a copy of the GNU General Public License along with Fedilab; if not, * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; + import android.app.Activity; import android.content.Context; import android.content.Intent; @@ -38,6 +40,7 @@ import app.fedilab.android.databinding.DrawerSliderBinding; import app.fedilab.android.mastodon.activities.MediaActivity; import app.fedilab.android.mastodon.client.entities.api.Attachment; import app.fedilab.android.mastodon.client.entities.api.Status; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.helper.Helper; import jp.wasabeef.glide.transformations.BlurTransformation; @@ -102,14 +105,17 @@ public class SliderAdapter extends SliderViewAdapter(status.media_attachments)); - mediaIntent.putExtras(b); - ActivityOptionsCompat options = ActivityOptionsCompat - .makeSceneTransitionAnimation((Activity) context, viewHolder.binding.ivAutoImageSlider, status.media_attachments.get(0).url); - // start the new activity - context.startActivity(mediaIntent, options.toBundle()); + Bundle args = new Bundle(); + args.putInt(Helper.ARG_MEDIA_POSITION, position + 1); + args.putSerializable(Helper.ARG_MEDIA_ARRAY, new ArrayList<>(status.media_attachments)); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + mediaIntent.putExtras(bundle); + ActivityOptionsCompat options = ActivityOptionsCompat + .makeSceneTransitionAnimation((Activity) context, viewHolder.binding.ivAutoImageSlider, status.media_attachments.get(0).url); + context.startActivity(mediaIntent, options.toBundle()); + }); } }); } diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/StatusAdapter.java b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/StatusAdapter.java index b417ff6b..984e6902 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/StatusAdapter.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/StatusAdapter.java @@ -88,7 +88,6 @@ import androidx.fragment.app.Fragment; import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.ViewModelProvider; import androidx.lifecycle.ViewModelStoreOwner; - import androidx.preference.PreferenceManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; @@ -153,6 +152,7 @@ import app.fedilab.android.mastodon.client.entities.api.Reaction; import app.fedilab.android.mastodon.client.entities.api.Status; import app.fedilab.android.mastodon.client.entities.app.Account; import app.fedilab.android.mastodon.client.entities.app.BaseAccount; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.client.entities.app.PinnedTimeline; import app.fedilab.android.mastodon.client.entities.app.RemoteInstance; import app.fedilab.android.mastodon.client.entities.app.StatusCache; @@ -481,7 +481,7 @@ public class StatusAdapter extends RecyclerView.Adapter String loadMediaType = sharedpreferences.getString(context.getString(R.string.SET_LOAD_MEDIA_TYPE), "ALWAYS"); - if (statusToDeal.quote != null) { + if (statusToDeal.quote != null && (statusToDeal.spoiler_text == null || statusToDeal.spoiler_text.trim().isEmpty() || statusToDeal.isExpended)) { holder.binding.quotedMessage.cardviewContainer.setCardElevation((int) Helper.convertDpToPixel(5, context)); holder.binding.quotedMessage.dividerCard.setVisibility(View.GONE); holder.binding.quotedMessage.cardviewContainer.setStrokeWidth((int) Helper.convertDpToPixel(1, context)); @@ -503,8 +503,14 @@ public class StatusAdapter extends RecyclerView.Adapter return; } Intent intent = new Intent(context, ContextActivity.class); - intent.putExtra(Helper.ARG_STATUS, statusToDeal.quote); - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS, statusToDeal.quote); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); }); holder.binding.quotedMessage.cardviewContainer.setStrokeColor(ThemeHelper.getAttColor(context, R.attr.colorPrimary)); holder.binding.quotedMessage.statusContent.setText( @@ -932,22 +938,28 @@ public class StatusAdapter extends RecyclerView.Adapter if (results != null && results.statuses != null && results.statuses.size() > 0) { Status fetchedStatus = results.statuses.get(0); Intent intent = new Intent(context, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, fetchedStatus.reblog != null ? fetchedStatus.reblog.account : fetchedStatus.account); - intent.putExtras(b); - // start the new activity - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, fetchedStatus.reblog != null ? fetchedStatus.reblog.account : fetchedStatus.account); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); } else { Toasty.info(context, context.getString(R.string.toast_error_search), Toasty.LENGTH_SHORT).show(); } }); } else { Intent intent = new Intent(context, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, status.reblog != null ? status.reblog.account : status.account); - intent.putExtras(b); - // start the new activity - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, status.reblog != null ? status.reblog.account : status.account); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); } }); holder.binding.statusBoosterInfo.setOnClickListener(v -> { @@ -958,22 +970,28 @@ public class StatusAdapter extends RecyclerView.Adapter if (results != null && results.statuses != null && results.statuses.size() > 0) { Status fetchedStatus = results.statuses.get(0); Intent intent = new Intent(context, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, fetchedStatus.account); - intent.putExtras(b); - // start the new activity - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, fetchedStatus.account); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); } else { Toasty.info(context, context.getString(R.string.toast_error_search), Toasty.LENGTH_SHORT).show(); } }); } else { Intent intent = new Intent(context, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, status.account); - intent.putExtras(b); - // start the new activity - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, status.account); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); } }); //---> REBLOG/UNREBLOG @@ -1286,13 +1304,13 @@ public class StatusAdapter extends RecyclerView.Adapter } else { holder.binding.replyCount.setVisibility(View.GONE); } - if(statusToDeal.reblogs_count > 0) { + if (statusToDeal.reblogs_count > 0) { holder.binding.boostCount.setText(String.valueOf(statusToDeal.reblogs_count)); holder.binding.boostCount.setVisibility(View.VISIBLE); } else { holder.binding.boostCount.setVisibility(View.GONE); } - if(statusToDeal.favourites_count > 0) { + if (statusToDeal.favourites_count > 0) { holder.binding.favoriteCount.setText(String.valueOf(statusToDeal.favourites_count)); holder.binding.favoriteCount.setVisibility(View.VISIBLE); } else { @@ -1317,7 +1335,7 @@ public class StatusAdapter extends RecyclerView.Adapter } else { holder.binding.dateShort.setCompoundDrawables(null, null, null, null); } - if(relativeDate) { + if (relativeDate) { if (originalDateForBoost || status.reblog == null) { holder.binding.dateShort.setText(Helper.dateDiff(context, statusToDeal.created_at)); } else { @@ -1448,6 +1466,7 @@ public class StatusAdapter extends RecyclerView.Adapter } } else { holder.binding.statusContent.setVisibility(View.GONE); + holder.binding.quotedMessage.cardviewContainer.setVisibility(View.GONE); holder.binding.mediaContainer.setVisibility(View.GONE); holder.binding.card.setVisibility(View.GONE); } @@ -1656,14 +1675,17 @@ public class StatusAdapter extends RecyclerView.Adapter return; } Intent mediaIntent = new Intent(context, MediaActivity.class); - Bundle b = new Bundle(); - b.putInt(Helper.ARG_MEDIA_POSITION, finalMediaPosition); - b.putSerializable(Helper.ARG_MEDIA_ARRAY, new ArrayList<>(statusToDeal.media_attachments)); - mediaIntent.putExtras(b); - ActivityOptionsCompat options = ActivityOptionsCompat - .makeSceneTransitionAnimation((Activity) context, layoutMediaBinding.media, statusToDeal.media_attachments.get(0).url); - // start the new activity - context.startActivity(mediaIntent, options.toBundle()); + Bundle args = new Bundle(); + args.putInt(Helper.ARG_MEDIA_POSITION, finalMediaPosition); + args.putSerializable(Helper.ARG_MEDIA_ARRAY, new ArrayList<>(statusToDeal.media_attachments)); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + mediaIntent.putExtras(bundle); + ActivityOptionsCompat options = ActivityOptionsCompat + .makeSceneTransitionAnimation((Activity) context, layoutMediaBinding.media, statusToDeal.media_attachments.get(0).url); + context.startActivity(mediaIntent, options.toBundle()); + }); }); layoutMediaBinding.viewHide.setOnClickListener(v -> { statusToDeal.sensitive = !statusToDeal.sensitive; @@ -1724,14 +1746,17 @@ public class StatusAdapter extends RecyclerView.Adapter return; } Intent mediaIntent = new Intent(context, MediaActivity.class); - Bundle b = new Bundle(); - b.putInt(Helper.ARG_MEDIA_POSITION, finalMediaPosition); - b.putSerializable(Helper.ARG_MEDIA_ARRAY, new ArrayList<>(statusToDeal.media_attachments)); - mediaIntent.putExtras(b); - ActivityOptionsCompat options = ActivityOptionsCompat - .makeSceneTransitionAnimation((Activity) context, layoutMediaBinding.media, statusToDeal.media_attachments.get(0).url); - // start the new activity - context.startActivity(mediaIntent, options.toBundle()); + Bundle args = new Bundle(); + args.putInt(Helper.ARG_MEDIA_POSITION, finalMediaPosition); + args.putSerializable(Helper.ARG_MEDIA_ARRAY, new ArrayList<>(statusToDeal.media_attachments)); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + mediaIntent.putExtras(bundle); + ActivityOptionsCompat options = ActivityOptionsCompat + .makeSceneTransitionAnimation((Activity) context, layoutMediaBinding.media, statusToDeal.media_attachments.get(0).url); + context.startActivity(mediaIntent, options.toBundle()); + }); }); layoutMediaBinding.viewHide.setOnClickListener(v -> { statusToDeal.sensitive = !statusToDeal.sensitive; @@ -1761,20 +1786,32 @@ public class StatusAdapter extends RecyclerView.Adapter holder.binding.reblogInfo.setOnClickListener(v -> { if (statusToDeal.reblogs_count > 0) { Intent intent = new Intent(context, StatusInfoActivity.class); - intent.putExtra(Helper.ARG_TYPE_OF_INFO, StatusInfoActivity.typeOfInfo.BOOSTED_BY); - intent.putExtra(Helper.ARG_STATUS, statusToDeal); - intent.putExtra(Helper.ARG_CHECK_REMOTELY, remote); - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS, statusToDeal); + args.putSerializable(Helper.ARG_TYPE_OF_INFO, StatusInfoActivity.typeOfInfo.BOOSTED_BY); + args.putBoolean(Helper.ARG_CHECK_REMOTELY, remote); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); } }); holder.binding.favouriteInfo.setOnClickListener(v -> { if (statusToDeal.favourites_count > 0) { Intent intent = new Intent(context, StatusInfoActivity.class); - intent.putExtra(Helper.ARG_TYPE_OF_INFO, StatusInfoActivity.typeOfInfo.LIKED_BY); - intent.putExtra(Helper.ARG_STATUS, statusToDeal); - intent.putExtra(Helper.ARG_CHECK_REMOTELY, remote); - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS, statusToDeal); + args.putSerializable(Helper.ARG_TYPE_OF_INFO, StatusInfoActivity.typeOfInfo.LIKED_BY); + args.putBoolean(Helper.ARG_CHECK_REMOTELY, remote); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); } }); @@ -1782,7 +1819,7 @@ public class StatusAdapter extends RecyclerView.Adapter if (statusToDeal.poll != null && statusToDeal.poll.options != null) { int normalize; - if(statusToDeal.poll.multiple && statusToDeal.poll.voters_count > 1) { + if (statusToDeal.poll.multiple && statusToDeal.poll.voters_count > 1) { normalize = statusToDeal.poll.voters_count; } else { normalize = statusToDeal.poll.votes_count; @@ -1990,22 +2027,31 @@ public class StatusAdapter extends RecyclerView.Adapter return; } if (context instanceof ContextActivity && !remote) { - Bundle bundle = new Bundle(); - bundle.putSerializable(Helper.ARG_STATUS, statusToDeal); - Fragment fragment = Helper.addFragment(((AppCompatActivity) context).getSupportFragmentManager(), R.id.nav_host_fragment_content_main, new FragmentMastodonContext(), bundle, null, FragmentMastodonContext.class.getName()); - ((ContextActivity) context).setCurrentFragment((FragmentMastodonContext) fragment); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS, statusToDeal); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + Fragment fragment = Helper.addFragment(((AppCompatActivity) context).getSupportFragmentManager(), R.id.nav_host_fragment_content_main, new FragmentMastodonContext(), bundle, null, FragmentMastodonContext.class.getName()); + ((ContextActivity) context).setCurrentFragment((FragmentMastodonContext) fragment); + }); } else { if (remote) { //Lemmy main post that should open Lemmy threads if (adapter instanceof StatusAdapter && ((StatusAdapter) adapter).type == RemoteInstance.InstanceType.LEMMY && status.lemmy_post_id != null) { - Bundle bundle = new Bundle(); - bundle.putSerializable(Helper.ARG_REMOTE_INSTANCE, ((StatusAdapter) adapter).pinnedTimeline); - bundle.putSerializable(Helper.ARG_TIMELINE_TYPE, Timeline.TimeLineEnum.REMOTE); - bundle.putString(Helper.ARG_LEMMY_POST_ID, status.lemmy_post_id); - bundle.putSerializable(Helper.ARG_STATUS, status); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_REMOTE_INSTANCE, ((StatusAdapter) adapter).pinnedTimeline); + args.putSerializable(Helper.ARG_TIMELINE_TYPE, Timeline.TimeLineEnum.REMOTE); + args.putString(Helper.ARG_LEMMY_POST_ID, status.lemmy_post_id); + args.putSerializable(Helper.ARG_STATUS, status); Intent intent = new Intent(context, TimelineActivity.class); - intent.putExtras(bundle); - context.startActivity(intent); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); + } //Classic other cases for remote instances that will search the remote context else if (!(context instanceof ContextActivity)) { //We are not already checking a remote conversation Toasty.info(context, context.getString(R.string.retrieve_remote_status), Toasty.LENGTH_SHORT).show(); @@ -2014,8 +2060,14 @@ public class StatusAdapter extends RecyclerView.Adapter if (results != null && results.statuses != null && results.statuses.size() > 0) { Status fetchedStatus = results.statuses.get(0); Intent intent = new Intent(context, ContextActivity.class); - intent.putExtra(Helper.ARG_STATUS, fetchedStatus); - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS, fetchedStatus); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); } else { Toasty.info(context, context.getString(R.string.toast_error_search), Toasty.LENGTH_SHORT).show(); } @@ -2035,8 +2087,14 @@ public class StatusAdapter extends RecyclerView.Adapter } } else { Intent intent = new Intent(context, ContextActivity.class); - intent.putExtra(Helper.ARG_STATUS, statusToDeal); - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS, statusToDeal); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); } } }); @@ -2120,9 +2178,15 @@ public class StatusAdapter extends RecyclerView.Adapter } statusDeleted.id = null; statusDraft.statusDraftList.add(statusDeleted); - intent.putExtra(Helper.ARG_STATUS_DRAFT, statusDraft); - intent.putExtra(Helper.ARG_STATUS_REPLY_ID, statusDeleted.in_reply_to_id); - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS_DRAFT, statusDraft); + args.putSerializable(Helper.ARG_STATUS_REPLY_ID, statusDeleted.in_reply_to_id); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); sendAction(context, Helper.ARG_STATUS_DELETED, statusToDeal, null); }); } @@ -2143,10 +2207,16 @@ public class StatusAdapter extends RecyclerView.Adapter statusToDeal.spoilerChecked = true; } statusDraft.statusDraftList.add(statusToDeal); - intent.putExtra(Helper.ARG_STATUS_DRAFT, statusDraft); - intent.putExtra(Helper.ARG_EDIT_STATUS_ID, statusToDeal.id); - intent.putExtra(Helper.ARG_STATUS_REPLY_ID, statusToDeal.in_reply_to_id); - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS_DRAFT, statusDraft); + args.putString(Helper.ARG_EDIT_STATUS_ID, statusToDeal.id); + args.putString(Helper.ARG_STATUS_REPLY_ID, statusToDeal.in_reply_to_id); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); } else { Toasty.error(context, context.getString(R.string.toast_error), Toasty.LENGTH_SHORT).show(); } @@ -2250,8 +2320,14 @@ public class StatusAdapter extends RecyclerView.Adapter return true; } else if (itemId == R.id.action_report) { Intent intent = new Intent(context, ReportActivity.class); - intent.putExtra(Helper.ARG_STATUS, statusToDeal); - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS, statusToDeal); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); } else if (itemId == R.id.action_copy) { ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); String content; @@ -2305,14 +2381,24 @@ public class StatusAdapter extends RecyclerView.Adapter context.startActivity(Intent.createChooser(sendIntent, context.getString(R.string.share_with))); } else if (itemId == R.id.action_custom_sharing) { Intent intent = new Intent(context, CustomSharingActivity.class); - intent.putExtra(Helper.ARG_STATUS, statusToDeal); - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS, statusToDeal); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); } else if (itemId == R.id.action_mention) { Intent intent = new Intent(context, ComposeActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_STATUS_MENTION, statusToDeal); - intent.putExtras(b); - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS_MENTION, statusToDeal); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); } else if (itemId == R.id.action_open_with) { new Thread(() -> { try { @@ -2412,19 +2498,31 @@ public class StatusAdapter extends RecyclerView.Adapter if (results != null && results.statuses != null && results.statuses.size() > 0) { Status fetchedStatus = results.statuses.get(0); Intent intent = new Intent(context, ComposeActivity.class); - intent.putExtra(Helper.ARG_STATUS_REPLY, fetchedStatus); - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS_REPLY, fetchedStatus); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); } else { Toasty.info(context, context.getString(R.string.toast_error_search), Toasty.LENGTH_SHORT).show(); } }); } else { Intent intent = new Intent(context, ComposeActivity.class); - intent.putExtra(Helper.ARG_STATUS_REPLY, statusToDeal); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS_REPLY, statusToDeal); if (status.reblog != null) { - intent.putExtra(Helper.ARG_MENTION_BOOSTER, status.account); + args.putSerializable(Helper.ARG_MENTION_BOOSTER, status.account); } - context.startActivity(intent); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); } }); //For reports @@ -2691,14 +2789,17 @@ public class StatusAdapter extends RecyclerView.Adapter return; } Intent mediaIntent = new Intent(context, MediaActivity.class); - Bundle b = new Bundle(); - b.putInt(Helper.ARG_MEDIA_POSITION, mediaPosition); - b.putSerializable(Helper.ARG_MEDIA_ARRAY, new ArrayList<>(statusToDeal.media_attachments)); - mediaIntent.putExtras(b); - ActivityOptionsCompat options = ActivityOptionsCompat - .makeSceneTransitionAnimation((Activity) context, layoutMediaBinding.media, statusToDeal.media_attachments.get(0).url); - // start the new activity - context.startActivity(mediaIntent, options.toBundle()); + Bundle args = new Bundle(); + args.putInt(Helper.ARG_MEDIA_POSITION, mediaPosition); + args.putSerializable(Helper.ARG_MEDIA_ARRAY, new ArrayList<>(statusToDeal.media_attachments)); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + mediaIntent.putExtras(bundle); + ActivityOptionsCompat options = ActivityOptionsCompat + .makeSceneTransitionAnimation((Activity) context, layoutMediaBinding.media, statusToDeal.media_attachments.get(0).url); + context.startActivity(mediaIntent, options.toBundle()); + }); }); layoutMediaBinding.viewHide.setOnClickListener(v -> { statusToDeal.sensitive = !statusToDeal.sensitive; @@ -2748,20 +2849,24 @@ public class StatusAdapter extends RecyclerView.Adapter * @param id - Id of an account (can be null) */ public static void sendAction(@NonNull Context context, @NonNull String type, @Nullable Status status, @Nullable String id) { - Bundle b = new Bundle(); + Bundle args = new Bundle(); if (status != null) { - b.putSerializable(type, status); + args.putSerializable(type, status); } if (id != null) { - b.putString(type, id); + args.putString(type, id); } if (type.equals(ARG_TIMELINE_REFRESH_ALL)) { - b.putBoolean(ARG_TIMELINE_REFRESH_ALL, true); + args.putBoolean(ARG_TIMELINE_REFRESH_ALL, true); } Intent intentBC = new Intent(Helper.RECEIVE_STATUS_ACTION); - intentBC.putExtras(b); - intentBC.setPackage(BuildConfig.APPLICATION_ID); - context.sendBroadcast(intentBC); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intentBC.putExtras(bundle); + intentBC.setPackage(BuildConfig.APPLICATION_ID); + context.sendBroadcast(intentBC); + }); } @@ -3144,31 +3249,45 @@ public class StatusAdapter extends RecyclerView.Adapter holder.bindingArt.artAcct.setText(String.format(Locale.getDefault(), "@%s", status.account.acct)); holder.bindingArt.artPp.setOnClickListener(v -> { Intent intent = new Intent(context, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, status.account); - intent.putExtras(b); - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, status.account); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); }); holder.bindingArt.artMedia.setOnClickListener(v -> { if (status.art_attachment != null) { Intent mediaIntent = new Intent(context, MediaActivity.class); - Bundle b = new Bundle(); - b.putInt(Helper.ARG_MEDIA_POSITION, 1); + Bundle args = new Bundle(); + args.putInt(Helper.ARG_MEDIA_POSITION, 1); ArrayList attachments = new ArrayList<>(); attachments.add(status.art_attachment); - b.putSerializable(Helper.ARG_MEDIA_ARRAY, attachments); - mediaIntent.putExtras(b); - ActivityOptionsCompat options = ActivityOptionsCompat - .makeSceneTransitionAnimation((Activity) context, holder.bindingArt.artMedia, status.art_attachment.url); - context.startActivity(mediaIntent, options.toBundle()); + args.putSerializable(Helper.ARG_MEDIA_ARRAY, attachments); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + mediaIntent.putExtras(bundle); + ActivityOptionsCompat options = ActivityOptionsCompat + .makeSceneTransitionAnimation((Activity) context, holder.bindingArt.artMedia, status.art_attachment.url); + context.startActivity(mediaIntent, options.toBundle()); + }); } else { Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); } }); holder.bindingArt.bottomBanner.setOnClickListener(v -> { Intent intent = new Intent(context, ContextActivity.class); - intent.putExtra(Helper.ARG_STATUS, status); - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS, status); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); }); } else if (viewHolder.getItemViewType() == STATUS_PIXELFED) { Status statusToDeal = status.reblog != null ? status.reblog : status; @@ -3196,15 +3315,25 @@ public class StatusAdapter extends RecyclerView.Adapter holder.bindingPixelfed.artAcct.setText(String.format(Locale.getDefault(), "@%s", statusToDeal.account.acct)); holder.bindingPixelfed.artPp.setOnClickListener(v -> { Intent intent = new Intent(context, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, statusToDeal.account); - intent.putExtras(b); - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, statusToDeal.account); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); }); holder.bindingPixelfed.bottomBanner.setOnClickListener(v -> { Intent intent = new Intent(context, ContextActivity.class); - intent.putExtra(Helper.ARG_STATUS, statusToDeal); - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS, statusToDeal); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); }); } } @@ -3217,8 +3346,7 @@ public class StatusAdapter extends RecyclerView.Adapter @Override public void onViewRecycled(@NonNull RecyclerView.ViewHolder viewHolder) { super.onViewRecycled(viewHolder); - if (viewHolder instanceof StatusViewHolder) { - StatusViewHolder holder = (StatusViewHolder) viewHolder; + if (viewHolder instanceof StatusViewHolder holder) { if (holder.binding != null) { PlayerView doubleTapPlayerView = holder.binding.media.getRoot().findViewById(R.id.media_video); if (doubleTapPlayerView != null && doubleTapPlayerView.getPlayer() != null) { diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/StatusDirectMessageAdapter.java b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/StatusDirectMessageAdapter.java index 83d1f881..4523cae7 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/StatusDirectMessageAdapter.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/StatusDirectMessageAdapter.java @@ -15,6 +15,7 @@ package app.fedilab.android.mastodon.ui.drawer; * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; import static app.fedilab.android.mastodon.ui.drawer.StatusAdapter.prepareRequestBuilder; import android.app.Activity; @@ -77,6 +78,7 @@ import app.fedilab.android.mastodon.activities.MediaActivity; import app.fedilab.android.mastodon.client.entities.api.Attachment; import app.fedilab.android.mastodon.client.entities.api.Poll; import app.fedilab.android.mastodon.client.entities.api.Status; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.helper.CacheDataSourceFactory; import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.helper.LongClickLinkMovementMethod; @@ -191,14 +193,17 @@ public class StatusDirectMessageAdapter extends RecyclerView.Adapter(status.media_attachments)); - mediaIntent.putExtras(b); - ActivityOptionsCompat options = ActivityOptionsCompat - .makeSceneTransitionAnimation((Activity) context, layoutMediaBinding.media, status.media_attachments.get(0).url); - // start the new activity - context.startActivity(mediaIntent, options.toBundle()); + Bundle args = new Bundle(); + args.putInt(Helper.ARG_MEDIA_POSITION, mediaPosition); + args.putSerializable(Helper.ARG_MEDIA_ARRAY, new ArrayList<>(status.media_attachments)); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + mediaIntent.putExtras(bundle); + ActivityOptionsCompat options = ActivityOptionsCompat + .makeSceneTransitionAnimation((Activity) context, layoutMediaBinding.media, status.media_attachments.get(0).url); + context.startActivity(mediaIntent, options.toBundle()); + }); }); layoutMediaBinding.viewHide.setOnClickListener(v -> { status.sensitive = !status.sensitive; @@ -667,14 +672,17 @@ public class StatusDirectMessageAdapter extends RecyclerView.Adapter(status.media_attachments)); - mediaIntent.putExtras(b); - ActivityOptionsCompat options = ActivityOptionsCompat - .makeSceneTransitionAnimation((Activity) context, layoutMediaBinding.media, status.media_attachments.get(0).url); - // start the new activity - context.startActivity(mediaIntent, options.toBundle()); + Bundle args = new Bundle(); + args.putInt(Helper.ARG_MEDIA_POSITION, finalMediaPosition); + args.putSerializable(Helper.ARG_MEDIA_ARRAY, new ArrayList<>(status.media_attachments)); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + mediaIntent.putExtras(bundle); + ActivityOptionsCompat options = ActivityOptionsCompat + .makeSceneTransitionAnimation((Activity) context, layoutMediaBinding.media, status.media_attachments.get(0).url); + context.startActivity(mediaIntent, options.toBundle()); + }); }); layoutMediaBinding.viewHide.setOnClickListener(v -> { status.sensitive = !status.sensitive; diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/StatusDraftAdapter.java b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/StatusDraftAdapter.java index bb8a90c8..40dcfd79 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/StatusDraftAdapter.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/StatusDraftAdapter.java @@ -15,9 +15,12 @@ package app.fedilab.android.mastodon.ui.drawer; * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; + import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; +import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -39,6 +42,7 @@ import app.fedilab.android.databinding.DrawerStatusDraftBinding; import app.fedilab.android.mastodon.activities.ComposeActivity; import app.fedilab.android.mastodon.client.entities.api.Attachment; import app.fedilab.android.mastodon.client.entities.api.Status; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.client.entities.app.StatusDraft; import app.fedilab.android.mastodon.exception.DBException; import app.fedilab.android.mastodon.helper.Helper; @@ -100,11 +104,16 @@ public class StatusDraftAdapter extends RecyclerView.Adapter { Intent intent = new Intent(context, ComposeActivity.class); - intent.putExtra(Helper.ARG_STATUS_DRAFT, statusDraft); - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS_DRAFT, statusDraft); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); }); - holder.binding.delete.setOnClickListener(v -> { AlertDialog.Builder unfollowConfirm = new MaterialAlertDialogBuilder(context); unfollowConfirm.setMessage(context.getString(R.string.remove_draft)); diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/StatusScheduledAdapter.java b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/StatusScheduledAdapter.java index 96648818..14334b89 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/StatusScheduledAdapter.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/StatusScheduledAdapter.java @@ -16,10 +16,12 @@ package app.fedilab.android.mastodon.ui.drawer; import static androidx.core.text.HtmlCompat.FROM_HTML_MODE_LEGACY; +import static app.fedilab.android.BaseMainActivity.currentAccount; import android.content.Context; import android.content.Intent; import android.os.Build; +import android.os.Bundle; import android.text.Html; import android.text.SpannableString; import android.view.LayoutInflater; @@ -44,6 +46,7 @@ import app.fedilab.android.R; import app.fedilab.android.databinding.DrawerStatusScheduledBinding; import app.fedilab.android.mastodon.activities.ComposeActivity; import app.fedilab.android.mastodon.client.entities.api.ScheduledStatus; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.client.entities.app.ScheduledBoost; import app.fedilab.android.mastodon.client.entities.app.StatusDraft; import app.fedilab.android.mastodon.exception.DBException; @@ -126,10 +129,15 @@ public class StatusScheduledAdapter extends RecyclerView.Adapter { if (statusDraft != null) { Intent intent = new Intent(context, ComposeActivity.class); - intent.putExtra(Helper.ARG_STATUS_DRAFT, statusDraft); - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_STATUS_DRAFT, statusDraft); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); } - }); holder.binding.delete.setOnClickListener(v -> { AlertDialog.Builder unfollowConfirm = new MaterialAlertDialogBuilder(context); diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/SuggestionAdapter.java b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/SuggestionAdapter.java index 55bbc985..cb5fb225 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/SuggestionAdapter.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/SuggestionAdapter.java @@ -15,7 +15,8 @@ package app.fedilab.android.mastodon.ui.drawer; * see . */ -import android.app.Activity; +import static app.fedilab.android.BaseMainActivity.currentAccount; + import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; @@ -26,7 +27,6 @@ import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; -import androidx.core.app.ActivityOptionsCompat; import androidx.lifecycle.ViewModelProvider; import androidx.lifecycle.ViewModelStoreOwner; import androidx.preference.PreferenceManager; @@ -41,6 +41,7 @@ import app.fedilab.android.databinding.DrawerSuggestionBinding; import app.fedilab.android.mastodon.activities.ProfileActivity; import app.fedilab.android.mastodon.client.entities.api.Account; import app.fedilab.android.mastodon.client.entities.api.Suggestion; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.helper.MastodonHelper; import app.fedilab.android.mastodon.viewmodel.mastodon.AccountsVM; @@ -87,11 +88,14 @@ public class SuggestionAdapter extends RecyclerView.Adapter { Intent intent = new Intent(context, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, account); - intent.putExtras(b); - // start the new activity - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, account); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); }); holder.binding.followAction.setIconResource(R.drawable.ic_baseline_person_add_24); if (account == null) { diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/TagAdapter.java b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/TagAdapter.java index 81e1b67c..8ee8508d 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/TagAdapter.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/TagAdapter.java @@ -14,6 +14,8 @@ package app.fedilab.android.mastodon.ui.drawer; * You should have received a copy of the GNU General Public License along with Fedilab; if not, * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; + import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; @@ -41,6 +43,7 @@ import app.fedilab.android.databinding.DrawerTagBinding; import app.fedilab.android.mastodon.activities.HashTagActivity; import app.fedilab.android.mastodon.client.entities.api.History; import app.fedilab.android.mastodon.client.entities.api.Tag; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.helper.Helper; public class TagAdapter extends RecyclerView.Adapter { @@ -100,10 +103,14 @@ public class TagAdapter extends RecyclerView.Adapter { tagViewHolder.binding.getRoot().setOnClickListener(v1 -> { Intent intent = new Intent(context, HashTagActivity.class); - Bundle b = new Bundle(); - b.putString(Helper.ARG_SEARCH_KEYWORD, tag.name.trim()); - intent.putExtras(b); - context.startActivity(intent); + Bundle args = new Bundle(); + args.putString(Helper.ARG_SEARCH_KEYWORD, tag.name.trim()); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + context.startActivity(intent); + }); }); } diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/TagsSearchAdapter.java b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/TagsSearchAdapter.java index 1de85313..82972901 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/TagsSearchAdapter.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/TagsSearchAdapter.java @@ -11,10 +11,14 @@ import android.widget.Filterable; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; +import com.github.mikephil.charting.data.Entry; + import java.util.ArrayList; import java.util.List; +import app.fedilab.android.R; import app.fedilab.android.databinding.DrawerTagSearchBinding; +import app.fedilab.android.mastodon.client.entities.api.History; import app.fedilab.android.mastodon.client.entities.api.Tag; /* Copyright 2021 Thomas Schneider @@ -37,6 +41,7 @@ public class TagsSearchAdapter extends ArrayAdapter implements Filterable { private final List tags; private final List tempTags; private final List suggestions; + private final Context context; private final Filter searchFilter = new Filter() { @Override @@ -75,6 +80,7 @@ public class TagsSearchAdapter extends ArrayAdapter implements Filterable { public TagsSearchAdapter(Context context, List tags) { super(context, android.R.layout.simple_list_item_1, tags); + this.context = context; this.tags = tags; this.tempTags = new ArrayList<>(tags); this.suggestions = new ArrayList<>(tags); @@ -110,6 +116,21 @@ public class TagsSearchAdapter extends ArrayAdapter implements Filterable { holder = (TagSearchViewHolder) convertView.getTag(); } holder.binding.tagName.setText(String.format("#%s", tag.name)); + List historyList = tag.history; + + int stat = 0; + + if (historyList != null) { + for (History history : historyList) { + stat += Integer.parseInt(history.accounts); + } + } + if(stat > 0 ) { + holder.binding.tagCount.setText("(" + context.getString(R.string.talking_about, stat) + ")"); + holder.binding.tagCount.setVisibility(View.VISIBLE); + } else { + holder.binding.tagCount.setVisibility(View.GONE); + } return holder.view; } diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/admin/AdminAccountAdapter.java b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/admin/AdminAccountAdapter.java index 98967224..29bff755 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/admin/AdminAccountAdapter.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/drawer/admin/AdminAccountAdapter.java @@ -15,6 +15,8 @@ package app.fedilab.android.mastodon.ui.drawer.admin; * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; + import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; @@ -34,6 +36,7 @@ import app.fedilab.android.R; import app.fedilab.android.databinding.DrawerAdminAccountBinding; import app.fedilab.android.mastodon.activities.admin.AdminAccountActivity; import app.fedilab.android.mastodon.client.entities.api.admin.AdminAccount; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.helper.MastodonHelper; @@ -77,11 +80,15 @@ public class AdminAccountAdapter extends RecyclerView.Adapter { Intent intent = new Intent(context, AdminAccountActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, adminAccount); - intent.putExtras(b); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(intent); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_ACCOUNT, adminAccount); + new CachedBundle(context).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(intent); + }); }); holder.binding.username.setText(adminAccount.account.display_name); holder.binding.acct.setText(String.format(Locale.getDefault(), "@%s", adminAccount.account.acct)); diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/media/FragmentMedia.java b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/media/FragmentMedia.java index b1649b32..6740a6d8 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/media/FragmentMedia.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/media/FragmentMedia.java @@ -110,9 +110,17 @@ public class FragmentMedia extends Fragment { enableSliding(true); } }); - binding.mediaPicture.setOnClickListener(v -> ((MediaActivity) requireActivity()).toogleFullScreen()); + binding.mediaPicture.setOnClickListener(v -> { + if (isAdded()) { + ((MediaActivity) requireActivity()).toogleFullScreen(); + } + }); - binding.mediaVideo.setOnClickListener(v -> ((MediaActivity) requireActivity()).toogleFullScreen()); + binding.mediaVideo.setOnClickListener(v -> { + if (isAdded()) { + ((MediaActivity) requireActivity()).toogleFullScreen(); + } + }); String type = attachment.type; String preview_url = attachment.preview_url; @@ -363,7 +371,8 @@ public class FragmentMedia extends Fragment { binding.videoLayout.setVisibility(View.GONE); try { ActivityCompat.finishAfterTransition(requireActivity()); - }catch (Exception ignored){} + } catch (Exception ignored) { + } } } @@ -386,7 +395,9 @@ public class FragmentMedia extends Fragment { @Override public boolean onPreDraw() { imageView.getViewTreeObserver().removeOnPreDrawListener(this); - ActivityCompat.startPostponedEnterTransition(requireActivity()); + if (isAdded()) { + ActivityCompat.startPostponedEnterTransition(requireActivity()); + } return true; } }); diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/media/FragmentMediaProfile.java b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/media/FragmentMediaProfile.java index 8d8daca7..bea3e7b6 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/media/FragmentMediaProfile.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/media/FragmentMediaProfile.java @@ -14,6 +14,8 @@ package app.fedilab.android.mastodon.ui.fragment.media; * You should have received a copy of the GNU General Public License along with Fedilab; if not, * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; + import android.content.SharedPreferences; import android.os.Bundle; import android.view.LayoutInflater; @@ -38,6 +40,8 @@ import app.fedilab.android.mastodon.client.entities.api.Account; import app.fedilab.android.mastodon.client.entities.api.Attachment; import app.fedilab.android.mastodon.client.entities.api.Status; import app.fedilab.android.mastodon.client.entities.api.Statuses; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; +import app.fedilab.android.mastodon.exception.DBException; import app.fedilab.android.mastodon.helper.CrossActionHelper; import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.helper.MastodonHelper; @@ -68,17 +72,37 @@ public class FragmentMediaProfile extends Fragment { SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(requireActivity()); boolean displayScrollBar = sharedpreferences.getBoolean(getString(R.string.SET_TIMELINE_SCROLLBAR), false); binding.recyclerView.setVerticalScrollBarEnabled(displayScrollBar); - Bundle bundle = this.getArguments(); - if (bundle != null) { - accountTimeline = (Account) getArguments().getSerializable(Helper.ARG_ACCOUNT); - checkRemotely = getArguments().getBoolean(Helper.ARG_CHECK_REMOTELY, false); + + if (getArguments() != null) { + long bundleId = getArguments().getLong(Helper.ARG_INTENT_ID, -1); + if (bundleId != -1) { + new CachedBundle(requireActivity()).getBundle(bundleId, currentAccount, this::initializeAfterBundle); + } else { + if (getArguments().containsKey(Helper.ARG_CACHED_ACCOUNT_ID)) { + try { + accountTimeline = new CachedBundle(requireActivity()).getCachedAccount(currentAccount, getArguments().getString(Helper.ARG_CACHED_ACCOUNT_ID)); + } catch (DBException e) { + e.printStackTrace(); + } + } + initializeAfterBundle(getArguments()); + + } + } else { + initializeAfterBundle(null); } return binding.getRoot(); } - @Override - public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); + private void initializeAfterBundle(Bundle bundle) { + + if (bundle != null) { + if (bundle.containsKey(Helper.ARG_ACCOUNT)) { + accountTimeline = (Account) bundle.getSerializable(Helper.ARG_ACCOUNT); + } + checkRemotely = bundle.getBoolean(Helper.ARG_CHECK_REMOTELY, false); + } + flagLoading = false; accountsVM = new ViewModelProvider(requireActivity()).get(AccountsVM.class); mediaStatuses = new ArrayList<>(); @@ -114,7 +138,12 @@ public class FragmentMediaProfile extends Fragment { accountsVM.getAccountStatuses(BaseMainActivity.currentInstance, BaseMainActivity.currentToken, accountTimeline.id, null, null, null, null, null, true, false, MastodonHelper.statusesPerCall(requireActivity())) .observe(getViewLifecycleOwner(), this::initializeStatusesCommonView); } + } + + @Override + public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); } /** diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentComposeSettings.java b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentComposeSettings.java index afe46342..2b27992e 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentComposeSettings.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentComposeSettings.java @@ -19,6 +19,7 @@ import android.content.SharedPreferences; import android.os.Bundle; import androidx.preference.EditTextPreference; +import androidx.preference.ListPreference; import androidx.preference.MultiSelectListPreference; import androidx.preference.PreferenceFragmentCompat; import androidx.preference.PreferenceManager; @@ -30,6 +31,7 @@ import java.util.Set; import app.fedilab.android.BaseMainActivity; import app.fedilab.android.R; import app.fedilab.android.mastodon.client.entities.app.Languages; +import app.fedilab.android.mastodon.helper.Helper; public class FragmentComposeSettings extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener { @@ -43,12 +45,21 @@ public class FragmentComposeSettings extends PreferenceFragmentCompat implements private void createPref() { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireActivity()); + + //Theme for dialogs + ListPreference SET_THREAD_MESSAGE = findPreference(getString(R.string.SET_THREAD_MESSAGE)); + if (SET_THREAD_MESSAGE != null) { + SET_THREAD_MESSAGE.getContext().setTheme(Helper.dialogStyle()); + } + //--------- + EditTextPreference SET_WATERMARK_TEXT = findPreference(getString(R.string.SET_WATERMARK_TEXT)); if (SET_WATERMARK_TEXT != null) { String val = sharedPreferences.getString(getString(R.string.SET_WATERMARK_TEXT) + BaseMainActivity.currentUserID + BaseMainActivity.currentInstance, sharedPreferences.getString(getString(R.string.SET_WATERMARK_TEXT), null)); SET_WATERMARK_TEXT.setText(val); } + MultiSelectListPreference SET_SELECTED_LANGUAGE = findPreference(getString(R.string.SET_SELECTED_LANGUAGE)); if (SET_SELECTED_LANGUAGE != null) { diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentExtraFeaturesSettings.java b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentExtraFeaturesSettings.java index 8ba49507..4212c66e 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentExtraFeaturesSettings.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentExtraFeaturesSettings.java @@ -25,6 +25,7 @@ import androidx.preference.SwitchPreferenceCompat; import app.fedilab.android.R; import app.fedilab.android.activities.MainActivity; +import app.fedilab.android.mastodon.helper.Helper; public class FragmentExtraFeaturesSettings extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener { @@ -41,6 +42,18 @@ public class FragmentExtraFeaturesSettings extends PreferenceFragmentCompat impl addPreferencesFromResource(R.xml.pref_extra_features); PreferenceScreen preferenceScreen = getPreferenceScreen(); SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(requireActivity()); + + //Theme for dialogs + ListPreference SET_POST_FORMAT = findPreference(getString(R.string.SET_POST_FORMAT)); + if (SET_POST_FORMAT != null) { + SET_POST_FORMAT.getContext().setTheme(Helper.dialogStyle()); + } + ListPreference SET_COMPOSE_LOCAL_ONLY = findPreference(getString(R.string.SET_DEFAULT_LOCALE_NEW)); + if (SET_COMPOSE_LOCAL_ONLY != null) { + SET_COMPOSE_LOCAL_ONLY.getContext().setTheme(Helper.dialogStyle()); + } + //--------- + SwitchPreferenceCompat SET_EXTAND_EXTRA_FEATURES = findPreference(getString(R.string.SET_EXTAND_EXTRA_FEATURES)); if (SET_EXTAND_EXTRA_FEATURES != null) { boolean checked = sharedpreferences.getBoolean(getString(R.string.SET_EXTAND_EXTRA_FEATURES) + MainActivity.currentUserID + MainActivity.currentInstance, false); @@ -69,13 +82,11 @@ public class FragmentExtraFeaturesSettings extends PreferenceFragmentCompat impl SET_DISPLAY_REACTIONS.setChecked(checked); } - ListPreference SET_POST_FORMAT = findPreference(getString(R.string.SET_POST_FORMAT)); if (SET_POST_FORMAT != null) { String format = sharedpreferences.getString(getString(R.string.SET_POST_FORMAT) + MainActivity.currentUserID + MainActivity.currentInstance, "text/plain"); SET_POST_FORMAT.setValue(format); } - ListPreference SET_COMPOSE_LOCAL_ONLY = findPreference(getString(R.string.SET_COMPOSE_LOCAL_ONLY)); if (SET_COMPOSE_LOCAL_ONLY != null) { int localOnly = sharedpreferences.getInt(getString(R.string.SET_COMPOSE_LOCAL_ONLY) + MainActivity.currentUserID + MainActivity.currentInstance, 0); SET_COMPOSE_LOCAL_ONLY.setValue(String.valueOf(localOnly)); diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentHomeCacheSettings.java b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentHomeCacheSettings.java index 8fe1f1de..ed98dea4 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentHomeCacheSettings.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentHomeCacheSettings.java @@ -63,13 +63,21 @@ public class FragmentHomeCacheSettings extends PreferenceFragmentCompat implemen return; } SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(requireActivity()); + + //Theme for dialogs + ListPreference SET_FETCH_HOME_DELAY_VALUE = findPreference(getString(R.string.SET_FETCH_HOME_DELAY_VALUE)); + if (SET_FETCH_HOME_DELAY_VALUE != null) { + SET_FETCH_HOME_DELAY_VALUE.getContext().setTheme(Helper.dialogStyle()); + } + //--------- + + SwitchPreference SET_FETCH_HOME = findPreference(getString(R.string.SET_FETCH_HOME)); if (SET_FETCH_HOME != null) { boolean checked = sharedpreferences.getBoolean(getString(R.string.SET_FETCH_HOME) + MainActivity.currentUserID + MainActivity.currentInstance, false); SET_FETCH_HOME.setChecked(checked); } - ListPreference SET_FETCH_HOME_DELAY_VALUE = findPreference(getString(R.string.SET_FETCH_HOME_DELAY_VALUE)); if (SET_FETCH_HOME_DELAY_VALUE != null) { String timeRefresh = sharedpreferences.getString(getString(R.string.SET_FETCH_HOME_DELAY_VALUE) + MainActivity.currentUserID + MainActivity.currentInstance, "60"); SET_FETCH_HOME_DELAY_VALUE.setValue(timeRefresh); diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentInterfaceSettings.java b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentInterfaceSettings.java index c18a0c8f..3019cccb 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentInterfaceSettings.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentInterfaceSettings.java @@ -33,6 +33,7 @@ import app.fedilab.android.BuildConfig; import app.fedilab.android.R; import app.fedilab.android.activities.MainActivity; import app.fedilab.android.mastodon.helper.Helper; +import app.fedilab.android.mastodon.helper.ImageListPreference; import app.fedilab.android.mastodon.helper.LogoHelper; import es.dmoral.toasty.Toasty; @@ -54,6 +55,13 @@ public class FragmentInterfaceSettings extends PreferenceFragmentCompat implemen Toasty.error(requireActivity(), getString(R.string.toast_error), Toasty.LENGTH_SHORT).show(); return; } + + //Theme for dialogs + ImageListPreference SET_LOGO_LAUNCHER = findPreference(getString(R.string.SET_LOGO_LAUNCHER)); + if (SET_LOGO_LAUNCHER != null) { + SET_LOGO_LAUNCHER.getContext().setTheme(Helper.dialogStyle()); + } + //--------- SeekBarPreference SET_FONT_SCALE = findPreference(getString(R.string.SET_FONT_SCALE_INT)); if (SET_FONT_SCALE != null) { SET_FONT_SCALE.setMax(180); @@ -64,7 +72,6 @@ public class FragmentInterfaceSettings extends PreferenceFragmentCompat implemen SET_FONT_SCALE_ICON.setMax(180); SET_FONT_SCALE_ICON.setMin(80); } - ListPreference SET_LOGO_LAUNCHER = findPreference(getString(R.string.SET_LOGO_LAUNCHER)); if (SET_LOGO_LAUNCHER != null) { SET_LOGO_LAUNCHER.setIcon(LogoHelper.getDrawable(SET_LOGO_LAUNCHER.getValue())); } @@ -120,6 +127,9 @@ public class FragmentInterfaceSettings extends PreferenceFragmentCompat implemen editor.putString(getString(R.string.SET_LOGO_LAUNCHER), newLauncher); } } + if (key.compareToIgnoreCase(getString(R.string.SET_DISABLE_TOPBAR_SCROLLING)) == 0) { + recreate = true; + } editor.apply(); } } diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentLanguageSettings.java b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentLanguageSettings.java index 6ba2d944..40f05735 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentLanguageSettings.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentLanguageSettings.java @@ -18,6 +18,7 @@ import android.annotation.SuppressLint; import android.content.SharedPreferences; import android.os.Bundle; +import androidx.preference.ListPreference; import androidx.preference.Preference; import androidx.preference.PreferenceFragmentCompat; import androidx.preference.PreferenceManager; @@ -37,6 +38,14 @@ public class FragmentLanguageSettings extends PreferenceFragmentCompat implement private void createPref() { Preference SET_TRANSLATE_VALUES_RESET = findPreference(getString(R.string.SET_TRANSLATE_VALUES_RESET)); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireActivity()); + + //Theme for dialogs + ListPreference SET_DEFAULT_LOCALE_NEW = findPreference(getString(R.string.SET_DEFAULT_LOCALE_NEW)); + if (SET_DEFAULT_LOCALE_NEW != null) { + SET_DEFAULT_LOCALE_NEW.getContext().setTheme(Helper.dialogStyle()); + } + //--------- + if (SET_TRANSLATE_VALUES_RESET != null) { SET_TRANSLATE_VALUES_RESET.setOnPreferenceClickListener(preference -> { SharedPreferences.Editor editor = sharedPreferences.edit(); diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentNotificationsSettings.java b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentNotificationsSettings.java index a665adc9..7a834ccb 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentNotificationsSettings.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentNotificationsSettings.java @@ -40,6 +40,7 @@ import java.util.ArrayList; import java.util.List; import app.fedilab.android.R; +import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.helper.PushHelper; import app.fedilab.android.mastodon.helper.settings.TimePreference; import app.fedilab.android.mastodon.helper.settings.TimePreferenceDialogFragment; @@ -76,13 +77,37 @@ public class FragmentNotificationsSettings extends PreferenceFragmentCompat impl getPreferenceScreen().removeAll(); addPreferencesFromResource(R.xml.pref_notifications); PreferenceScreen preferenceScreen = getPreferenceScreen(); + + //Theme for dialogs + ListPreference SET_NOTIFICATION_TYPE = findPreference(getString(R.string.SET_NOTIFICATION_TYPE)); + if (SET_NOTIFICATION_TYPE != null) { + SET_NOTIFICATION_TYPE.getContext().setTheme(Helper.dialogStyle()); + } + ListPreference SET_NOTIFICATION_DELAY_VALUE = findPreference(getString(R.string.SET_NOTIFICATION_DELAY_VALUE)); + if (SET_NOTIFICATION_DELAY_VALUE != null) { + SET_NOTIFICATION_DELAY_VALUE.getContext().setTheme(Helper.dialogStyle()); + } + ListPreference SET_PUSH_DISTRIBUTOR = findPreference(getString(R.string.SET_PUSH_DISTRIBUTOR)); + if (SET_PUSH_DISTRIBUTOR != null) { + SET_PUSH_DISTRIBUTOR.getContext().setTheme(Helper.dialogStyle()); + } + ListPreference SET_LED_COLOUR_VAL_N = findPreference(getString(R.string.SET_LED_COLOUR_VAL_N)); + if (SET_LED_COLOUR_VAL_N != null) { + SET_LED_COLOUR_VAL_N.getContext().setTheme(Helper.dialogStyle()); + } + ListPreference SET_NOTIFICATION_ACTION = findPreference(getString(R.string.SET_NOTIFICATION_ACTION)); + if (SET_NOTIFICATION_ACTION != null) { + SET_NOTIFICATION_ACTION.getContext().setTheme(Helper.dialogStyle()); + } + //--------- + + if (preferenceScreen == null) { Toasty.error(requireActivity(), getString(R.string.toast_error), Toasty.LENGTH_SHORT).show(); return; } - ListPreference SET_NOTIFICATION_TYPE = findPreference(getString(R.string.SET_NOTIFICATION_TYPE)); String[] notificationValues = getResources().getStringArray(R.array.SET_NOTIFICATION_TYPE_VALUE); if (SET_NOTIFICATION_TYPE != null && SET_NOTIFICATION_TYPE.getValue().equals(notificationValues[2])) { PreferenceCategory notification_sounds = findPreference("notification_sounds"); @@ -97,26 +122,21 @@ public class FragmentNotificationsSettings extends PreferenceFragmentCompat impl if (notification_time_slot != null) { preferenceScreen.removePreference(notification_time_slot); } - ListPreference SET_NOTIFICATION_DELAY_VALUE = findPreference("SET_NOTIFICATION_DELAY_VALUE"); if (SET_NOTIFICATION_DELAY_VALUE != null) { preferenceScreen.removePreferenceRecursively("SET_NOTIFICATION_DELAY_VALUE"); } - ListPreference SET_PUSH_DISTRIBUTOR = findPreference("SET_PUSH_DISTRIBUTOR"); if (SET_PUSH_DISTRIBUTOR != null) { preferenceScreen.removePreferenceRecursively("SET_PUSH_DISTRIBUTOR"); } return; } else if (SET_NOTIFICATION_TYPE != null && SET_NOTIFICATION_TYPE.getValue().equals(notificationValues[1])) { - ListPreference SET_PUSH_DISTRIBUTOR = findPreference("SET_PUSH_DISTRIBUTOR"); if (SET_PUSH_DISTRIBUTOR != null) { preferenceScreen.removePreferenceRecursively("SET_PUSH_DISTRIBUTOR"); } } else { - ListPreference SET_NOTIFICATION_DELAY_VALUE = findPreference("SET_NOTIFICATION_DELAY_VALUE"); if (SET_NOTIFICATION_DELAY_VALUE != null) { preferenceScreen.removePreferenceRecursively("SET_NOTIFICATION_DELAY_VALUE"); } - ListPreference SET_PUSH_DISTRIBUTOR = findPreference(getString(R.string.SET_PUSH_DISTRIBUTOR)); if (SET_PUSH_DISTRIBUTOR != null) { List distributors = UnifiedPush.getDistributors(requireActivity(), new ArrayList<>()); SET_PUSH_DISTRIBUTOR.setValue(UnifiedPush.getDistributor(requireActivity())); diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentThemingSettings.java b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentThemingSettings.java index f9e77b55..e6e42cbb 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentThemingSettings.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentThemingSettings.java @@ -114,6 +114,22 @@ public class FragmentThemingSettings extends PreferenceFragmentCompat implements Toasty.error(requireActivity(), getString(R.string.toast_error), Toasty.LENGTH_SHORT).show(); } SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(requireActivity()); + + //Theme for dialogs + ListPreference SET_THEME_BASE = findPreference(getString(R.string.SET_THEME_BASE)); + if (SET_THEME_BASE != null) { + SET_THEME_BASE.getContext().setTheme(Helper.dialogStyle()); + } + ListPreference SET_THEME_DEFAULT_LIGHT = findPreference(getString(R.string.SET_THEME_DEFAULT_LIGHT)); + if (SET_THEME_DEFAULT_LIGHT != null) { + SET_THEME_DEFAULT_LIGHT.getContext().setTheme(Helper.dialogStyle()); + } + ListPreference SET_THEME_DEFAULT_DARK = findPreference(getString(R.string.SET_THEME_DEFAULT_DARK)); + if (SET_THEME_DEFAULT_DARK != null) { + SET_THEME_DEFAULT_DARK.getContext().setTheme(Helper.dialogStyle()); + } + //--------- + SwitchPreferenceCompat SET_DYNAMIC_COLOR = findPreference(getString(R.string.SET_DYNAMICCOLOR)); SwitchPreferenceCompat SET_CUSTOM_ACCENT = findPreference(getString(R.string.SET_CUSTOM_ACCENT)); ColorPreferenceCompat SET_CUSTOM_ACCENT_DARK_VALUE = findPreference(getString(R.string.SET_CUSTOM_ACCENT_DARK_VALUE)); diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentTimelinesSettings.java b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentTimelinesSettings.java index 77946049..0383e1f8 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentTimelinesSettings.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/settings/FragmentTimelinesSettings.java @@ -31,6 +31,7 @@ import app.fedilab.android.mastodon.helper.Helper; public class FragmentTimelinesSettings extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener { boolean recreate; + @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { addPreferencesFromResource(R.xml.pref_timelines); @@ -47,7 +48,18 @@ public class FragmentTimelinesSettings extends PreferenceFragmentCompat implemen ListPreference SET_TRANSLATOR = findPreference(getString(R.string.SET_TRANSLATOR)); ListPreference SET_TRANSLATOR_VERSION = findPreference(getString(R.string.SET_TRANSLATOR_VERSION)); - + //Theme for dialogs + if (SET_TRANSLATOR_VERSION != null) { + SET_TRANSLATOR_VERSION.getContext().setTheme(Helper.dialogStyle()); + } + if (SET_TRANSLATOR != null) { + SET_TRANSLATOR.getContext().setTheme(Helper.dialogStyle()); + } + ListPreference SET_LOAD_MEDIA_TYPE = findPreference(getString(R.string.SET_LOAD_MEDIA_TYPE)); + if (SET_LOAD_MEDIA_TYPE != null) { + SET_LOAD_MEDIA_TYPE.getContext().setTheme(Helper.dialogStyle()); + } + //--------- EditTextPreference SET_TRANSLATOR_API_KEY = findPreference(getString(R.string.SET_TRANSLATOR_API_KEY)); EditTextPreference SET_TRANSLATOR_DOMAIN = findPreference(getString(R.string.SET_TRANSLATOR_DOMAIN)); if (SET_TRANSLATOR != null && !SET_TRANSLATOR.getValue().equals("DEEPL")) { diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentMastodonAccount.java b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentMastodonAccount.java index 4e26ec8e..f55c7492 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentMastodonAccount.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentMastodonAccount.java @@ -15,6 +15,7 @@ package app.fedilab.android.mastodon.ui.fragment.timeline; * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; import static app.fedilab.android.BaseMainActivity.currentInstance; import static app.fedilab.android.BaseMainActivity.currentToken; import static app.fedilab.android.mastodon.helper.MastodonHelper.ACCOUNTS_PER_CALL; @@ -38,14 +39,15 @@ import java.util.List; import app.fedilab.android.BaseMainActivity; import app.fedilab.android.R; -import app.fedilab.android.activities.MainActivity; import app.fedilab.android.databinding.FragmentPaginationBinding; import app.fedilab.android.mastodon.activities.SearchResultTabActivity; import app.fedilab.android.mastodon.client.entities.api.Account; import app.fedilab.android.mastodon.client.entities.api.Accounts; import app.fedilab.android.mastodon.client.entities.api.Pagination; import app.fedilab.android.mastodon.client.entities.api.RelationShip; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.client.entities.app.Timeline; +import app.fedilab.android.mastodon.exception.DBException; import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.helper.MastodonHelper; import app.fedilab.android.mastodon.ui.drawer.AccountAdapter; @@ -77,19 +79,49 @@ public class FragmentMastodonAccount extends Fragment { public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - if (getArguments() != null) { - search = getArguments().getString(Helper.ARG_SEARCH_KEYWORD, null); - accountTimeline = (Account) getArguments().getSerializable(Helper.ARG_ACCOUNT); - followType = (FedilabProfileTLPageAdapter.follow_type) getArguments().getSerializable(Helper.ARG_FOLLOW_TYPE); - viewModelKey = getArguments().getString(Helper.ARG_VIEW_MODEL_KEY, ""); - timelineType = (Timeline.TimeLineEnum) getArguments().get(Helper.ARG_TIMELINE_TYPE); - order = getArguments().getString(Helper.ARG_DIRECTORY_ORDER, "active"); - local = getArguments().getBoolean(Helper.ARG_DIRECTORY_LOCAL, false); - checkRemotely = getArguments().getBoolean(Helper.ARG_CHECK_REMOTELY, false); - } + instance = currentInstance; token = currentToken; + flagLoading = false; + binding = FragmentPaginationBinding.inflate(inflater, container, false); + SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(requireActivity()); + boolean displayScrollBar = sharedpreferences.getBoolean(getString(R.string.SET_TIMELINE_SCROLLBAR), false); + binding.recyclerView.setVerticalScrollBarEnabled(displayScrollBar); + if (getArguments() != null) { + long bundleId = getArguments().getLong(Helper.ARG_INTENT_ID, -1); + if (bundleId != -1) { + new CachedBundle(requireActivity()).getBundle(bundleId, currentAccount, this::initializeAfterBundle); + } else { + if (getArguments().containsKey(Helper.ARG_CACHED_ACCOUNT_ID)) { + try { + accountTimeline = new CachedBundle(requireActivity()).getCachedAccount(currentAccount, getArguments().getString(Helper.ARG_CACHED_ACCOUNT_ID)); + } catch (DBException e) { + e.printStackTrace(); + } + } + initializeAfterBundle(getArguments()); + } + } else { + initializeAfterBundle(null); + } + + return binding.getRoot(); + } + + private void initializeAfterBundle(Bundle bundle) { + if (bundle != null) { + search = bundle.getString(Helper.ARG_SEARCH_KEYWORD, null); + if (bundle.containsKey(Helper.ARG_ACCOUNT)) { + accountTimeline = (Account) bundle.getSerializable(Helper.ARG_ACCOUNT); + } + followType = (FedilabProfileTLPageAdapter.follow_type) bundle.getSerializable(Helper.ARG_FOLLOW_TYPE); + viewModelKey = bundle.getString(Helper.ARG_VIEW_MODEL_KEY, ""); + timelineType = (Timeline.TimeLineEnum) bundle.get(Helper.ARG_TIMELINE_TYPE); + order = bundle.getString(Helper.ARG_DIRECTORY_ORDER, "active"); + local = bundle.getBoolean(Helper.ARG_DIRECTORY_LOCAL, false); + checkRemotely = bundle.getBoolean(Helper.ARG_CHECK_REMOTELY, false); + } if (checkRemotely) { String[] acctArray = accountTimeline.acct.split("@"); if (acctArray.length > 1) { @@ -102,20 +134,6 @@ public class FragmentMastodonAccount extends Fragment { token = currentToken; } } - - flagLoading = false; - binding = FragmentPaginationBinding.inflate(inflater, container, false); - SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(requireActivity()); - boolean displayScrollBar = sharedpreferences.getBoolean(getString(R.string.SET_TIMELINE_SCROLLBAR), false); - binding.recyclerView.setVerticalScrollBarEnabled(displayScrollBar); - return binding.getRoot(); - } - - @Override - public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - binding.loader.setVisibility(View.VISIBLE); - binding.recyclerView.setVisibility(View.GONE); accountsVM = new ViewModelProvider(FragmentMastodonAccount.this).get(viewModelKey, AccountsVM.class); max_id = null; offset = 0; @@ -126,6 +144,14 @@ public class FragmentMastodonAccount extends Fragment { router(true); } + @Override + public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + binding.loader.setVisibility(View.VISIBLE); + binding.recyclerView.setVisibility(View.GONE); + + } + /** * Router for timelines */ @@ -206,7 +232,7 @@ public class FragmentMastodonAccount extends Fragment { } } else if (timelineType == Timeline.TimeLineEnum.MUTED_TIMELINE_HOME) { if (firstLoad) { - accountsVM.getMutedHome(MainActivity.currentAccount) + accountsVM.getMutedHome(currentAccount) .observe(getViewLifecycleOwner(), this::initializeAccountCommonView); } } else if (timelineType == Timeline.TimeLineEnum.BLOCKED_TIMELINE) { diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentMastodonContext.java b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentMastodonContext.java index 3adf0c1f..e8d6bc38 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentMastodonContext.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentMastodonContext.java @@ -14,6 +14,7 @@ package app.fedilab.android.mastodon.ui.fragment.timeline; * You should have received a copy of the GNU General Public License along with Fedilab; if not, * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; import static app.fedilab.android.mastodon.activities.ContextActivity.displayCW; import static app.fedilab.android.mastodon.activities.ContextActivity.expand; @@ -21,7 +22,6 @@ import android.content.BroadcastReceiver; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; -import android.os.Build; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; @@ -31,7 +31,6 @@ import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; - import androidx.preference.PreferenceManager; import androidx.recyclerview.widget.LinearLayoutManager; @@ -44,6 +43,7 @@ import app.fedilab.android.databinding.FragmentPaginationBinding; import app.fedilab.android.mastodon.activities.ContextActivity; import app.fedilab.android.mastodon.client.entities.api.Context; import app.fedilab.android.mastodon.client.entities.api.Status; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.client.entities.app.Timeline; import app.fedilab.android.mastodon.helper.DividerDecoration; import app.fedilab.android.mastodon.helper.Helper; @@ -59,75 +59,79 @@ public class FragmentMastodonContext extends Fragment { private StatusesVM statusesVM; private List statuses; private StatusAdapter statusAdapter; - private boolean refresh; //Handle actions that can be done in other fragments private final BroadcastReceiver receive_action = new BroadcastReceiver() { @Override public void onReceive(android.content.Context context, Intent intent) { - Bundle b = intent.getExtras(); - if (b != null) { - Status receivedStatus = (Status) b.getSerializable(Helper.ARG_STATUS_ACTION); - String delete_statuses_for_user = b.getString(Helper.ARG_STATUS_ACCOUNT_ID_DELETED); - Status status_to_delete = (Status) b.getSerializable(Helper.ARG_STATUS_DELETED); - Status statusPosted = (Status) b.getSerializable(Helper.ARG_STATUS_POSTED); - Status status_to_update = (Status) b.getSerializable(Helper.ARG_STATUS_UPDATED); - if (receivedStatus != null && statusAdapter != null) { - int position = getPosition(receivedStatus); - if (position >= 0) { - statuses.get(position).reblog = receivedStatus.reblog; - statuses.get(position).reblogged = receivedStatus.reblogged; - statuses.get(position).favourited = receivedStatus.favourited; - statuses.get(position).bookmarked = receivedStatus.bookmarked; - statuses.get(position).reblogs_count = receivedStatus.reblogs_count; - statuses.get(position).favourites_count = receivedStatus.favourites_count; - statusAdapter.notifyItemChanged(position); - } - } else if (delete_statuses_for_user != null && statusAdapter != null) { - List statusesToRemove = new ArrayList<>(); - for (Status status : statuses) { - if (status.account.id.equals(delete_statuses_for_user)) { - statusesToRemove.add(status); + Bundle args = intent.getExtras(); + if (args != null) { + long bundleId = args.getLong(Helper.ARG_INTENT_ID, -1); + new CachedBundle(requireActivity()).getBundle(bundleId, currentAccount, bundle -> { + Status receivedStatus = (Status) bundle.getSerializable(Helper.ARG_STATUS_ACTION); + String delete_statuses_for_user = bundle.getString(Helper.ARG_STATUS_ACCOUNT_ID_DELETED); + Status status_to_delete = (Status) bundle.getSerializable(Helper.ARG_STATUS_DELETED); + Status statusPosted = (Status) bundle.getSerializable(Helper.ARG_STATUS_POSTED); + Status status_to_update = (Status) bundle.getSerializable(Helper.ARG_STATUS_UPDATED); + if (receivedStatus != null && statusAdapter != null) { + int position = getPosition(receivedStatus); + if (position >= 0) { + statuses.get(position).reblog = receivedStatus.reblog; + statuses.get(position).reblogged = receivedStatus.reblogged; + statuses.get(position).favourited = receivedStatus.favourited; + statuses.get(position).bookmarked = receivedStatus.bookmarked; + statuses.get(position).reblogs_count = receivedStatus.reblogs_count; + statuses.get(position).favourites_count = receivedStatus.favourites_count; + statusAdapter.notifyItemChanged(position); } - } - for (Status statusToRemove : statusesToRemove) { - int position = getPosition(statusToRemove); + } else if (delete_statuses_for_user != null && statusAdapter != null) { + List statusesToRemove = new ArrayList<>(); + for (Status status : statuses) { + if (status.account.id.equals(delete_statuses_for_user)) { + statusesToRemove.add(status); + } + } + for (Status statusToRemove : statusesToRemove) { + int position = getPosition(statusToRemove); + if (position >= 0) { + statuses.remove(position); + statusAdapter.notifyItemRemoved(position); + } + } + } else if (status_to_delete != null && statusAdapter != null) { + int position = getPosition(status_to_delete); if (position >= 0) { statuses.remove(position); statusAdapter.notifyItemRemoved(position); } - } - } else if (status_to_delete != null && statusAdapter != null) { - int position = getPosition(status_to_delete); - if (position >= 0) { - statuses.remove(position); - statusAdapter.notifyItemRemoved(position); - } - } else if (status_to_update != null && statusAdapter != null) { - int position = getPosition(status_to_update); - if (position >= 0) { - statuses.set(position, status_to_update); - statusAdapter.notifyItemChanged(position); - } - } else if (statusPosted != null && statusAdapter != null) { - if (requireActivity() instanceof ContextActivity) { - int i = 0; - for (Status status : statuses) { - if (status.id.equals(statusPosted.in_reply_to_id)) { - statuses.add((i + 1), statusPosted); - statusAdapter.notifyItemInserted((i + 1)); - if (requireActivity() instanceof ContextActivity) { - //Redraw decorations - statusAdapter.notifyItemRangeChanged(0, statuses.size()); + } else if (status_to_update != null && statusAdapter != null) { + int position = getPosition(status_to_update); + if (position >= 0) { + statuses.set(position, status_to_update); + statusAdapter.notifyItemChanged(position); + } + } else if (statusPosted != null && statusAdapter != null) { + if (requireActivity() instanceof ContextActivity) { + int i = 0; + for (Status status : statuses) { + if (status.id.equals(statusPosted.in_reply_to_id)) { + statuses.add((i + 1), statusPosted); + statusAdapter.notifyItemInserted((i + 1)); + if (requireActivity() instanceof ContextActivity) { + //Redraw decorations + statusAdapter.notifyItemRangeChanged(0, statuses.size()); + } + break; } - break; + i++; } - i++; } } - } + }); + } } }; + private boolean refresh; private Status focusedStatus; private String remote_instance, focusedStatusURI; private Status firstStatus; @@ -160,10 +164,21 @@ public class FragmentMastodonContext extends Fragment { pullToRefresh = false; focusedStatusURI = null; refresh = true; + binding = FragmentPaginationBinding.inflate(inflater, container, false); if (getArguments() != null) { - focusedStatus = (Status) getArguments().getSerializable(Helper.ARG_STATUS); - remote_instance = getArguments().getString(Helper.ARG_REMOTE_INSTANCE, null); - focusedStatusURI = getArguments().getString(Helper.ARG_FOCUSED_STATUS_URI, null); + long bundleId = getArguments().getLong(Helper.ARG_INTENT_ID, -1); + new CachedBundle(requireActivity()).getBundle(bundleId, currentAccount, this::initializeAfterBundle); + } else { + initializeAfterBundle(null); + } + return binding.getRoot(); + } + + private void initializeAfterBundle(Bundle bundle) { + if (bundle != null) { + focusedStatus = (Status) bundle.getSerializable(Helper.ARG_STATUS); + remote_instance = bundle.getString(Helper.ARG_REMOTE_INSTANCE, null); + focusedStatusURI = bundle.getString(Helper.ARG_FOCUSED_STATUS_URI, null); } if (remote_instance != null) { user_instance = remote_instance; @@ -176,7 +191,7 @@ public class FragmentMastodonContext extends Fragment { getChildFragmentManager().beginTransaction().remove(this).commit(); } - binding = FragmentPaginationBinding.inflate(inflater, container, false); + SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(requireActivity()); boolean displayScrollBar = sharedpreferences.getBoolean(getString(R.string.SET_TIMELINE_SCROLLBAR), false); binding.recyclerView.setVerticalScrollBarEnabled(displayScrollBar); @@ -204,9 +219,9 @@ public class FragmentMastodonContext extends Fragment { } ContextCompat.registerReceiver(requireActivity(), receive_action, new IntentFilter(Helper.RECEIVE_STATUS_ACTION), ContextCompat.RECEIVER_NOT_EXPORTED); - return binding.getRoot(); } + public void refresh() { if (statuses != null) { for (Status status : statuses) { diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentMastodonDirectMessage.java b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentMastodonDirectMessage.java index 3c0a6164..0459e119 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentMastodonDirectMessage.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentMastodonDirectMessage.java @@ -50,7 +50,6 @@ import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; - import androidx.preference.PreferenceManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.work.Data; @@ -83,6 +82,7 @@ import app.fedilab.android.mastodon.client.entities.api.Context; import app.fedilab.android.mastodon.client.entities.api.Mention; import app.fedilab.android.mastodon.client.entities.api.Poll; import app.fedilab.android.mastodon.client.entities.api.Status; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.client.entities.app.StatusDraft; import app.fedilab.android.mastodon.exception.DBException; import app.fedilab.android.mastodon.helper.Helper; @@ -112,17 +112,19 @@ public class FragmentMastodonDirectMessage extends Fragment { private final BroadcastReceiver broadcast_data = new BroadcastReceiver() { @Override public void onReceive(android.content.Context context, Intent intent) { - Bundle b = intent.getExtras(); - if (b != null) { - - if (b.getBoolean(Helper.RECEIVE_NEW_MESSAGE, false)) { - Status statusReceived = (Status) b.getSerializable(Helper.RECEIVE_STATUS_ACTION); - if (statusReceived != null) { - statuses.add(statusReceived); - statusDirectMessageAdapter.notifyItemInserted(statuses.size() - 1); - initiliazeStatus(); + Bundle args = intent.getExtras(); + if (args != null) { + long bundleId = args.getLong(Helper.ARG_INTENT_ID, -1); + new CachedBundle(requireActivity()).getBundle(bundleId, currentAccount, bundle -> { + if (bundle.getBoolean(Helper.RECEIVE_NEW_MESSAGE, false)) { + Status statusReceived = (Status) bundle.getSerializable(Helper.RECEIVE_STATUS_ACTION); + if (statusReceived != null) { + statuses.add(statusReceived); + statusDirectMessageAdapter.notifyItemInserted(statuses.size() - 1); + initiliazeStatus(); + } } - } + }); } } }; @@ -132,8 +134,21 @@ public class FragmentMastodonDirectMessage extends Fragment { focusedStatus = null; pullToRefresh = false; + binding = FragmentDirectMessageBinding.inflate(inflater, container, false); if (getArguments() != null) { - focusedStatus = (Status) getArguments().getSerializable(Helper.ARG_STATUS); + long bundleId = getArguments().getLong(Helper.ARG_INTENT_ID, -1); + new CachedBundle(requireActivity()).getBundle(bundleId, currentAccount, this::initializeAfterBundle); + } else { + initializeAfterBundle(null); + } + return binding.getRoot(); + } + + + private void initializeAfterBundle(Bundle bundle) { + + if (bundle != null) { + focusedStatus = (Status) bundle.getSerializable(Helper.ARG_STATUS); } user_instance = MainActivity.currentInstance; user_token = MainActivity.currentToken; @@ -141,7 +156,7 @@ public class FragmentMastodonDirectMessage extends Fragment { if (focusedStatus == null) { getChildFragmentManager().beginTransaction().remove(this).commit(); } - binding = FragmentDirectMessageBinding.inflate(inflater, container, false); + statusesVM = new ViewModelProvider(FragmentMastodonDirectMessage.this).get(StatusesVM.class); binding.recyclerView.setNestedScrollingEnabled(true); this.statuses = new ArrayList<>(); @@ -217,10 +232,8 @@ public class FragmentMastodonDirectMessage extends Fragment { } }); - return binding.getRoot(); } - private void onSubmit(StatusDraft statusDraft) { new Thread(() -> { if (statusDraft.instance == null) { diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentMastodonNotification.java b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentMastodonNotification.java index e5f09fa7..f9fbaf8b 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentMastodonNotification.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentMastodonNotification.java @@ -14,12 +14,13 @@ package app.fedilab.android.mastodon.ui.fragment.timeline; * You should have received a copy of the GNU General Public License along with Fedilab; if not, * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; + import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; -import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; @@ -31,7 +32,6 @@ import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; - import androidx.preference.PreferenceManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; @@ -49,6 +49,7 @@ import app.fedilab.android.databinding.FragmentPaginationBinding; import app.fedilab.android.mastodon.client.entities.api.Notification; import app.fedilab.android.mastodon.client.entities.api.Notifications; import app.fedilab.android.mastodon.client.entities.api.Status; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.client.entities.app.StatusCache; import app.fedilab.android.mastodon.client.entities.app.Timeline; import app.fedilab.android.mastodon.exception.DBException; @@ -73,43 +74,46 @@ public class FragmentMastodonNotification extends Fragment implements Notificati private final BroadcastReceiver receive_action = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { - Bundle b = intent.getExtras(); - if (b != null) { - Status receivedStatus = (Status) b.getSerializable(Helper.ARG_STATUS_ACTION); - String delete_all_for_account_id = b.getString(Helper.ARG_DELETE_ALL_FOR_ACCOUNT_ID); - boolean refreshNotifications = b.getBoolean(Helper.ARG_REFRESH_NOTFICATION, false); - if (refreshNotifications) { - scrollToTop(); - } else if (receivedStatus != null && notificationAdapter != null) { - int position = getPosition(receivedStatus); - if (position >= 0) { - if (notificationList.get(position).status != null) { - notificationList.get(position).status.reblog = receivedStatus.reblog; - notificationList.get(position).status.reblogged = receivedStatus.reblogged; - notificationList.get(position).status.favourited = receivedStatus.favourited; - notificationList.get(position).status.bookmarked = receivedStatus.bookmarked; - notificationList.get(position).status.favourites_count = receivedStatus.favourites_count; - notificationList.get(position).status.reblogs_count = receivedStatus.reblogs_count; - notificationAdapter.notifyItemChanged(position); + Bundle args = intent.getExtras(); + if (args != null) { + long bundleId = args.getLong(Helper.ARG_INTENT_ID, -1); + new CachedBundle(requireActivity()).getBundle(bundleId, currentAccount, bundle -> { + Status receivedStatus = (Status) bundle.getSerializable(Helper.ARG_STATUS_ACTION); + String delete_all_for_account_id = bundle.getString(Helper.ARG_DELETE_ALL_FOR_ACCOUNT_ID); + boolean refreshNotifications = bundle.getBoolean(Helper.ARG_REFRESH_NOTFICATION, false); + if (refreshNotifications) { + scrollToTop(); + } else if (receivedStatus != null && notificationAdapter != null) { + int position = getPosition(receivedStatus); + if (position >= 0) { + if (notificationList.get(position).status != null) { + notificationList.get(position).status.reblog = receivedStatus.reblog; + notificationList.get(position).status.reblogged = receivedStatus.reblogged; + notificationList.get(position).status.favourited = receivedStatus.favourited; + notificationList.get(position).status.bookmarked = receivedStatus.bookmarked; + notificationList.get(position).status.favourites_count = receivedStatus.favourites_count; + notificationList.get(position).status.reblogs_count = receivedStatus.reblogs_count; + notificationAdapter.notifyItemChanged(position); + } } - } - } else if (delete_all_for_account_id != null) { - List toRemove = new ArrayList<>(); - if (notificationList != null) { - for (int position = 0; position < notificationList.size(); position++) { - if (notificationList.get(position).account.id.equals(delete_all_for_account_id)) { - toRemove.add(notificationList.get(position)); + } else if (delete_all_for_account_id != null) { + List toRemove = new ArrayList<>(); + if (notificationList != null) { + for (int position = 0; position < notificationList.size(); position++) { + if (notificationList.get(position).account.id.equals(delete_all_for_account_id)) { + toRemove.add(notificationList.get(position)); + } } } - } - if (toRemove.size() > 0) { - for (int i = 0; i < toRemove.size(); i++) { - int position = getPosition(toRemove.get(i)); - notificationList.remove(position); - notificationAdapter.notifyItemRemoved(position); + if (toRemove.size() > 0) { + for (int i = 0; i < toRemove.size(); i++) { + int position = getPosition(toRemove.get(i)); + notificationList.remove(position); + notificationAdapter.notifyItemRemoved(position); + } } } - } + }); } } }; diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentMastodonTag.java b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentMastodonTag.java index d0027c98..0682ceef 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentMastodonTag.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentMastodonTag.java @@ -170,7 +170,7 @@ public class FragmentMastodonTag extends Fragment { Collections.sort(tags, (obj1, obj2) -> Integer.compare(obj2.getWeight(), obj1.getWeight())); boolean isInCollection = false; for (Tag tag : tags) { - if (tag.name.compareToIgnoreCase(search) == 0) { + if (tag.name.trim().compareToIgnoreCase(search.trim()) == 0) { isInCollection = true; break; } diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentMastodonTimeline.java b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentMastodonTimeline.java index 64ee7268..6a64147c 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentMastodonTimeline.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentMastodonTimeline.java @@ -15,6 +15,7 @@ package app.fedilab.android.mastodon.ui.fragment.timeline; * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; import static app.fedilab.android.BaseMainActivity.currentInstance; import static app.fedilab.android.BaseMainActivity.networkAvailable; @@ -35,7 +36,6 @@ import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; - import androidx.preference.PreferenceManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; @@ -57,10 +57,12 @@ import app.fedilab.android.mastodon.client.entities.api.Pagination; import app.fedilab.android.mastodon.client.entities.api.Status; import app.fedilab.android.mastodon.client.entities.api.Statuses; import app.fedilab.android.mastodon.client.entities.app.BubbleTimeline; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.client.entities.app.PinnedTimeline; import app.fedilab.android.mastodon.client.entities.app.RemoteInstance; import app.fedilab.android.mastodon.client.entities.app.TagTimeline; import app.fedilab.android.mastodon.client.entities.app.Timeline; +import app.fedilab.android.mastodon.exception.DBException; import app.fedilab.android.mastodon.helper.CrossActionHelper; import app.fedilab.android.mastodon.helper.GlideApp; import app.fedilab.android.mastodon.helper.Helper; @@ -92,88 +94,91 @@ public class FragmentMastodonTimeline extends Fragment implements StatusAdapter. private final BroadcastReceiver receive_action = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { - Bundle b = intent.getExtras(); - if (b != null) { - Status receivedStatus = (Status) b.getSerializable(Helper.ARG_STATUS_ACTION); - String delete_statuses_for_user = b.getString(Helper.ARG_STATUS_ACCOUNT_ID_DELETED); - String delete_all_for_account_id = b.getString(Helper.ARG_DELETE_ALL_FOR_ACCOUNT_ID); - Status status_to_delete = (Status) b.getSerializable(Helper.ARG_STATUS_DELETED); - Status status_to_update = (Status) b.getSerializable(Helper.ARG_STATUS_UPDATED); - Status statusPosted = (Status) b.getSerializable(Helper.ARG_STATUS_DELETED); - boolean refreshAll = b.getBoolean(Helper.ARG_TIMELINE_REFRESH_ALL, false); - if (receivedStatus != null && statusAdapter != null) { - int position = getPosition(receivedStatus); - if (position >= 0) { - if (receivedStatus.reblog != null) { - timelineStatuses.get(position).reblog = receivedStatus.reblog; - } - if (timelineStatuses.get(position).reblog != null) { - timelineStatuses.get(position).reblog.reblogged = receivedStatus.reblogged; - timelineStatuses.get(position).reblog.favourited = receivedStatus.favourited; - timelineStatuses.get(position).reblog.bookmarked = receivedStatus.bookmarked; - timelineStatuses.get(position).reblog.reblogs_count = receivedStatus.reblogs_count; - timelineStatuses.get(position).reblog.favourites_count = receivedStatus.favourites_count; - } else { - timelineStatuses.get(position).reblogged = receivedStatus.reblogged; - timelineStatuses.get(position).favourited = receivedStatus.favourited; - timelineStatuses.get(position).bookmarked = receivedStatus.bookmarked; - timelineStatuses.get(position).reblogs_count = receivedStatus.reblogs_count; - timelineStatuses.get(position).favourites_count = receivedStatus.favourites_count; - } + Bundle args = intent.getExtras(); + if (args != null) { + long bundleId = args.getLong(Helper.ARG_INTENT_ID, -1); + new CachedBundle(requireActivity()).getBundle(bundleId, currentAccount, bundle -> { + Status receivedStatus = (Status) bundle.getSerializable(Helper.ARG_STATUS_ACTION); + String delete_statuses_for_user = bundle.getString(Helper.ARG_STATUS_ACCOUNT_ID_DELETED); + String delete_all_for_account_id = bundle.getString(Helper.ARG_DELETE_ALL_FOR_ACCOUNT_ID); + Status status_to_delete = (Status) bundle.getSerializable(Helper.ARG_STATUS_DELETED); + Status status_to_update = (Status) bundle.getSerializable(Helper.ARG_STATUS_UPDATED); + Status statusPosted = (Status) bundle.getSerializable(Helper.ARG_STATUS_DELETED); + boolean refreshAll = bundle.getBoolean(Helper.ARG_TIMELINE_REFRESH_ALL, false); + if (receivedStatus != null && statusAdapter != null) { + int position = getPosition(receivedStatus); + if (position >= 0) { + if (receivedStatus.reblog != null) { + timelineStatuses.get(position).reblog = receivedStatus.reblog; + } + if (timelineStatuses.get(position).reblog != null) { + timelineStatuses.get(position).reblog.reblogged = receivedStatus.reblogged; + timelineStatuses.get(position).reblog.favourited = receivedStatus.favourited; + timelineStatuses.get(position).reblog.bookmarked = receivedStatus.bookmarked; + timelineStatuses.get(position).reblog.reblogs_count = receivedStatus.reblogs_count; + timelineStatuses.get(position).reblog.favourites_count = receivedStatus.favourites_count; + } else { + timelineStatuses.get(position).reblogged = receivedStatus.reblogged; + timelineStatuses.get(position).favourited = receivedStatus.favourited; + timelineStatuses.get(position).bookmarked = receivedStatus.bookmarked; + timelineStatuses.get(position).reblogs_count = receivedStatus.reblogs_count; + timelineStatuses.get(position).favourites_count = receivedStatus.favourites_count; + } - statusAdapter.notifyItemChanged(position); - } - } else if (delete_statuses_for_user != null && statusAdapter != null) { - List statusesToRemove = new ArrayList<>(); - for (Status status : timelineStatuses) { - if (status != null && status.account != null && status.account.id != null && status.account.id.equals(delete_statuses_for_user)) { - statusesToRemove.add(status); + statusAdapter.notifyItemChanged(position); } - } - for (Status statusToRemove : statusesToRemove) { - int position = getPosition(statusToRemove); + } else if (delete_statuses_for_user != null && statusAdapter != null) { + List statusesToRemove = new ArrayList<>(); + for (Status status : timelineStatuses) { + if (status != null && status.account != null && status.account.id != null && status.account.id.equals(delete_statuses_for_user)) { + statusesToRemove.add(status); + } + } + for (Status statusToRemove : statusesToRemove) { + int position = getPosition(statusToRemove); + if (position >= 0) { + timelineStatuses.remove(position); + statusAdapter.notifyItemRemoved(position); + } + } + } else if (status_to_delete != null && statusAdapter != null) { + int position = getPosition(status_to_delete); if (position >= 0) { timelineStatuses.remove(position); statusAdapter.notifyItemRemoved(position); } - } - } else if (status_to_delete != null && statusAdapter != null) { - int position = getPosition(status_to_delete); - if (position >= 0) { - timelineStatuses.remove(position); - statusAdapter.notifyItemRemoved(position); - } - } else if (status_to_update != null && statusAdapter != null) { - int position = getPosition(status_to_update); - if (position >= 0) { - timelineStatuses.set(position, status_to_update); - statusAdapter.notifyItemChanged(position); - } - } else if (statusPosted != null && statusAdapter != null && timelineType == Timeline.TimeLineEnum.HOME) { - timelineStatuses.add(0, statusPosted); - statusAdapter.notifyItemInserted(0); - } else if (delete_all_for_account_id != null) { - List toRemove = new ArrayList<>(); - if (timelineStatuses != null) { - for (int position = 0; position < timelineStatuses.size(); position++) { - if (timelineStatuses.get(position).account.id.equals(delete_all_for_account_id)) { - toRemove.add(timelineStatuses.get(position)); + } else if (status_to_update != null && statusAdapter != null) { + int position = getPosition(status_to_update); + if (position >= 0) { + timelineStatuses.set(position, status_to_update); + statusAdapter.notifyItemChanged(position); + } + } else if (statusPosted != null && statusAdapter != null && timelineType == Timeline.TimeLineEnum.HOME) { + timelineStatuses.add(0, statusPosted); + statusAdapter.notifyItemInserted(0); + } else if (delete_all_for_account_id != null) { + List toRemove = new ArrayList<>(); + if (timelineStatuses != null) { + for (int position = 0; position < timelineStatuses.size(); position++) { + if (timelineStatuses.get(position).account.id.equals(delete_all_for_account_id)) { + toRemove.add(timelineStatuses.get(position)); + } } } - } - if (toRemove.size() > 0) { - for (int i = 0; i < toRemove.size(); i++) { - int position = getPosition(toRemove.get(i)); - if (position >= 0) { - timelineStatuses.remove(position); - statusAdapter.notifyItemRemoved(position); + if (toRemove.size() > 0) { + for (int i = 0; i < toRemove.size(); i++) { + int position = getPosition(toRemove.get(i)); + if (position >= 0) { + timelineStatuses.remove(position); + statusAdapter.notifyItemRemoved(position); + } } } + } else if (refreshAll) { + refreshAllAdapters(); } - } else if (refreshAll) { - refreshAllAdapters(); - } + }); } } }; @@ -346,29 +351,12 @@ public class FragmentMastodonTimeline extends Fragment implements StatusAdapter. @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); - timelinesVM = new ViewModelProvider(FragmentMastodonTimeline.this).get(viewModelKey, TimelinesVM.class); - accountsVM = new ViewModelProvider(FragmentMastodonTimeline.this).get(viewModelKey, AccountsVM.class); - initialStatuses = null; - lockForResumeCall = 0; binding.loader.setVisibility(View.VISIBLE); binding.recyclerView.setVisibility(View.GONE); - SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(requireActivity()); - max_id = statusReport != null ? statusReport.id : null; - offset = 0; - - rememberPosition = sharedpreferences.getBoolean(getString(R.string.SET_REMEMBER_POSITION), true); - //Inner marker are only for pinned timelines and main timelines, they have isViewInitialized set to false - if (max_id == null && !isViewInitialized && rememberPosition) { - max_id = sharedpreferences.getString(getString(R.string.SET_INNER_MARKER) + BaseMainActivity.currentUserID + BaseMainActivity.currentInstance + slug, null); - } if (search != null) { binding.swipeContainer.setRefreshing(false); binding.swipeContainer.setEnabled(false); } - //Only fragment in main view pager should not have the view initialized - //AND Only the first fragment will initialize its view - flagLoading = false; - } @Override @@ -378,16 +366,36 @@ public class FragmentMastodonTimeline extends Fragment implements StatusAdapter. public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + timelineType = Timeline.TimeLineEnum.HOME; - canBeFederated = true; - retry_for_home_done = false; + binding = FragmentPaginationBinding.inflate(inflater, container, false); if (getArguments() != null) { - timelineType = (Timeline.TimeLineEnum) getArguments().get(Helper.ARG_TIMELINE_TYPE); - lemmy_post_id = getArguments().getString(Helper.ARG_LEMMY_POST_ID, null); - list_id = getArguments().getString(Helper.ARG_LIST_ID, null); - search = getArguments().getString(Helper.ARG_SEARCH_KEYWORD, null); - searchCache = getArguments().getString(Helper.ARG_SEARCH_KEYWORD_CACHE, null); - pinnedTimeline = (PinnedTimeline) getArguments().getSerializable(Helper.ARG_REMOTE_INSTANCE); + long bundleId = getArguments().getLong(Helper.ARG_INTENT_ID, -1); + if (bundleId != -1) { + new CachedBundle(requireActivity()).getBundle(bundleId, currentAccount, this::initializeAfterBundle); + } else { + if (getArguments().containsKey(Helper.ARG_CACHED_ACCOUNT_ID)) { + try { + accountTimeline = new CachedBundle(requireActivity()).getCachedAccount(currentAccount, getArguments().getString(Helper.ARG_CACHED_ACCOUNT_ID)); + } catch (DBException e) { + e.printStackTrace(); + } + } + initializeAfterBundle(getArguments()); + } + } + return binding.getRoot(); + } + + private void initializeAfterBundle(Bundle bundle) { + if (bundle != null) { + timelineType = (Timeline.TimeLineEnum) bundle.get(Helper.ARG_TIMELINE_TYPE); + lemmy_post_id = bundle.getString(Helper.ARG_LEMMY_POST_ID, null); + list_id = bundle.getString(Helper.ARG_LIST_ID, null); + search = bundle.getString(Helper.ARG_SEARCH_KEYWORD, null); + searchCache = bundle.getString(Helper.ARG_SEARCH_KEYWORD_CACHE, null); + pinnedTimeline = (PinnedTimeline) bundle.getSerializable(Helper.ARG_REMOTE_INSTANCE); + if (pinnedTimeline != null && pinnedTimeline.remoteInstance != null) { if (pinnedTimeline.remoteInstance.type != RemoteInstance.InstanceType.NITTER) { remoteInstance = pinnedTimeline.remoteInstance.host; @@ -400,24 +408,24 @@ public class FragmentMastodonTimeline extends Fragment implements StatusAdapter. if (timelineType == Timeline.TimeLineEnum.TREND_MESSAGE_PUBLIC) { canBeFederated = false; } - publicTrendsDomain = getArguments().getString(Helper.ARG_REMOTE_INSTANCE_STRING, null); - isViewInitialized = getArguments().getBoolean(Helper.ARG_INITIALIZE_VIEW, true); + publicTrendsDomain = bundle.getString(Helper.ARG_REMOTE_INSTANCE_STRING, null); + isViewInitialized = bundle.getBoolean(Helper.ARG_INITIALIZE_VIEW, true); isNotPinnedTimeline = isViewInitialized; - tagTimeline = (TagTimeline) getArguments().getSerializable(Helper.ARG_TAG_TIMELINE); - bubbleTimeline = (BubbleTimeline) getArguments().getSerializable(Helper.ARG_BUBBLE_TIMELINE); - accountTimeline = (Account) getArguments().getSerializable(Helper.ARG_ACCOUNT); - exclude_replies = !getArguments().getBoolean(Helper.ARG_SHOW_REPLIES, true); - checkRemotely = getArguments().getBoolean(Helper.ARG_CHECK_REMOTELY, false); - show_pinned = getArguments().getBoolean(Helper.ARG_SHOW_PINNED, false); - exclude_reblogs = !getArguments().getBoolean(Helper.ARG_SHOW_REBLOGS, true); - media_only = getArguments().getBoolean(Helper.ARG_SHOW_MEDIA_ONY, false); - viewModelKey = getArguments().getString(Helper.ARG_VIEW_MODEL_KEY, ""); - minified = getArguments().getBoolean(Helper.ARG_MINIFIED, false); - statusReport = (Status) getArguments().getSerializable(Helper.ARG_STATUS_REPORT); - initialStatus = (Status) getArguments().getSerializable(Helper.ARG_STATUS); + tagTimeline = (TagTimeline) bundle.getSerializable(Helper.ARG_TAG_TIMELINE); + bubbleTimeline = (BubbleTimeline) bundle.getSerializable(Helper.ARG_BUBBLE_TIMELINE); + if (bundle.containsKey(Helper.ARG_ACCOUNT)) { + accountTimeline = (Account) bundle.getSerializable(Helper.ARG_ACCOUNT); + } + exclude_replies = !bundle.getBoolean(Helper.ARG_SHOW_REPLIES, true); + checkRemotely = bundle.getBoolean(Helper.ARG_CHECK_REMOTELY, false); + show_pinned = bundle.getBoolean(Helper.ARG_SHOW_PINNED, false); + exclude_reblogs = !bundle.getBoolean(Helper.ARG_SHOW_REBLOGS, true); + media_only = bundle.getBoolean(Helper.ARG_SHOW_MEDIA_ONY, false); + viewModelKey = bundle.getString(Helper.ARG_VIEW_MODEL_KEY, ""); + minified = bundle.getBoolean(Helper.ARG_MINIFIED, false); + statusReport = (Status) bundle.getSerializable(Helper.ARG_STATUS_REPORT); + initialStatus = (Status) bundle.getSerializable(Helper.ARG_STATUS); } - - //When visiting a profile without being authenticated if (checkRemotely) { String[] acctArray = accountTimeline.acct.split("@"); @@ -454,13 +462,28 @@ public class FragmentMastodonTimeline extends Fragment implements StatusAdapter. slug = timelineType != Timeline.TimeLineEnum.ART ? timelineType.getValue() + (ident != null ? "|" + ident : "") : Timeline.TimeLineEnum.TAG.getValue() + (ident != null ? "|" + ident : ""); } + timelinesVM = new ViewModelProvider(FragmentMastodonTimeline.this).get(viewModelKey, TimelinesVM.class); + accountsVM = new ViewModelProvider(FragmentMastodonTimeline.this).get(viewModelKey, AccountsVM.class); + initialStatuses = null; + lockForResumeCall = 0; - ContextCompat.registerReceiver(requireActivity(), receive_action, new IntentFilter(Helper.RECEIVE_STATUS_ACTION), ContextCompat.RECEIVER_NOT_EXPORTED); - binding = FragmentPaginationBinding.inflate(inflater, container, false); + canBeFederated = true; + retry_for_home_done = false; SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(requireActivity()); boolean displayScrollBar = sharedpreferences.getBoolean(getString(R.string.SET_TIMELINE_SCROLLBAR), false); binding.recyclerView.setVerticalScrollBarEnabled(displayScrollBar); - return binding.getRoot(); + max_id = statusReport != null ? statusReport.id : null; + offset = 0; + rememberPosition = sharedpreferences.getBoolean(getString(R.string.SET_REMEMBER_POSITION), true); + //Inner marker are only for pinned timelines and main timelines, they have isViewInitialized set to false + if (max_id == null && !isViewInitialized && rememberPosition) { + max_id = sharedpreferences.getString(getString(R.string.SET_INNER_MARKER) + BaseMainActivity.currentUserID + BaseMainActivity.currentInstance + slug, null); + } + //Only fragment in main view pager should not have the view initialized + //AND Only the first fragment will initialize its view + flagLoading = false; + + ContextCompat.registerReceiver(requireActivity(), receive_action, new IntentFilter(Helper.RECEIVE_STATUS_ACTION), ContextCompat.RECEIVER_NOT_EXPORTED); } /** diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentNotificationContainer.java b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentNotificationContainer.java index fa5736bd..906dbc3a 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentNotificationContainer.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentNotificationContainer.java @@ -114,42 +114,42 @@ public class FragmentNotificationContainer extends Fragment { String[] categoriesArray = excludedCategories.split("\\|"); for (String category : categoriesArray) { switch (category) { - case "mention": + case "mention" -> { excludedCategoriesList.add("mention"); dialogView.displayMentions.setChecked(false); - break; - case "favourite": + } + case "favourite" -> { excludedCategoriesList.add("favourite"); dialogView.displayFavourites.setChecked(false); - break; - case "reblog": + } + case "reblog" -> { excludedCategoriesList.add("reblog"); dialogView.displayReblogs.setChecked(false); - break; - case "poll": + } + case "poll" -> { excludedCategoriesList.add("poll"); dialogView.displayPollResults.setChecked(false); - break; - case "status": + } + case "status" -> { excludedCategoriesList.add("status"); dialogView.displayUpdatesFromPeople.setChecked(false); - break; - case "follow": + } + case "follow" -> { excludedCategoriesList.add("follow"); dialogView.displayFollows.setChecked(false); - break; - case "update": + } + case "update" -> { excludedCategoriesList.add("update"); dialogView.displayUpdates.setChecked(false); - break; - case "admin.sign_up": + } + case "admin.sign_up" -> { excludedCategoriesList.add("admin.sign_up"); dialogView.displaySignups.setChecked(false); - break; - case "admin.report": + } + case "admin.report" -> { excludedCategoriesList.add("admin.report"); dialogView.displayReports.setChecked(false); - break; + } } } } @@ -224,8 +224,7 @@ public class FragmentNotificationContainer extends Fragment { Fragment fragment; if (binding.viewpagerNotificationContainer.getAdapter() != null) { fragment = (Fragment) binding.viewpagerNotificationContainer.getAdapter().instantiateItem(binding.viewpagerNotificationContainer, tab.getPosition()); - if (fragment instanceof FragmentMastodonNotification) { - FragmentMastodonNotification fragmentMastodonNotification = ((FragmentMastodonNotification) fragment); + if (fragment instanceof FragmentMastodonNotification fragmentMastodonNotification) { fragmentMastodonNotification.scrollToTop(); } } diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentProfileTimeline.java b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentProfileTimeline.java index 52d8394b..b1c1f9d7 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentProfileTimeline.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/fragment/timeline/FragmentProfileTimeline.java @@ -14,6 +14,8 @@ package app.fedilab.android.mastodon.ui.fragment.timeline; * You should have received a copy of the GNU General Public License along with Fedilab; if not, * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; + import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; @@ -33,7 +35,9 @@ import com.google.android.material.tabs.TabLayout; import app.fedilab.android.R; import app.fedilab.android.databinding.FragmentProfileTimelinesBinding; import app.fedilab.android.mastodon.client.entities.api.Account; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.client.entities.app.Timeline; +import app.fedilab.android.mastodon.exception.DBException; import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.ui.pageadapter.FedilabProfilePageAdapter; @@ -46,19 +50,22 @@ public class FragmentProfileTimeline extends Fragment { public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - + binding = FragmentProfileTimelinesBinding.inflate(inflater, container, false); if (getArguments() != null) { - account = (Account) getArguments().getSerializable(Helper.ARG_ACCOUNT); + String cached_account_id = getArguments().getString(Helper.ARG_CACHED_ACCOUNT_ID); + try { + account = new CachedBundle(requireActivity()).getCachedAccount(currentAccount, cached_account_id); + } catch (DBException e) { + e.printStackTrace(); + } checkRemotely = getArguments().getBoolean(Helper.ARG_CHECK_REMOTELY, false); + initializeAfterBundle(); } - binding = FragmentProfileTimelinesBinding.inflate(inflater, container, false); return binding.getRoot(); } - @Override - public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); + private void initializeAfterBundle() { binding.tabLayout.addTab(binding.tabLayout.newTab().setText(getString(R.string.toots))); binding.tabLayout.addTab(binding.tabLayout.newTab().setText(getString(R.string.replies))); binding.tabLayout.addTab(binding.tabLayout.newTab().setText(getString(R.string.media))); @@ -80,10 +87,7 @@ public class FragmentProfileTimeline extends Fragment { public void onTabReselected(TabLayout.Tab tab) { if (binding.viewpager.getAdapter() != null && binding.viewpager .getAdapter() - .instantiateItem(binding.viewpager, binding.viewpager.getCurrentItem()) instanceof FragmentMastodonTimeline) { - FragmentMastodonTimeline fragmentMastodonTimeline = (FragmentMastodonTimeline) binding.viewpager - .getAdapter() - .instantiateItem(binding.viewpager, binding.viewpager.getCurrentItem()); + .instantiateItem(binding.viewpager, binding.viewpager.getCurrentItem()) instanceof FragmentMastodonTimeline fragmentMastodonTimeline) { fragmentMastodonTimeline.goTop(); } } @@ -105,24 +109,25 @@ public class FragmentProfileTimeline extends Fragment { popup.setOnDismissListener(menu1 -> { if (binding.viewpager.getAdapter() != null && binding.viewpager .getAdapter() - .instantiateItem(binding.viewpager, binding.viewpager.getCurrentItem()) instanceof FragmentMastodonTimeline) { - FragmentMastodonTimeline fragmentMastodonTimeline = (FragmentMastodonTimeline) binding.viewpager - .getAdapter() - .instantiateItem(binding.viewpager, binding.viewpager.getCurrentItem()); + .instantiateItem(binding.viewpager, binding.viewpager.getCurrentItem()) instanceof FragmentMastodonTimeline fragmentMastodonTimeline) { FragmentTransaction fragTransaction = getChildFragmentManager().beginTransaction(); fragTransaction.detach(fragmentMastodonTimeline).commit(); - Bundle bundle = new Bundle(); - bundle.putSerializable(Helper.ARG_TIMELINE_TYPE, Timeline.TimeLineEnum.ACCOUNT_TIMELINE); - bundle.putSerializable(Helper.ARG_ACCOUNT, account); - bundle.putBoolean(Helper.ARG_SHOW_PINNED, true); - bundle.putBoolean(Helper.ARG_CHECK_REMOTELY, checkRemotely); - bundle.putBoolean(Helper.ARG_SHOW_REBLOGS, show_boosts); - bundle.putBoolean(Helper.ARG_SHOW_REPLIES, show_replies); - fragmentMastodonTimeline.setArguments(bundle); - FragmentTransaction fragTransaction2 = getChildFragmentManager().beginTransaction(); - fragTransaction2.attach(fragmentMastodonTimeline); - fragTransaction2.commit(); - fragmentMastodonTimeline.recreate(); + Bundle args = new Bundle(); + args.putSerializable(Helper.ARG_TIMELINE_TYPE, Timeline.TimeLineEnum.ACCOUNT_TIMELINE); + args.putSerializable(Helper.ARG_ACCOUNT, account); + args.putBoolean(Helper.ARG_SHOW_PINNED, true); + args.putBoolean(Helper.ARG_CHECK_REMOTELY, checkRemotely); + args.putBoolean(Helper.ARG_SHOW_REBLOGS, show_boosts); + args.putBoolean(Helper.ARG_SHOW_REPLIES, show_replies); + new CachedBundle(requireActivity()).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + fragmentMastodonTimeline.setArguments(bundle); + FragmentTransaction fragTransaction2 = getChildFragmentManager().beginTransaction(); + fragTransaction2.attach(fragmentMastodonTimeline); + fragTransaction2.commit(); + fragmentMastodonTimeline.recreate(); + }); } }); @@ -158,5 +163,10 @@ public class FragmentProfileTimeline extends Fragment { } + @Override + public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + } + } diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/pageadapter/FedilabNotificationPageAdapter.java b/app/src/main/java/app/fedilab/android/mastodon/ui/pageadapter/FedilabNotificationPageAdapter.java index 57c90774..5a4721e0 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/pageadapter/FedilabNotificationPageAdapter.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/pageadapter/FedilabNotificationPageAdapter.java @@ -53,45 +53,33 @@ public class FedilabNotificationPageAdapter extends FragmentStatePagerAdapter { FragmentMastodonNotification fragmentMastodonNotification = new FragmentMastodonNotification(); if (!extended) { switch (position) { - case 0: - bundle.putSerializable(Helper.ARG_NOTIFICATION_TYPE, FragmentMastodonNotification.NotificationTypeEnum.ALL); - break; - case 1: - bundle.putSerializable(Helper.ARG_NOTIFICATION_TYPE, FragmentMastodonNotification.NotificationTypeEnum.MENTIONS); - break; + case 0 -> + bundle.putSerializable(Helper.ARG_NOTIFICATION_TYPE, FragmentMastodonNotification.NotificationTypeEnum.ALL); + case 1 -> + bundle.putSerializable(Helper.ARG_NOTIFICATION_TYPE, FragmentMastodonNotification.NotificationTypeEnum.MENTIONS); } } else { switch (position) { - case 0: - bundle.putSerializable(Helper.ARG_NOTIFICATION_TYPE, FragmentMastodonNotification.NotificationTypeEnum.ALL); - break; - case 1: - bundle.putSerializable(Helper.ARG_NOTIFICATION_TYPE, FragmentMastodonNotification.NotificationTypeEnum.MENTIONS); - break; - case 2: - bundle.putSerializable(Helper.ARG_NOTIFICATION_TYPE, FragmentMastodonNotification.NotificationTypeEnum.FAVOURITES); - break; - case 3: - bundle.putSerializable(Helper.ARG_NOTIFICATION_TYPE, FragmentMastodonNotification.NotificationTypeEnum.REBLOGS); - break; - case 4: - bundle.putSerializable(Helper.ARG_NOTIFICATION_TYPE, FragmentMastodonNotification.NotificationTypeEnum.POLLS); - break; - case 5: - bundle.putSerializable(Helper.ARG_NOTIFICATION_TYPE, FragmentMastodonNotification.NotificationTypeEnum.TOOTS); - break; - case 6: - bundle.putSerializable(Helper.ARG_NOTIFICATION_TYPE, FragmentMastodonNotification.NotificationTypeEnum.FOLLOWS); - break; - case 7: - bundle.putSerializable(Helper.ARG_NOTIFICATION_TYPE, FragmentMastodonNotification.NotificationTypeEnum.UPDATES); - break; - case 8: - bundle.putSerializable(Helper.ARG_NOTIFICATION_TYPE, FragmentMastodonNotification.NotificationTypeEnum.ADMIN_SIGNUP); - break; - case 9: - bundle.putSerializable(Helper.ARG_NOTIFICATION_TYPE, FragmentMastodonNotification.NotificationTypeEnum.ADMIN_REPORT); - break; + case 0 -> + bundle.putSerializable(Helper.ARG_NOTIFICATION_TYPE, FragmentMastodonNotification.NotificationTypeEnum.ALL); + case 1 -> + bundle.putSerializable(Helper.ARG_NOTIFICATION_TYPE, FragmentMastodonNotification.NotificationTypeEnum.MENTIONS); + case 2 -> + bundle.putSerializable(Helper.ARG_NOTIFICATION_TYPE, FragmentMastodonNotification.NotificationTypeEnum.FAVOURITES); + case 3 -> + bundle.putSerializable(Helper.ARG_NOTIFICATION_TYPE, FragmentMastodonNotification.NotificationTypeEnum.REBLOGS); + case 4 -> + bundle.putSerializable(Helper.ARG_NOTIFICATION_TYPE, FragmentMastodonNotification.NotificationTypeEnum.POLLS); + case 5 -> + bundle.putSerializable(Helper.ARG_NOTIFICATION_TYPE, FragmentMastodonNotification.NotificationTypeEnum.TOOTS); + case 6 -> + bundle.putSerializable(Helper.ARG_NOTIFICATION_TYPE, FragmentMastodonNotification.NotificationTypeEnum.FOLLOWS); + case 7 -> + bundle.putSerializable(Helper.ARG_NOTIFICATION_TYPE, FragmentMastodonNotification.NotificationTypeEnum.UPDATES); + case 8 -> + bundle.putSerializable(Helper.ARG_NOTIFICATION_TYPE, FragmentMastodonNotification.NotificationTypeEnum.ADMIN_SIGNUP); + case 9 -> + bundle.putSerializable(Helper.ARG_NOTIFICATION_TYPE, FragmentMastodonNotification.NotificationTypeEnum.ADMIN_REPORT); } } fragmentMastodonNotification.setArguments(bundle); diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/pageadapter/FedilabProfilePageAdapter.java b/app/src/main/java/app/fedilab/android/mastodon/ui/pageadapter/FedilabProfilePageAdapter.java index dc1c747d..22f55cd9 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/pageadapter/FedilabProfilePageAdapter.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/pageadapter/FedilabProfilePageAdapter.java @@ -56,35 +56,46 @@ public class FedilabProfilePageAdapter extends FragmentStatePagerAdapter { public Fragment getItem(int position) { Bundle bundle = new Bundle(); bundle.putString(Helper.ARG_VIEW_MODEL_KEY, "FEDILAB_" + position); + FragmentMastodonTimeline fragmentMastodonTimeline; switch (position) { - case 0: - FragmentMastodonTimeline fragmentProfileTimeline = new FragmentMastodonTimeline(); + case 0 -> { + fragmentMastodonTimeline = new FragmentMastodonTimeline(); bundle.putSerializable(Helper.ARG_TIMELINE_TYPE, Timeline.TimeLineEnum.ACCOUNT_TIMELINE); - bundle.putSerializable(Helper.ARG_ACCOUNT, account); + if(account != null) { + bundle.putSerializable(Helper.ARG_CACHED_ACCOUNT_ID, account.id); + } bundle.putBoolean(Helper.ARG_SHOW_PINNED, true); bundle.putBoolean(Helper.ARG_SHOW_REPLIES, false); bundle.putBoolean(Helper.ARG_SHOW_REBLOGS, true); bundle.putBoolean(Helper.ARG_CHECK_REMOTELY, checkRemotely); - fragmentProfileTimeline.setArguments(bundle); - return fragmentProfileTimeline; - case 1: - fragmentProfileTimeline = new FragmentMastodonTimeline(); + fragmentMastodonTimeline.setArguments(bundle); + return fragmentMastodonTimeline; + } + case 1 -> { + fragmentMastodonTimeline = new FragmentMastodonTimeline(); bundle.putSerializable(Helper.ARG_TIMELINE_TYPE, Timeline.TimeLineEnum.ACCOUNT_TIMELINE); - bundle.putSerializable(Helper.ARG_ACCOUNT, account); + if(account != null) { + bundle.putSerializable(Helper.ARG_CACHED_ACCOUNT_ID, account.id); + } bundle.putBoolean(Helper.ARG_SHOW_PINNED, false); bundle.putBoolean(Helper.ARG_SHOW_REPLIES, true); bundle.putBoolean(Helper.ARG_SHOW_REBLOGS, false); bundle.putBoolean(Helper.ARG_CHECK_REMOTELY, checkRemotely); - fragmentProfileTimeline.setArguments(bundle); - return fragmentProfileTimeline; - case 2: + fragmentMastodonTimeline.setArguments(bundle); + return fragmentMastodonTimeline; + } + case 2 -> { FragmentMediaProfile fragmentMediaProfile = new FragmentMediaProfile(); - bundle.putSerializable(Helper.ARG_ACCOUNT, account); + if(account != null) { + bundle.putSerializable(Helper.ARG_CACHED_ACCOUNT_ID, account.id); + } bundle.putBoolean(Helper.ARG_CHECK_REMOTELY, checkRemotely); fragmentMediaProfile.setArguments(bundle); return fragmentMediaProfile; - default: + } + default -> { return new FragmentMastodonTimeline(); + } } } diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/pageadapter/FedilabProfileTLPageAdapter.java b/app/src/main/java/app/fedilab/android/mastodon/ui/pageadapter/FedilabProfileTLPageAdapter.java index 748b01ae..c7104302 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/pageadapter/FedilabProfileTLPageAdapter.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/pageadapter/FedilabProfileTLPageAdapter.java @@ -54,26 +54,29 @@ public class FedilabProfileTLPageAdapter extends FragmentStatePagerAdapter { @NonNull @Override public Fragment getItem(int position) { + Bundle bundle; switch (position) { - case 0: + case 0 -> { FragmentProfileTimeline fragmentProfileTimeline = new FragmentProfileTimeline(); - Bundle bundle = new Bundle(); - bundle.putSerializable(Helper.ARG_ACCOUNT, account); + bundle = new Bundle(); + bundle.putString(Helper.ARG_CACHED_ACCOUNT_ID, account.id); bundle.putSerializable(Helper.ARG_CHECK_REMOTELY, checkRemotely); fragmentProfileTimeline.setArguments(bundle); return fragmentProfileTimeline; - case 1: - case 2: + } + case 1, 2 -> { FragmentMastodonAccount fragmentMastodonAccount = new FragmentMastodonAccount(); bundle = new Bundle(); - bundle.putSerializable(Helper.ARG_ACCOUNT, account); + bundle.putString(Helper.ARG_CACHED_ACCOUNT_ID, account.id); bundle.putSerializable(Helper.ARG_CHECK_REMOTELY, checkRemotely); bundle.putString(Helper.ARG_VIEW_MODEL_KEY, "FEDILAB_" + position); bundle.putSerializable(Helper.ARG_FOLLOW_TYPE, position == 1 ? follow_type.FOLLOWING : follow_type.FOLLOWERS); fragmentMastodonAccount.setArguments(bundle); return fragmentMastodonAccount; - default: + } + default -> { return new FragmentMastodonTimeline(); + } } } diff --git a/app/src/main/java/app/fedilab/android/mastodon/ui/pageadapter/FedilabScheduledPageAdapter.java b/app/src/main/java/app/fedilab/android/mastodon/ui/pageadapter/FedilabScheduledPageAdapter.java index 9045d8e2..26cb486a 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/ui/pageadapter/FedilabScheduledPageAdapter.java +++ b/app/src/main/java/app/fedilab/android/mastodon/ui/pageadapter/FedilabScheduledPageAdapter.java @@ -52,14 +52,12 @@ public class FedilabScheduledPageAdapter extends FragmentStatePagerAdapter { bundle.putString(Helper.ARG_VIEW_MODEL_KEY, "FEDILAB_" + position); FragmentScheduled fragmentScheduled = new FragmentScheduled(); switch (position) { - case 1: - bundle.putSerializable(Helper.ARG_TIMELINE_TYPE, Timeline.TimeLineEnum.SCHEDULED_TOOT_CLIENT); - break; - case 2: - bundle.putSerializable(Helper.ARG_TIMELINE_TYPE, Timeline.TimeLineEnum.SCHEDULED_BOOST); - break; - default: - bundle.putSerializable(Helper.ARG_TIMELINE_TYPE, Timeline.TimeLineEnum.SCHEDULED_TOOT_SERVER); + case 1 -> + bundle.putSerializable(Helper.ARG_TIMELINE_TYPE, Timeline.TimeLineEnum.SCHEDULED_TOOT_CLIENT); + case 2 -> + bundle.putSerializable(Helper.ARG_TIMELINE_TYPE, Timeline.TimeLineEnum.SCHEDULED_BOOST); + default -> + bundle.putSerializable(Helper.ARG_TIMELINE_TYPE, Timeline.TimeLineEnum.SCHEDULED_TOOT_SERVER); } fragmentScheduled.setArguments(bundle); return fragmentScheduled; diff --git a/app/src/main/java/app/fedilab/android/mastodon/viewmodel/mastodon/AccountsVM.java b/app/src/main/java/app/fedilab/android/mastodon/viewmodel/mastodon/AccountsVM.java index 91a1856f..ed91fe5d 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/viewmodel/mastodon/AccountsVM.java +++ b/app/src/main/java/app/fedilab/android/mastodon/viewmodel/mastodon/AccountsVM.java @@ -14,6 +14,8 @@ package app.fedilab.android.mastodon.viewmodel.mastodon; * You should have received a copy of the GNU General Public License along with Fedilab; if not, * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; + import android.app.Application; import android.net.Uri; import android.os.Handler; @@ -30,6 +32,7 @@ import java.util.List; import app.fedilab.android.R; import app.fedilab.android.activities.MainActivity; +import app.fedilab.android.mastodon.activities.ProfileActivity; import app.fedilab.android.mastodon.client.endpoints.MastodonAccountsService; import app.fedilab.android.mastodon.client.entities.api.Account; import app.fedilab.android.mastodon.client.entities.api.Accounts; @@ -52,6 +55,7 @@ import app.fedilab.android.mastodon.client.entities.api.Suggestions; import app.fedilab.android.mastodon.client.entities.api.Tag; import app.fedilab.android.mastodon.client.entities.api.Token; import app.fedilab.android.mastodon.client.entities.app.BaseAccount; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.client.entities.app.MutedAccounts; import app.fedilab.android.mastodon.client.entities.app.StatusCache; import app.fedilab.android.mastodon.exception.DBException; @@ -342,6 +346,7 @@ public class AccountsVM extends AndroidViewModel { Response accountResponse = accountCall.execute(); if (accountResponse.isSuccessful()) { account = accountResponse.body(); + new CachedBundle(getApplication().getApplicationContext()).insertAccountBundle(account, currentAccount); } } catch (Exception e) { e.printStackTrace(); @@ -1073,6 +1078,9 @@ public class AccountsVM extends AndroidViewModel { Response> searchResponse = searchCall.execute(); if (searchResponse.isSuccessful()) { accountList = searchResponse.body(); + if(accountList != null && accountList.size() > 0 ) { + new CachedBundle(getApplication().getApplicationContext()).insertAccountBundle(accountList.get(0), currentAccount); + } } } catch (Exception e) { e.printStackTrace(); diff --git a/app/src/main/java/app/fedilab/android/peertube/activities/PeertubeActivity.java b/app/src/main/java/app/fedilab/android/peertube/activities/PeertubeActivity.java index cab6b84f..0fd8dd48 100644 --- a/app/src/main/java/app/fedilab/android/peertube/activities/PeertubeActivity.java +++ b/app/src/main/java/app/fedilab/android/peertube/activities/PeertubeActivity.java @@ -1591,7 +1591,7 @@ public class PeertubeActivity extends BasePeertubeActivity implements CommentLis } } }; - ContextCompat.registerReceiver(PeertubeActivity.this, mPowerKeyReceiver, theFilter, ContextCompat.RECEIVER_NOT_EXPORTED); + ContextCompat.registerReceiver(PeertubeActivity.this, mPowerKeyReceiver, theFilter, ContextCompat.RECEIVER_NOT_EXPORTED); } private void unregisterReceiver() { diff --git a/app/src/main/java/app/fedilab/android/peertube/activities/PeertubeMainActivity.java b/app/src/main/java/app/fedilab/android/peertube/activities/PeertubeMainActivity.java index 3e56a2b6..9c9fccc0 100644 --- a/app/src/main/java/app/fedilab/android/peertube/activities/PeertubeMainActivity.java +++ b/app/src/main/java/app/fedilab/android/peertube/activities/PeertubeMainActivity.java @@ -61,7 +61,6 @@ import androidx.drawerlayout.widget.DrawerLayout; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentStatePagerAdapter; - import androidx.preference.PreferenceManager; import androidx.viewpager.widget.PagerAdapter; import androidx.viewpager.widget.ViewPager; diff --git a/app/src/main/java/app/fedilab/android/peertube/client/RetrofitPeertubeAPI.java b/app/src/main/java/app/fedilab/android/peertube/client/RetrofitPeertubeAPI.java index 2de3aaee..049509a1 100644 --- a/app/src/main/java/app/fedilab/android/peertube/client/RetrofitPeertubeAPI.java +++ b/app/src/main/java/app/fedilab/android/peertube/client/RetrofitPeertubeAPI.java @@ -43,10 +43,10 @@ import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; -import java.io.UnsupportedEncodingException; import java.net.IDN; import java.net.URL; import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; @@ -178,11 +178,8 @@ public class RetrofitPeertubeAPI { error.printStackTrace(); return; } - try { - //At the state the instance can be encoded - instance = URLDecoder.decode(instance, "utf-8"); - } catch (UnsupportedEncodingException ignored) { - } + //At the state the instance can be encoded + instance = URLDecoder.decode(instance, StandardCharsets.UTF_8); SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(activity); account.token = token; account.client_id = client_id; diff --git a/app/src/main/java/app/fedilab/android/peertube/fragment/SettingsFragment.java b/app/src/main/java/app/fedilab/android/peertube/fragment/SettingsFragment.java index c535c1a5..404fea4d 100644 --- a/app/src/main/java/app/fedilab/android/peertube/fragment/SettingsFragment.java +++ b/app/src/main/java/app/fedilab/android/peertube/fragment/SettingsFragment.java @@ -17,7 +17,6 @@ import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.res.ResourcesCompat; import androidx.fragment.app.FragmentActivity; - import androidx.preference.ListPreference; import androidx.preference.MultiSelectListPreference; import androidx.preference.Preference; diff --git a/app/src/main/java/app/fedilab/android/peertube/helper/Helper.java b/app/src/main/java/app/fedilab/android/peertube/helper/Helper.java index 3197ab45..db5c74bc 100644 --- a/app/src/main/java/app/fedilab/android/peertube/helper/Helper.java +++ b/app/src/main/java/app/fedilab/android/peertube/helper/Helper.java @@ -57,7 +57,6 @@ import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; - import androidx.preference.PreferenceManager; import com.avatarfirst.avatargenlib.AvatarGenerator; @@ -276,7 +275,7 @@ public class Helper { * @return String rounded value to be displayed */ public static String withSuffix(long count) { - if (count < 1000) return "" + count; + if (count < 1000) return String.valueOf(count); int exp = (int) (Math.log(count) / Math.log(1000)); Locale locale = null; try { diff --git a/app/src/main/java/app/fedilab/android/peertube/services/RetrieveInfoService.java b/app/src/main/java/app/fedilab/android/peertube/services/RetrieveInfoService.java index a4b4842c..d4274e0c 100644 --- a/app/src/main/java/app/fedilab/android/peertube/services/RetrieveInfoService.java +++ b/app/src/main/java/app/fedilab/android/peertube/services/RetrieveInfoService.java @@ -54,7 +54,7 @@ public class RetrieveInfoService extends Service implements NetworkStateReceiver super.onCreate(); networkStateReceiver = new NetworkStateReceiver(); networkStateReceiver.addListener(this); - ContextCompat.registerReceiver(RetrieveInfoService.this, networkStateReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION), ContextCompat.RECEIVER_NOT_EXPORTED); + ContextCompat.registerReceiver(RetrieveInfoService.this, networkStateReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION), ContextCompat.RECEIVER_NOT_EXPORTED); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, getString(R.string.notification_channel_name), diff --git a/app/src/main/java/app/fedilab/android/peertube/webview/MastalabWebChromeClient.java b/app/src/main/java/app/fedilab/android/peertube/webview/MastalabWebChromeClient.java index eb98146c..aa7d05b3 100644 --- a/app/src/main/java/app/fedilab/android/peertube/webview/MastalabWebChromeClient.java +++ b/app/src/main/java/app/fedilab/android/peertube/webview/MastalabWebChromeClient.java @@ -109,11 +109,10 @@ public class MastalabWebChromeClient extends WebChromeClient implements MediaPla @Override public void onShowCustomView(View view, CustomViewCallback callback) { - if (view instanceof FrameLayout) { + if (view instanceof FrameLayout frameLayout) { if (((AppCompatActivity) activity).getSupportActionBar() != null) ((AppCompatActivity) activity).getSupportActionBar().hide(); // A video wants to be shown - FrameLayout frameLayout = (FrameLayout) view; View focusedChild = frameLayout.getFocusedChild(); // Save video related variables @@ -125,9 +124,8 @@ public class MastalabWebChromeClient extends WebChromeClient implements MediaPla activityNonVideoView.setVisibility(View.INVISIBLE); activityVideoView.addView(videoViewContainer, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); activityVideoView.setVisibility(View.VISIBLE); - if (focusedChild instanceof android.widget.VideoView) { + if (focusedChild instanceof android.widget.VideoView videoView) { // android.widget.VideoView (typically API level <11) - android.widget.VideoView videoView = (android.widget.VideoView) focusedChild; // Handle all the required events videoView.setOnCompletionListener(this); videoView.setOnErrorListener(this); diff --git a/app/src/main/java/app/fedilab/android/sqlite/Sqlite.java b/app/src/main/java/app/fedilab/android/sqlite/Sqlite.java index bb5029b8..14617283 100644 --- a/app/src/main/java/app/fedilab/android/sqlite/Sqlite.java +++ b/app/src/main/java/app/fedilab/android/sqlite/Sqlite.java @@ -23,7 +23,7 @@ import android.database.sqlite.SQLiteOpenHelper; public class Sqlite extends SQLiteOpenHelper { - public static final int DB_VERSION = 11; + public static final int DB_VERSION = 12; public static final String DB_NAME = "fedilab_db"; //Table of owned accounts @@ -105,6 +105,10 @@ public class Sqlite extends SQLiteOpenHelper { public static final String COL_TAG = "TAG"; public static final String TABLE_TIMELINE_CACHE_LOGS = "TIMELINE_CACHE_LOGS"; + public static final String TABLE_INTENT = "INTENT"; + + public static final String COL_BUNDLE = "BUNDLE"; + public static final String COL_TARGET_ID = "TARGET_ID"; private static final String CREATE_TABLE_USER_ACCOUNT = "CREATE TABLE " + TABLE_USER_ACCOUNT + " (" @@ -233,6 +237,16 @@ public class Sqlite extends SQLiteOpenHelper { + COL_TYPE + " TEXT NOT NULL, " + COL_CREATED_AT + " TEXT NOT NULL)"; + private final String CREATE_TABLE_INTENT = "CREATE TABLE " + + TABLE_INTENT + "(" + + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + + COL_INSTANCE + " TEXT, " + + COL_USER_ID + " TEXT, " + + COL_TYPE + " TEXT NOT NULL DEFAULT 'ARGS', " + + COL_TARGET_ID + " TEXT, " + + COL_BUNDLE + " TEXT, " + + COL_CREATED_AT + " TEXT NOT NULL)"; + public Sqlite(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); @@ -263,6 +277,7 @@ public class Sqlite extends SQLiteOpenHelper { db.execSQL(CREATE_TABLE_STORED_INSTANCES); db.execSQL(CREATE_TABLE_CACHE_TAGS); db.execSQL(CREATE_TABLE_TIMELINE_CACHE_LOGS); + db.execSQL(CREATE_TABLE_INTENT); } @Override @@ -295,6 +310,8 @@ public class Sqlite extends SQLiteOpenHelper { db.execSQL(CREATE_TABLE_CACHE_TAGS); case 10: db.execSQL(CREATE_TABLE_TIMELINE_CACHE_LOGS); + case 11: + db.execSQL(CREATE_TABLE_INTENT); default: break; } diff --git a/app/src/main/java/app/fedilab/android/ui/fragment/FragmentLoginPickInstanceMastodon.java b/app/src/main/java/app/fedilab/android/ui/fragment/FragmentLoginPickInstanceMastodon.java index 8f59d29e..9fc04821 100644 --- a/app/src/main/java/app/fedilab/android/ui/fragment/FragmentLoginPickInstanceMastodon.java +++ b/app/src/main/java/app/fedilab/android/ui/fragment/FragmentLoginPickInstanceMastodon.java @@ -15,6 +15,8 @@ package app.fedilab.android.ui.fragment; * see . */ +import static app.fedilab.android.BaseMainActivity.currentAccount; + import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; @@ -32,6 +34,7 @@ import java.util.List; import app.fedilab.android.R; import app.fedilab.android.databinding.FragmentLoginPickInstanceMastodonBinding; import app.fedilab.android.mastodon.client.entities.api.JoinMastodonInstance; +import app.fedilab.android.mastodon.client.entities.app.CachedBundle; import app.fedilab.android.mastodon.client.entities.app.Timeline; import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.ui.drawer.InstanceRegAdapter; @@ -145,10 +148,13 @@ public class FragmentLoginPickInstanceMastodon extends Fragment implements Insta Bundle args = new Bundle(); args.putSerializable(Helper.ARG_REMOTE_INSTANCE_STRING, clickedInstance.domain); args.putSerializable(Helper.ARG_TIMELINE_TYPE, Timeline.TimeLineEnum.TREND_MESSAGE_PUBLIC); - - Helper.addFragment( - getParentFragmentManager(), android.R.id.content, new FragmentMastodonTimeline(), - args, null, FragmentLoginRegisterMastodon.class.getName()); + new CachedBundle(requireActivity()).insertBundle(args, currentAccount, bundleId -> { + Bundle bundle = new Bundle(); + bundle.putLong(Helper.ARG_INTENT_ID, bundleId); + Helper.addFragment( + getParentFragmentManager(), android.R.id.content, new FragmentMastodonTimeline(), + bundle, null, FragmentLoginRegisterMastodon.class.getName()); + }); } } } \ No newline at end of file diff --git a/app/src/main/res/layouts/mastodon/layout/activity_search_result_tabs.xml b/app/src/main/res/layouts/mastodon/layout/activity_search_result_tabs.xml index 065e3476..edc6ae61 100644 --- a/app/src/main/res/layouts/mastodon/layout/activity_search_result_tabs.xml +++ b/app/src/main/res/layouts/mastodon/layout/activity_search_result_tabs.xml @@ -26,7 +26,7 @@ android:layout_width="match_parent" android:layout_height="wrap_content" app:tabGravity="fill" - app:tabMode="scrollable" /> + app:tabMode="auto" /> --> + + diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 3e152a0d..c1fbee6f 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -43,8 +43,8 @@ المفضلة متابِعون جدد الإشارات - الترقيات - عرض الترقيات + المعاد نشرها + عرض المعاد نشرها عرض الردود افتح في المتصفح ترجمة @@ -208,12 +208,12 @@ عدد الرسائل التي يتم تحميلها كل مرة تعطيل الصور الرمزية المتحركة تنبيهي عندما يتبعني أحدهم - تنبيهي عندما يقوم أحدهم بترقية منشوري + إشعاري عندما يقوم أحدهم بإعادة نشر منشوري إخطاري عندما يُعجَب أحدهم بأحد منشوراتي إخطاري عندما يُشار إليّ أرسل إشعاراً عند انتهاء استطلاع الرأي إشعار بالمشاركات الجديدة - عرض مربع حوار للتأكيد قبل ترقية أي تبويق + عرض مربع حوار للتأكيد قبل إعادة نشر أي منشور عرض مربع حوار للتأكيد قبل إضافة أي تبويق إلى المفضلة هل تود الإشعار؟ كتم الاشعارات @@ -258,7 +258,7 @@ الكلمات المفتاحية الكلمات المفتاحية… - العمومية + للعامة غير المدرجة الخاصة المباشرة @@ -291,16 +291,16 @@ متابعة مثيل الخادم إنّك مُتابِع لمثيل الخادم هذا! الشراكات - إخفاء ترقيات %s + إخفاء المعاد نشرها مِن طرف %s أوصِ به على صفحتك - إظهار ترقيات %s + إظهار المعاد نشرها مِن %s إلغاء التوصية مِن صفحتك رسالة مباشِرة عوامل التصفية ليس هناك أي عامل تصفية بعدُ. يمكنك إنشاء واحد بالنقر على زر \"+\". كلمة مفتاحية أو عبارة الخط الزمني الرئيسي - الخطوط الزمنية العمومية + الخطوط الزمنية العامة الإشعارات المحادثات سوف يتم العثور عليه بغض النظر عن حالة الأحرف في النص أو حتى و إن كان في الرسالة تحذير عن المحتوى @@ -316,7 +316,7 @@ لم تقم بعد بإنشاء قائمة. اضغط على زر \"+\" لإنشاء قائمة. توسيع الوسائط المخفية تلقائيًا مُتابِع جديد - ترقية جديدة + إعادة نشر جديدة مفضلة جديدة إشارة جديدة انتهى استطلاع الرأي @@ -340,9 +340,9 @@ عرض المزيد اعرض أقل الوسم موجود مِن قَبل! - برمجة الترقية - تمت برمجة الترقية! - ليس هناك أية برمجة للترقية للعرض! + برمجة إعادة نشر + تمت برمجة إعادة النشر! + ليس هناك أية إعادة نشر للعرض! فتح القائمة الصورة الشخصية رأسية الصفحة الشخصية @@ -581,7 +581,7 @@ تم التحقق منه عبر %1$s (%2$s) الإجراء مُعطّل إلغاء المتابعة - حدث خطأ ما، الرجاء التحقق من مسار التحميلات في الإعدادات. + حدث خطأ ما، الرجاء التحقق من مسار التنزيلات في الإعدادات. الإعلانات ليس هناك إعلانات! إضافة ردة فعل @@ -699,7 +699,7 @@ إضافة حقل غير مقفَل مُقفَل - مُبَرمَج + المُبَرمَجة القائمة الدنيا تعديل القائمة اختر حُلة @@ -865,4 +865,20 @@ موزع الإشعارات أخبرنا ما الخَطب مع هذا المنشور وصف إلزامي للوسائط + الاقتراحات + لم تقم بحجب أي نطاق بعد + المُتابَعون + قِسمة الرسائل الطويلة في الردود + يقوم بكتم كافة الحسابات على الخيط الرئيس. + قَسِّم الرسالة + إلغاء كتمه على الخيط الرئيس + الوسوم المتابَعة + تخصيص الألوان + لا تقم بتقسيمها + إدارة الوسوم + ميزات إضافية + النطاقات المحظورة + أتريد تقسيم هذه الرسائل في الردود؟ + دليل الحسابات + كتمه على الخيط الرئيس \ No newline at end of file diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml new file mode 100644 index 00000000..954237d7 --- /dev/null +++ b/app/src/main/res/values-bg/strings.xml @@ -0,0 +1,411 @@ + + + Затваряне + Отваряне в браузъра + Кеш памет + Относно + Парола + Излизане + Акаунти + Превеждане + Не + Поверителност + Хаштагове + Да + Сваляне на %1$s + Инстанция: mastodon.social + Споменавания + Инстанция + Съобщения + Сваляне + Относно инстанцията + Отмяна + Мултимедия + Отговори + Камера + Начало + Споделяне с + Добавяне на акаунт + Нови последователи + Изтриване на всички + Размер на текста + Следващо + Предишно + Отваряне чрез + Потвърждаване + Споделяне чрез Федилаб + Потребителско име + Чернови + Любими + Показване на отговори + Заглушени потребители + Блокирани потребители + Известия + Заявки за последване + Няма съобщения за показване + Заглушаване + Блокиране + Докладване + Изтриване + Копиране + Отметки + %d сек + %d мин + %d ч + %d д + + %d секунда + %d секунди + + + %d минута + %d минути + + + %d час + %d часа + + + %d ден + %d дни + + Няма чернови! + Избиране на акаунт + Изтриване на черновата? + Разработчик: + Лиценз: + GNU GPL V3 + Програмен код: + Търсене на инстанции: + Няма заявка за последване + Съобщения +\n %1$s + Отхвърляне + и + Заглушаване + Мултимедията е запазена + Файл: %1$s + Е-поща + Запазване + Съдържанието на съобщението е копирано в клипборда + Информацията е копирана в клипборда + Между + Последване + s + Размер на иконките + Настройки + Вмъкване на емоджи + Споделяне + Споменаване + Вече следваш този хаштаг! + Споделяния + Показване на споделяния + Показване на съобщенията ми + Местна емисия + Сигурен ли си, че искаш да излезеш @%1$s@%2$s? + Добавяне на това съобщение към любими? + Споделяне на това съобщение? + Предупреждаване при липса на описание на мултимедията в съобщение преди споделяне + Добавяне на отметка + Премахване на отметката + Премахване на тази мултимедия? + Съобщението ти е празно! + Няма налично описание! + Последователи +\n %1$s + Последвани +\n %1$s + Няма известие за показване + Последователи + Изтриване на всички известия? + Съобщението беше споделено! + Търсене + Списъци + Парола + Последване на инстанцията + Публични емисии + Начална емисия + Показване на споделяния от %s + Филтри + Известия + Разговори + Блокиране на домейна + Информация + Промяна на езика + Профилна снимка + Бот + Само мултимедия + Езици + Няма хаштагове + Изпращане + Готово + Гласуване + Преместване на емисия + Скриване на емисия + Управляване на емисиите + Категории + Текст + Филтър + Акаунт + Споделено от + Само последователи + Отпоследване на %1$s + Напиши хаштага за да се последва + Отпоследване + Заглушаване на хаштага + Закачане на хаштага + Управляване на хаштаговете + Сега работи с акаунта %1$s + Последване на хаштага + Показване на директните съобщения + Изпращане на имейл + Премахване на това съобщение от любими? + Споделено също от: + Емисии + Скриване на споделяния от %s + Последване на хаштаг + Последвани хаштагове + Управляване на акаунтите + Управляване на хаштаговете + Не бяха намерени емисии на тази инстанция! + Запомняне на позицията в емисиите + Премахване на закачената емисия? + Изтриване на емисията + Показване на емисии + Емисии в списък + Изтриване на закачените емисии? + Последвани + Отпоследване на хаштага + Отпоследване на хаштага + Отпоследване + Изтриване + Изтриване на списъка + Леми инстанция + Заглавие + Заглавие + Запланиране + те спомена + написа ново съобщение + те последва + Всички известия са изтрити! + Акаунтът беше блокиран! + Акаунтът беше последван! + Опа! Възникна грешка! + Запазване на промените + Вграден в приложението браузър + Следва те + Директно + Добавяне в списък + Прокси + Потребителско име + Партньорства + Директно съобщение + Запланиране на споделяне + Набиращи популярност + Съобщения (Устройство) + Съобщения (Сървър) + Категория + Описание + Интерфейс + Контакти + Разрешения + Гласово съобщение + Избиране + Писане + Нулиране + Редактиране на профила + Теми + Оповестявания + Няма оповестявания! + Взаимодействия + Планирани + Модератор + Блокирани домейни + Формат на публикацията + Балон + Директория + Моят акаунт + Бележки към изданието + Моето приложение + Моята инстанция + Предложени + Няма акаунти за показване + Акаунтът беше заглушен! + Администратор + Потребител + Запланирани съобщения + Изтриване & пре-написване + Съобщението е изпратено! + Деликатно съдържание? + Издание %1$s + Няма запланирани съобщения за показване! + Изтриване на запланираното съобщение? + Акаунтът вече не е блокиран! + Акаунтът вече не е заглушен! + Акаунтът вече не е следван! + Съобщението вече не е споделено! + Съобщението беше добавено към твоите отметки! + Съобщението беше премахнато от твоите отметки! + Известяване за нови публикации + Известяване? + Заключване на акаунта + Автоматично разгъване на cw + Отблокиране + Мб + Публично + Ключови думи… + Ключови думи + Описание + Заглавие… + Нелистнато + Поверително + Филтриране по регулярни изрази + Заглавие на новия списък + Все още нямаш списъци! + Ключова дума или израз + Обновяване на филтър + Изтича след + Изтриване на филтъра? + Контекст на филтъра + Цяла дума + Автоматично разгъване на скрита мултимедия + Домейнът е блокиран + Показване на повече + Хаштагът вече съществува! + Някое от тези + Всяко от тези + Никое от тези + Локални + Споделяне + Излизане от акаунта + Копиране на връзката + Филтриране на емисия с хаштагове + Копиране на информацията + Списък на блокираните обаждания + Създаване на анкета + Вариант %d + Емоджи + Показвано име + Добавяне на вариант + Регионални + Общи + Музика + Активизъм + Технологии + Гейминг + %1$s потребители + Паролите не съвпадат! + Акаунтът е създаден! + Запазване на съобщението в чернови? + Доклади + Активни + Нови + Аудио + Добавяне на инстанция + Федилаб спря :( + Видимост + Изчистване на кеша при напускане + + %d гласувал + %d гласували + + Кешът (мултимедия, кеширани съобщения, данни от вградения браузър) ще се изчисти автоматично при напускане на приложението. + YouTube + Twitter + Instagram + Reddit + Medium + Добавяне на бележки + Бележки за акаунта + Връзки + Нулиране на цветовете + Темата беше изнесена + Настройките бяха изнесени + Настройките са изнесени успешно + Внасяне на тема + Докосни тук, за да внесеш тема от предишно изнасяне + Изнасяне на темата + Докосни тук, за да изнесеш текущата тема + Видео кеш в МБ, нула означава липса на кеш. + Продължаване + Не ми харесва + Това е спам + Блокиране на %1$s + Нямаш акаунт? + Добавяне на филтър + Добавяне на поле + Бот-акаунт + Откриваем акаунт + Заключен + Отключен + Винаги да се показва бутона за отмятане + Одобряване + Домейн + Одобрено + Изтриване на ключова дума + Показване въпреки това + Добавяне на ключова дума + Отблокиране на домейна + Домейни + Следван от: + Домейн на преводача + Нови съобщения + Следва те + Кеширано съобщение + Публичен коментар + %d нови съобщения + Не следваш никакви хаштагове! + Скриване напълно + Внасяне на данни + Настройките са внесени успешно + Профилът е обновен! + Винаги да се маркира мултимедията като деликатна + Тъмна тема по подразбиране + Споделяне на връзката + Заглушаване на %1$s + Изкуство + Храна + Споменавания + %d обновени съобщения + Допълнителни коментари + Последно активни + Филтър + Винаги да се показва бутона за превеждане + Едно избрано + Множество избрани + Размер на файл кеша + Изчистване на кеш паметта + Изтриване на кеш паметта + Съобщения съхранявани в чернови + Отваряне на чернова + Сигурен ли си, че искаш да изтриеш кеш паметта? Ако имаш чернови с мултимедия, прикачената мултимедия ще бъде загубена. + Внасяне на настройки + Изнасяне на настройки + Зареждане на изнесени настройки + Оповестяване · %1$s - %2$s + Емисиите ще бъдат кеширани, за да бъде приложението по-бързо. + Отговор + Начало и списъци + Профили + Ключова дума или израз + Скриване с предупреждение + Действие на филтъра + Акаунтът е одобрен + Разрешаване + Политика за поверителност + Поверителен коментар + Светла тема по подразбиране + Нямаш блокирани домейни + Само локални + Допълнителни функции + Преводач + Преводач + Версия на преводача + Версия + Списък + Филтриране на езици + Кеш на началната емисия + Хаштагът е премахнат! + Хаштагът е сменен! + Изпращане въпреки това + \ No newline at end of file diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index c82e4c75..31f8bf87 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1042,8 +1042,8 @@ Folgeanfrage gestellt Vor dem Teilen warnen, falls der Beitrag keine Medienbeschreibung hat Diesem Beitrag fehlt die Medienbeschreibung. Dennoch teilen\? - Automatisches Abrufen entfernter Medien, wenn diese nicht verfügbar sind - Rufe Beiträge ab + Automatisch entfernte Medien abrufen, wenn diese nicht verfügbar sind + Beiträge abrufen Beschreibung hinzufügen Entferntes Konto abrufen! Beenden @@ -1065,7 +1065,7 @@ Teile lange Beiträge in Antworten auf Den Beitrag aufteilen Nicht aufteilen - Vorschau + Vorschaubild Der Beitrag wird in mehrere Antworten aufgeteilt, um die maximale Zeichenanzahl Ihrer Instanz einzuhalten. Diese Beiträge in Antworten aufteilen? Informationen wurden in die Zwischenablage kopiert diff --git a/app/src/main/res/values-eo/strings.xml b/app/src/main/res/values-eo/strings.xml index 0830836c..41745fd0 100644 --- a/app/src/main/res/values-eo/strings.xml +++ b/app/src/main/res/values-eo/strings.xml @@ -257,7 +257,7 @@ Listoj Ĉu vi certas, ke vi volas porĉiame forigi ĉi tiun liston? - Aldoni al la listo + Aldoni al listo Forigi la liston Nova listo titolo La konto estis aldonita al la listo! @@ -354,14 +354,14 @@ Lingvoj Nur aŭdvidaĵo Montru NSFW - Boto - Pixelfed instenco - Mastodono Instenco + Roboto + Pixelfed servilo + Mastodono-servilo Iu ajn de ĉi tiuj Ĉiuj de ĉi tiuj - None of these - Any of these words (space-separated) - All these words (space-separated) + Neniom + Iuj ajn vortoj (apartigitaj per spacetoj) + Ĉiuj ajn vortoj (apartigitaj per spacetoj) Add some words to filter (space-separated) Change column name Misskey instance @@ -386,11 +386,11 @@ No tags Attach an image when sharing a URL - Krei Baloto - Elekta %d - Vi bezonas du elektoj malpleje por la baloto! + Krei enketon + Opcio %d + Havendas almenaŭ du opciojn por la enketo! Farite - end at %s + finiĝis je %s Voĉdoni Partoprenita balotenketo finiĝis A poll you tooted has ended @@ -417,7 +417,7 @@ Saving… Image Saved Successfully! Failed to save Image - Add a poll item + Aldoni enketeron Mute conversation Unmute conversation The conversation is no longer muted! @@ -477,9 +477,9 @@ Allow content creators to share statuses to their RSS feeds Verki Elekti - Aldoni instencon - Enable crash reports - If enabled, a crash report will be created locally and then you will be able to share it. + Aldoni servilon + Ŝalti kolaps-raportojn + Se ŝaltita, kolaps-raporto estos kreita loke, kaj poste vi eblos disvastigi ĝin. Fedilab haltis :( You can send me by email the crash report. It will help to fix it :)\n\nYou can add additional content. Thank you! Visibility @@ -608,4 +608,11 @@ Mencioj Stelumoj Konservi ŝanĝojn + Ŝanĝoj estis konservitaj! + %d ĝisdatigitaj mesaĝoj + Silentigita + Sekvi etikedon + Redakti liston + Privata komento + Kopii informon \ No newline at end of file diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index cc58ad2d..5c43ce19 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -948,7 +948,7 @@ Bulle Visibilité des réponses Liste - Suivant + Abonnements Visibilité des icônes Traducteur Traducteur @@ -1062,4 +1062,7 @@ L\'application affichera publiquement les conversations pour obtenir tous les messages. Les interactions auront besoin d\'une étape supplémentaire pour fédérer les messages. Afficher mes messages %d fréquence (minutes) + Miniature + Afficher une barre de défilement pour les fils + Souligner les éléments cliquables \ No newline at end of file diff --git a/app/src/main/res/values-gl/strings.xml b/app/src/main/res/values-gl/strings.xml index e2b37dea..92355354 100644 --- a/app/src/main/res/values-gl/strings.xml +++ b/app/src/main/res/values-gl/strings.xml @@ -445,13 +445,13 @@ O contrasinal debe conter ao menos 8 caracteres O nome de usuaria debería ter só letras, números e guión baixo Conta creada! - Xa tes unha conta! -\n -\n Lembra validar o email nas seguintes 48 horas. -\n -\n Xa podes acceder coa túa conta escribindo %1$s no primeiro campo e premendo Acceder. -\n -\n Importante: se a túa instancia require validación, recibirás un correo unha vez sexa validada! + Xa tes unha conta! +\n +\n Lembra validar o email nas seguintes 48 horas. +\n +\n Xa podes acceder coa túa conta escribindo %1$s no primeiro campo e premendo Acceder. +\n +\n Importante: se a túa instancia require validación, recibirás un correo unha vez sexa validada! \u0020 ¿Gardar mensaxe en borradores? Administración Informes @@ -1067,4 +1067,5 @@ Copiar información Subliñar os elementos clicables Xa segues ese cancelo! + Mostrar barra de desprazamento nas cronoloxías \ No newline at end of file diff --git a/app/src/main/res/values-ia/strings.xml b/app/src/main/res/values-ia/strings.xml index 93132f6c..127d1b44 100644 --- a/app/src/main/res/values-ia/strings.xml +++ b/app/src/main/res/values-ia/strings.xml @@ -40,4 +40,35 @@ Favoritos Compartir con Adder un conto + Le information ha essite copiate al area de transferentia + Compartite per Fedilab + Camera + Nove sequitores + Boosts + Mentiones + Monstrar le boosts + Chronologia local + Usatores silentiate + Inserer emoji + Necun message a monstrar + Facer boost a iste message? + Blocar + Silentiar + Deler + Copiar + Compartir + Tu message es vacue! + Visibilitate per predefinition del messages: + Le message esseva inviate! + Selige un conto + Version %1$s + Disveloppator: + Licentia: + GNU GPL V3 + Codice fonte: + Nulle conto a monstrar + Messages +\n %1$s + Sequitores +\n %1$s \ No newline at end of file diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 1852ebf7..01924364 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -1066,4 +1066,5 @@ 缩略图 消息将分为几个回复,以满足您所在实例的最大字数。 是否将长消息分为回复? + 信息已复制到剪贴板 \ No newline at end of file diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 565a3579..13f0b11f 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1065,6 +1065,7 @@ SET_LONG_PRESS_STORE_MEDIA SET_UNFOLLOW_VALIDATION SET_USE_SINGLE_TOPBAR + SET_DISABLE_TOPBAR_SCROLLING SET_DISPLAY_COUNTERS SET_DISPLAY_COMPACT_ACTION_BUTTON @@ -1731,6 +1732,7 @@ Load exported settings Push distributor Single action bar + Disable top bar scrolling When enabled, the app will only have a single bar for timelines Timelines in a list When enabled, all pinned timelines will be displayed in a drop-down menu diff --git a/app/src/main/res/xml/pref_interface.xml b/app/src/main/res/xml/pref_interface.xml index fd36d463..b60c07b6 100644 --- a/app/src/main/res/xml/pref_interface.xml +++ b/app/src/main/res/xml/pref_interface.xml @@ -12,6 +12,13 @@ app:summary="@string/set_single_topbar" app:title="@string/set_single_topbar_title" /> + +