TubeLab-App-Android/app/src/main/java/app/fedilab/fedilabtube/ShowAccountActivity.java

490 lines
20 KiB
Java

package app.fedilab.fedilabtube;
/* Copyright 2020 Thomas Schneider
*
* This file is a part of TubeLab
*
* 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.
*
* TubeLab 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 TubeLab; if not,
* see <http://www.gnu.org/licenses>. */
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.bumptech.glide.Glide;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import app.fedilab.fedilabtube.asynctasks.PostActionAsyncTask;
import app.fedilab.fedilabtube.asynctasks.RetrieveFeedsAsyncTask;
import app.fedilab.fedilabtube.asynctasks.RetrieveRelationshipAsyncTask;
import app.fedilab.fedilabtube.client.APIResponse;
import app.fedilab.fedilabtube.client.PeertubeAPI;
import app.fedilab.fedilabtube.client.entities.Account;
import app.fedilab.fedilabtube.client.entities.Error;
import app.fedilab.fedilabtube.client.entities.Relationship;
import app.fedilab.fedilabtube.client.entities.Status;
import app.fedilab.fedilabtube.client.entities.StatusDrawerParams;
import app.fedilab.fedilabtube.drawer.StatusListAdapter;
import app.fedilab.fedilabtube.fragment.DisplayAccountsFragment;
import app.fedilab.fedilabtube.fragment.DisplayStatusFragment;
import app.fedilab.fedilabtube.helper.Helper;
import app.fedilab.fedilabtube.interfaces.OnPostActionInterface;
import app.fedilab.fedilabtube.interfaces.OnRetrieveFeedsAccountInterface;
import app.fedilab.fedilabtube.interfaces.OnRetrieveFeedsInterface;
import app.fedilab.fedilabtube.interfaces.OnRetrieveRelationshipInterface;
import es.dmoral.toasty.Toasty;
import static androidx.core.text.HtmlCompat.FROM_HTML_MODE_LEGACY;
import static app.fedilab.fedilabtube.helper.Helper.getLiveInstance;
import static app.fedilab.fedilabtube.helper.Helper.isLoggedIn;
public class ShowAccountActivity extends AppCompatActivity implements OnPostActionInterface, OnRetrieveFeedsAccountInterface, OnRetrieveRelationshipInterface, OnRetrieveFeedsInterface {
private List<Status> statuses;
private StatusListAdapter statusListAdapter;
private ImageButton account_follow;
private ViewPager mPager;
private TabLayout tabLayout;
private TextView account_note;
private String userId;
private Relationship relationship;
private int maxScrollSize;
private boolean avatarShown = true;
private ImageView account_pp;
private TextView account_dn;
private TextView account_un;
private Account account;
private String accountId;
private boolean ischannel;
private AsyncTask<Void, Void, Void> retrieveRelationship;
private action doAction;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
setContentView(R.layout.activity_show_account);
setTitle("");
Bundle b = getIntent().getExtras();
account_follow = findViewById(R.id.account_follow);
account_follow.setEnabled(false);
account_pp = findViewById(R.id.account_pp);
account_dn = findViewById(R.id.account_dn);
account_un = findViewById(R.id.account_un);
account_pp.setBackgroundResource(R.drawable.account_pp_border);
if (b != null) {
account = b.getParcelable("account");
if (account == null) {
accountId = b.getString("accountId");
} else {
accountId = account.getId();
}
ischannel = b.getBoolean("ischannel", false);
userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
} else {
Toasty.error(ShowAccountActivity.this, getString(R.string.toast_error_loading_account), Toast.LENGTH_LONG).show();
}
statuses = new ArrayList<>();
StatusDrawerParams statusDrawerParams = new StatusDrawerParams();
statusDrawerParams.setType(RetrieveFeedsAsyncTask.Type.USER);
statusDrawerParams.setTargetedId(accountId);
statusDrawerParams.setStatuses(statuses);
statusListAdapter = new StatusListAdapter(statusDrawerParams);
tabLayout = findViewById(R.id.account_tabLayout);
account_note = findViewById(R.id.account_note);
/*header_edit_profile.setOnClickListener(v -> {
Intent intent = new Intent(ShowAccountActivity.this, EditProfileActivity.class);
startActivity(intent);
});*/
ImageView action_back = findViewById(R.id.action_back);
action_back.setOnClickListener(v -> finish());
if (account != null) {
ManageAccount();
}
}
private void ManageAccount() {
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
String accountIdRelation = account.getAcct();
if (isLoggedIn(ShowAccountActivity.this)) {
retrieveRelationship = new RetrieveRelationshipAsyncTask(ShowAccountActivity.this, accountIdRelation, ShowAccountActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
String urlHeader = account.getHeader();
if (urlHeader != null && urlHeader.startsWith("/")) {
urlHeader = "https://" + Helper.getLiveInstance(ShowAccountActivity.this) + account.getHeader();
}
if (urlHeader != null && !urlHeader.contains("missing.png")) {
ImageView banner_pp = findViewById(R.id.banner_pp);
Glide.with(banner_pp.getContext())
.load(urlHeader)
.into(banner_pp);
}
TextView actionbar_title = findViewById(R.id.show_account_title);
if (account.getAcct() != null)
actionbar_title.setText(account.getAcct());
ImageView pp_actionBar = findViewById(R.id.pp_actionBar);
if (account.getAvatar() != null) {
Helper.loadGiF(ShowAccountActivity.this, account, pp_actionBar);
}
final AppBarLayout appBar = findViewById(R.id.appBar);
maxScrollSize = appBar.getTotalScrollRange();
appBar.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {
LinearLayout toolbarContent = findViewById(R.id.toolbar_content);
if (toolbarContent != null) {
if (Math.abs(verticalOffset) - appBar.getTotalScrollRange() == 0) {
if (toolbarContent.getVisibility() == View.GONE)
toolbarContent.setVisibility(View.VISIBLE);
} else {
if (toolbarContent.getVisibility() == View.VISIBLE)
toolbarContent.setVisibility(View.GONE);
}
}
if (maxScrollSize == 0)
maxScrollSize = appBarLayout.getTotalScrollRange();
int percentage = (Math.abs(verticalOffset)) * 100 / maxScrollSize;
if (percentage >= 40 && avatarShown) {
avatarShown = false;
account_pp.animate()
.scaleY(0).scaleX(0)
.setDuration(400)
.start();
}
if (percentage <= 40 && !avatarShown) {
avatarShown = true;
account_pp.animate()
.scaleY(1).scaleX(1)
.start();
}
});
mPager = findViewById(R.id.account_viewpager);
if (!ischannel) {
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.videos)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.channels)));
mPager.setOffscreenPageLimit(2);
} else {
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.videos)));
mPager.setOffscreenPageLimit(1);
}
PagerAdapter mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
TabLayout.Tab tab = tabLayout.getTabAt(position);
if (tab != null)
tab.select();
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
mPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
Fragment fragment = null;
if (mPager.getAdapter() != null)
fragment = (Fragment) mPager.getAdapter().instantiateItem(mPager, tab.getPosition());
switch (tab.getPosition()) {
case 0:
if (fragment != null) {
DisplayStatusFragment displayStatusFragment = ((DisplayStatusFragment) fragment);
displayStatusFragment.scrollToTop();
}
break;
case 1:
if (fragment != null) {
DisplayAccountsFragment displayAccountsFragment = ((DisplayAccountsFragment) fragment);
displayAccountsFragment.scrollToTop();
}
break;
}
}
});
account_dn.setText(account.getDisplay_name());
if (!ischannel || account.getAcct().split("-").length < 4) {
account_un.setText(String.format("@%s", account.getAcct()));
} else {
account_un.setVisibility(View.GONE);
}
SpannableString spannableString;
if (account.getNote() != null && account.getNote().compareTo("null") != 0 && account.getNote().trim().length() > 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
spannableString = new SpannableString(Html.fromHtml(account.getNote(), FROM_HTML_MODE_LEGACY));
else
spannableString = new SpannableString(Html.fromHtml(account.getNote()));
account.setNoteSpan(spannableString);
account_note.setText(account.getNoteSpan(), TextView.BufferType.SPANNABLE);
account_note.setMovementMethod(LinkMovementMethod.getInstance());
account_note.setVisibility(View.VISIBLE);
} else {
account_note.setVisibility(View.GONE);
}
Helper.loadGiF(ShowAccountActivity.this, account, account_pp);
//Follow button
String target = account.getAcct();
account_follow.setOnClickListener(v -> {
if (doAction == action.NOTHING) {
Toasty.info(ShowAccountActivity.this, getString(R.string.nothing_to_do), Toast.LENGTH_LONG).show();
} else if (doAction == action.FOLLOW) {
account_follow.setEnabled(false);
new PostActionAsyncTask(ShowAccountActivity.this, PeertubeAPI.StatusAction.FOLLOW, target, ShowAccountActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else if (doAction == action.UNFOLLOW) {
boolean confirm_unfollow = sharedpreferences.getBoolean(Helper.SET_UNFOLLOW_VALIDATION, true);
if (confirm_unfollow) {
AlertDialog.Builder unfollowConfirm = new AlertDialog.Builder(ShowAccountActivity.this);
unfollowConfirm.setTitle(getString(R.string.unfollow_confirm));
unfollowConfirm.setMessage(account.getAcct());
unfollowConfirm.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
unfollowConfirm.setPositiveButton(R.string.yes, (dialog, which) -> {
account_follow.setEnabled(false);
new PostActionAsyncTask(ShowAccountActivity.this, PeertubeAPI.StatusAction.UNFOLLOW, target, ShowAccountActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
dialog.dismiss();
});
unfollowConfirm.show();
} else {
account_follow.setEnabled(false);
new PostActionAsyncTask(ShowAccountActivity.this, PeertubeAPI.StatusAction.UNFOLLOW, target, ShowAccountActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
});
TextView account_date = findViewById(R.id.account_date);
account_date.setText(Helper.shortDateToString(account.getCreated_at()));
account_date.setVisibility(View.VISIBLE);
}
@Override
public void onRetrieveFeedsAccount(List<Status> statuses) {
if (statuses != null) {
this.statuses.addAll(statuses);
statusListAdapter.notifyDataSetChanged();
}
}
@Override
public void onRetrieveFeeds(APIResponse apiResponse) {
if (apiResponse.getError() != null) {
Toasty.error(ShowAccountActivity.this, apiResponse.getError().getError(), Toast.LENGTH_LONG).show();
}
}
@Override
public void onRetrieveRelationship(Relationship relationship, Error error) {
if (error != null) {
Toasty.error(ShowAccountActivity.this, error.getError(), Toast.LENGTH_LONG).show();
return;
}
this.relationship = relationship;
manageButtonVisibility();
//The authenticated account is followed by the account
if (relationship != null && relationship.isFollowed_by() && !accountId.equals(userId)) {
TextView account_followed_by = findViewById(R.id.account_followed_by);
account_followed_by.setVisibility(View.VISIBLE);
}
invalidateOptionsMenu();
}
//Manages the visibility of the button
private void manageButtonVisibility() {
if (relationship == null)
return;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
int[][] states = new int[][]{
new int[]{android.R.attr.state_enabled}, // enabled
new int[]{-android.R.attr.state_enabled}, // disabled
new int[]{-android.R.attr.state_checked}, // unchecked
new int[]{android.R.attr.state_pressed} // pressed
};
int[] colors = new int[]{
ContextCompat.getColor(ShowAccountActivity.this, R.color.colorAccent),
ContextCompat.getColor(ShowAccountActivity.this, R.color.colorAccent),
ContextCompat.getColor(ShowAccountActivity.this, R.color.colorAccent),
ContextCompat.getColor(ShowAccountActivity.this, R.color.colorAccent)
};
account_follow.setBackgroundTintList(new ColorStateList(states, colors));
}
account_follow.setEnabled(true);
if (relationship.isFollowing()) {
account_follow.setImageResource(R.drawable.ic_user_minus);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
account_follow.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ShowAccountActivity.this, R.color.red_1)));
}
doAction = action.UNFOLLOW;
account_follow.setContentDescription(getString(R.string.action_unfollow));
account_follow.setVisibility(View.VISIBLE);
} else if (!relationship.isFollowing()) {
account_follow.setImageResource(R.drawable.ic_user_plus);
doAction = action.FOLLOW;
account_follow.setVisibility(View.VISIBLE);
account_follow.setContentDescription(getString(R.string.action_follow));
} else {
account_follow.setVisibility(View.GONE);
doAction = action.NOTHING;
}
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onStop() {
super.onStop();
if (retrieveRelationship != null && !retrieveRelationship.isCancelled()) {
retrieveRelationship.cancel(true);
}
}
@Override
public void onPostAction(int statusCode, PeertubeAPI.StatusAction statusAction, String targetedId, Error error) {
if (error != null) {
Toasty.error(ShowAccountActivity.this, error.getError(), Toast.LENGTH_LONG).show();
return;
}
String target = account.getAcct();
//IF action is unfollow or mute, sends an intent to remove statuses
if (statusAction == PeertubeAPI.StatusAction.UNFOLLOW) {
Bundle b = new Bundle();
b.putString("receive_action", targetedId);
Intent intentBC = new Intent(Helper.RECEIVE_ACTION);
intentBC.putExtras(b);
}
retrieveRelationship = new RetrieveRelationshipAsyncTask(ShowAccountActivity.this, target, ShowAccountActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public enum action {
FOLLOW,
UNFOLLOW,
NOTHING
}
/**
* Pager adapter for the 4 fragments
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
}
@NotNull
@Override
public Fragment getItem(int position) {
Bundle bundle = new Bundle();
if (position == 0) {
DisplayStatusFragment displayStatusFragment = new DisplayStatusFragment();
bundle = new Bundle();
bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.USER);
bundle.putString("targetedid", account.getAcct());
bundle.putBoolean("ischannel", ischannel);
displayStatusFragment.setArguments(bundle);
return displayStatusFragment;
}
DisplayAccountsFragment displayAccountsFragment = new DisplayAccountsFragment();
bundle.putString("targetedid", account.getId());
bundle.putString("instance", getLiveInstance(ShowAccountActivity.this));
bundle.putString("name", account.getAcct());
displayAccountsFragment.setArguments(bundle);
return displayAccountsFragment;
}
@Override
public int getCount() {
if (ischannel)
return 1;
else
return 2;
}
}
}