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

311 lines
12 KiB
Java

package app.fedilab.fedilabtube.fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import app.fedilab.fedilabtube.R;
import app.fedilab.fedilabtube.asynctasks.RetrieveFeedsAsyncTask;
import app.fedilab.fedilabtube.asynctasks.RetrievePeertubeSearchAsyncTask;
import app.fedilab.fedilabtube.client.APIResponse;
import app.fedilab.fedilabtube.client.PeertubeAPI;
import app.fedilab.fedilabtube.client.entities.Error;
import app.fedilab.fedilabtube.client.entities.Peertube;
import app.fedilab.fedilabtube.drawer.PeertubeAdapter;
import app.fedilab.fedilabtube.helper.Helper;
import app.fedilab.fedilabtube.interfaces.OnPostActionInterface;
import app.fedilab.fedilabtube.interfaces.OnRetrieveFeedsInterface;
import app.fedilab.fedilabtube.sqlite.Sqlite;
import es.dmoral.toasty.Toasty;
public class DisplayStatusFragment extends Fragment implements OnPostActionInterface, OnRetrieveFeedsInterface {
private LinearLayoutManager mLayoutManager;
private boolean flag_loading;
private Context context;
private AsyncTask<Void, Void, Void> asyncTask;
private PeertubeAdapter peertubeAdapater;
private String max_id;
private List<Peertube> peertubes;
private RetrieveFeedsAsyncTask.Type type;
private RelativeLayout mainLoader, nextElementLoader, textviewNoAction;
private boolean firstLoad;
private SwipeRefreshLayout swipeRefreshLayout;
private SharedPreferences sharedpreferences;
private boolean isSwipped;
private String search_peertube;
private TextView textviewNoActionText;
private boolean ischannel;
private boolean ownVideos;
private View rootView;
private RecyclerView lv_status;
public DisplayStatusFragment() {
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_video, container, false);
peertubes = new ArrayList<>();
context = getContext();
Bundle bundle = this.getArguments();
if (getArguments() != null) {
type = DisplayStatusFragmentArgs.fromBundle(getArguments()).getType();
}
if (bundle != null) {
String targetedId = bundle.getString("targetedid", null);
String tag = bundle.getString("tag", null);
search_peertube = bundle.getString("search_peertube", null);
String remote_channel_name = bundle.getString("remote_channel_name", null);
String instanceType = bundle.getString("instanceType", "MASTODON");
ischannel = bundle.getBoolean("ischannel", false);
int timelineId = bundle.getInt("timelineId");
}
if (ischannel) {
type = RetrieveFeedsAsyncTask.Type.CHANNEL;
}
assert context != null;
SQLiteDatabase db = Sqlite.getInstance(context.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
lv_status = rootView.findViewById(R.id.lv_status);
isSwipped = false;
max_id = null;
flag_loading = true;
firstLoad = true;
assert context != null;
sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
swipeRefreshLayout = rootView.findViewById(R.id.swipeContainer);
mainLoader = rootView.findViewById(R.id.loader);
nextElementLoader = rootView.findViewById(R.id.loading_next_status);
textviewNoAction = rootView.findViewById(R.id.no_action);
textviewNoActionText = rootView.findViewById(R.id.no_action_text);
mainLoader.setVisibility(View.VISIBLE);
nextElementLoader.setVisibility(View.GONE);
String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, context != null ? Helper.getLiveInstance(context) : null);
peertubeAdapater = new PeertubeAdapter(this.peertubes);
lv_status.setAdapter(peertubeAdapater);
mLayoutManager = new LinearLayoutManager(context);
lv_status.setLayoutManager(mLayoutManager);
swipeRefreshLayout.setOnRefreshListener(this::pullToRefresh);
if (context != null) {
//Load data depending of the value
if (search_peertube == null) { //Not a Peertube search
asyncTask = new RetrieveFeedsAsyncTask(context, type, "0", DisplayStatusFragment.this).execute();
} else {
asyncTask = new RetrievePeertubeSearchAsyncTask(context, "0", search_peertube, DisplayStatusFragment.this).execute();
}
} else {
new Handler(Looper.getMainLooper()).postDelayed(() -> {
if (context != null) {
if (search_peertube == null) { //Not a Peertube search
asyncTask = new RetrieveFeedsAsyncTask(context, type, "0", DisplayStatusFragment.this).execute();
} else {
asyncTask = new RetrievePeertubeSearchAsyncTask(context, "0", search_peertube, DisplayStatusFragment.this).execute();
}
}
}, 500);
}
lv_status.addOnScrollListener(new RecyclerView.OnScrollListener() {
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();
if (dy > 0) {
int visibleItemCount = mLayoutManager.getChildCount();
int totalItemCount = mLayoutManager.getItemCount();
if (firstVisibleItem + visibleItemCount == totalItemCount && context != null) {
if (!flag_loading) {
flag_loading = true;
if (search_peertube == null) { //Not a Peertube search
asyncTask = new RetrieveFeedsAsyncTask(context, type, max_id, DisplayStatusFragment.this).execute();
} else {
asyncTask = new RetrievePeertubeSearchAsyncTask(context, max_id, search_peertube, DisplayStatusFragment.this).execute();
}
nextElementLoader.setVisibility(View.VISIBLE);
}
} else {
nextElementLoader.setVisibility(View.GONE);
}
}
}
});
return rootView;
}
@Override
public void onPause() {
super.onPause();
if (swipeRefreshLayout != null) {
swipeRefreshLayout.setEnabled(false);
swipeRefreshLayout.setRefreshing(false);
swipeRefreshLayout.clearAnimation();
}
if (getActivity() != null) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null && getView() != null) {
imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
}
}
}
@Override
public void onCreate(Bundle saveInstance) {
super.onCreate(saveInstance);
}
@Override
public void onAttach(@NotNull Context context) {
super.onAttach(context);
this.context = context;
}
@Override
public void onStop() {
super.onStop();
}
@Override
public void onDestroy() {
super.onDestroy();
if (asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING)
asyncTask.cancel(true);
}
@Override
public void onRetrieveFeeds(APIResponse apiResponse) {
//hide loaders
mainLoader.setVisibility(View.GONE);
nextElementLoader.setVisibility(View.GONE);
//handle other API error but discards 404 - error which can often happen due to toots which have been deleted
if (this.peertubes == null || apiResponse == null || (apiResponse.getError() != null && apiResponse.getError().getStatusCode() != 404 && apiResponse.getError().getStatusCode() != 501)) {
if (apiResponse == null)
Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show();
else {
Toasty.error(context, apiResponse.getError().getError(), Toast.LENGTH_LONG).show();
}
swipeRefreshLayout.setRefreshing(false);
flag_loading = false;
return;
}
int previousPosition = this.peertubes.size();
if (max_id == null)
max_id = "0";
//max_id needs to work like an offset
int tootPerPage = sharedpreferences.getInt(Helper.SET_VIDEOS_PER_PAGE, Helper.VIDEOS_PER_PAGE);
max_id = String.valueOf(Integer.parseInt(max_id) + tootPerPage);
if (apiResponse.getPeertubes() == null) {
return;
}
this.peertubes.addAll(apiResponse.getPeertubes());
//If no item were inserted previously the adapter is created
if (previousPosition == 0) {
peertubeAdapater = new PeertubeAdapter(this.peertubes);
lv_status.setAdapter(peertubeAdapater);
} else
peertubeAdapater.notifyItemRangeInserted(previousPosition, apiResponse.getPeertubes().size());
//remove handlers
swipeRefreshLayout.setRefreshing(false);
textviewNoAction.setVisibility(View.GONE);
if (firstLoad && (apiResponse.getPeertubes() == null || apiResponse.getPeertubes().size() == 0)) {
textviewNoActionText.setText(R.string.no_video_to_display);
textviewNoAction.setVisibility(View.VISIBLE);
}
flag_loading = false;
firstLoad = false;
}
@Override
public void onDestroyView() {
if (lv_status != null) {
try {
lv_status.setAdapter(null);
} catch (Exception ignored) {
}
}
super.onDestroyView();
rootView = null;
}
@Override
public void onResume() {
super.onResume();
swipeRefreshLayout.setEnabled(true);
}
public void scrollToTop() {
if (mLayoutManager != null) {
mLayoutManager.scrollToPositionWithOffset(0, 0);
}
}
public void pullToRefresh() {
if (peertubes.size() > 0) {
int size = peertubes.size();
isSwipped = true;
peertubes.clear();
peertubes = new ArrayList<>();
max_id = "0";
peertubeAdapater.notifyItemRangeRemoved(0, size);
if (search_peertube == null) { //Not a Peertube search
asyncTask = new RetrieveFeedsAsyncTask(context, type, "0", DisplayStatusFragment.this).execute();
} else {
asyncTask = new RetrievePeertubeSearchAsyncTask(context, "0", search_peertube, DisplayStatusFragment.this).execute();
}
}
}
@Override
public void onPostAction(int statusCode, PeertubeAPI.StatusAction statusAction, String userId, Error error) {
}
}