diff --git a/app/src/main/java/app/fedilab/android/activities/PlaylistsActivity.java b/app/src/main/java/app/fedilab/android/activities/PlaylistsActivity.java index 02317ee16..8e2e98033 100644 --- a/app/src/main/java/app/fedilab/android/activities/PlaylistsActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/PlaylistsActivity.java @@ -43,14 +43,17 @@ import java.util.List; import app.fedilab.android.R; import app.fedilab.android.asynctasks.ManageListsAsyncTask; +import app.fedilab.android.asynctasks.ManagePlaylistsAsyncTask; import app.fedilab.android.asynctasks.RetrieveFeedsAsyncTask; import app.fedilab.android.client.APIResponse; import app.fedilab.android.client.Entities.Peertube; +import app.fedilab.android.client.Entities.Playlist; import app.fedilab.android.client.Entities.Status; import app.fedilab.android.drawers.PeertubeAdapter; import app.fedilab.android.drawers.StatusListAdapter; import app.fedilab.android.helper.Helper; import app.fedilab.android.interfaces.OnListActionInterface; +import app.fedilab.android.interfaces.OnPlaylistActionInterface; import es.dmoral.toasty.Toasty; @@ -59,7 +62,7 @@ import es.dmoral.toasty.Toasty; * Display playlists for Peertube */ -public class PlaylistsActivity extends BaseActivity implements OnListActionInterface { +public class PlaylistsActivity extends BaseActivity implements OnPlaylistActionInterface { private String title, listId; @@ -68,6 +71,7 @@ public class PlaylistsActivity extends BaseActivity implements OnListActionInter private boolean swiped; private List peertubes; private String max_id; + private Playlist playlist; private boolean firstLoad; private boolean flag_loading; private PeertubeAdapter peertubeAdapter; @@ -125,8 +129,7 @@ public class PlaylistsActivity extends BaseActivity implements OnListActionInter Bundle b = getIntent().getExtras(); if(b != null){ - title = b.getString("title"); - listId = b.getString("id"); + playlist = b.getParcelable("playlist"); }else{ Toasty.error(this,getString(R.string.toast_error_search),Toast.LENGTH_LONG).show(); } @@ -268,7 +271,7 @@ public class PlaylistsActivity extends BaseActivity implements OnListActionInter @Override - public void onActionDone(ManageListsAsyncTask.action actionType, APIResponse apiResponse, int statusCode) { + public void onActionDone(ManagePlaylistsAsyncTask.action actionType, APIResponse apiResponse, int statusCode) { final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); mainLoader.setVisibility(View.GONE); nextElementLoader.setVisibility(View.GONE); @@ -281,9 +284,9 @@ public class PlaylistsActivity extends BaseActivity implements OnListActionInter flag_loading = false; return; } - if( actionType == ManageListsAsyncTask.action.GET_LIST_TIMELINE) { + if( actionType == ManagePlaylistsAsyncTask.action.GET_LIST_VIDEOS) { - int previousPosition = this.lv_playlist.size(); + int previousPosition = this.peertubes.size(); List statuses = apiResponse.getStatuses(); max_id = apiResponse.getMax_id(); flag_loading = (max_id == null); diff --git a/app/src/main/java/app/fedilab/android/asynctasks/ManagePlaylistsAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/ManagePlaylistsAsyncTask.java index d8ca43977..55c5f52d3 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/ManagePlaylistsAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/ManagePlaylistsAsyncTask.java @@ -21,7 +21,6 @@ import android.os.AsyncTask; import java.lang.ref.WeakReference; -import app.fedilab.android.client.API; import app.fedilab.android.client.APIResponse; import app.fedilab.android.client.Entities.Account; import app.fedilab.android.client.Entities.Playlist; @@ -41,14 +40,12 @@ public class ManagePlaylistsAsyncTask extends AsyncTask { public enum action{ GET_PLAYLIST, - GET_LIST_TIMELINE, - GET_LIST_ACCOUNT, + GET_LIST_VIDEOS, CREATE_PLAYLIST, - DELETE_LIST, - UPDATE_LIST, - ADD_USERS, - DELETE_USERS, - SEARCH_USER + DELETE_PLAYLIST, + UPDATE_PLAYLIST, + ADD_VIDEOS, + DELETE_VIDEOS } private OnPlaylistActionInterface listener; @@ -56,15 +53,17 @@ public class ManagePlaylistsAsyncTask extends AsyncTask { private int statusCode; private action apiAction; private WeakReference contextReference; - private String max_id, since_id; + private String max_id; + private Playlist playlist; + private String videoId; - public ManagePlaylistsAsyncTask(Context context, action apiAction, Playlist playlist, String max_id, String since_id, OnPlaylistActionInterface onPlaylistActionInterface){ + public ManagePlaylistsAsyncTask(Context context, action apiAction, Playlist playlist, String videoId, String max_id, OnPlaylistActionInterface onPlaylistActionInterface){ contextReference = new WeakReference<>(context); this.listener = onPlaylistActionInterface; this.apiAction = apiAction; this.max_id = max_id; - this.since_id = since_id; - + this.playlist = playlist; + this.videoId = videoId; } @@ -77,22 +76,18 @@ public class ManagePlaylistsAsyncTask extends AsyncTask { Account account = new AccountDAO(contextReference.get(), db).getAccountByUserIDInstance(userId, instance); if (apiAction == action.GET_PLAYLIST) { apiResponse = new PeertubeAPI(contextReference.get()).getPlayists(account.getUsername()); - }else if(apiAction == action.GET_LIST_TIMELINE){ - apiResponse = new API(contextReference.get()).getListTimeline(this.listId, this.max_id, this.since_id, this.limit); - }else if(apiAction == action.GET_LIST_ACCOUNT){ - apiResponse = new API(contextReference.get()).getAccountsInList(this.listId,0); + }else if(apiAction == action.GET_LIST_VIDEOS){ + apiResponse = new PeertubeAPI(contextReference.get()).getPlaylistVideos(playlist.getId(),max_id, null); }else if( apiAction == action.CREATE_PLAYLIST){ - apiResponse = new API(contextReference.get()).createPlaylist(this.title); - }else if(apiAction == action.DELETE_LIST){ - statusCode = new API(contextReference.get()).deleteList(this.listId); - }else if(apiAction == action.UPDATE_LIST){ - apiResponse = new API(contextReference.get()).updateList(this.listId, this.title); - }else if(apiAction == action.ADD_USERS){ - apiResponse = new API(contextReference.get()).addAccountToList(this.listId, this.accountsId); - }else if(apiAction == action.DELETE_USERS){ - statusCode = new API(contextReference.get()).deleteAccountFromList(this.listId, this.accountsId); - }else if( apiAction == action.SEARCH_USER){ - apiResponse = new API(contextReference.get()).searchAccounts(this.search, 20, true); + apiResponse = new PeertubeAPI(contextReference.get()).createPlaylist(playlist); + }else if(apiAction == action.DELETE_PLAYLIST){ + statusCode = new PeertubeAPI(contextReference.get()).deletePlaylist(playlist.getId()); + }else if(apiAction == action.UPDATE_PLAYLIST){ + apiResponse = new PeertubeAPI(contextReference.get()).updatePlaylist(playlist); + }else if(apiAction == action.ADD_VIDEOS){ + statusCode = new PeertubeAPI(contextReference.get()).addVideoPlaylist(playlist.getId(),videoId); + }else if(apiAction == action.DELETE_VIDEOS){ + statusCode = new PeertubeAPI(contextReference.get()).deleteVideoPlaylist(playlist.getId(),videoId); } return null; } diff --git a/app/src/main/java/app/fedilab/android/client/PeertubeAPI.java b/app/src/main/java/app/fedilab/android/client/PeertubeAPI.java index 5525e024f..55b008ab1 100644 --- a/app/src/main/java/app/fedilab/android/client/PeertubeAPI.java +++ b/app/src/main/java/app/fedilab/android/client/PeertubeAPI.java @@ -1333,159 +1333,6 @@ public class PeertubeAPI { - /** - * Get filters for the user - * @return APIResponse - */ - public APIResponse getFilters(){ - - List filters = null; - try { - String response = new HttpsConnection(context, this.instance).get(getAbsoluteUrl("/filters"), 60, null, prefKeyOauthTokenT); - filters = parseFilters(new JSONArray(response)); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } catch (KeyManagementException e) { - e.printStackTrace(); - } catch (JSONException e) { - e.printStackTrace(); - } - apiResponse.setFilters(filters); - return apiResponse; - } - - /** - * Get a Filter by its id - * @return APIResponse - */ - @SuppressWarnings("unused") - public APIResponse getFilters(String filterId){ - - List filters = new ArrayList<>(); - Filters filter; - try { - String response = new HttpsConnection(context, this.instance).get(getAbsoluteUrl(String.format("/filters/%s", filterId)), 60, null, prefKeyOauthTokenT); - filter = parseFilter(new JSONObject(response)); - filters.add(filter); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } catch (KeyManagementException e) { - e.printStackTrace(); - } catch (JSONException e) { - e.printStackTrace(); - } - apiResponse.setFilters(filters); - return apiResponse; - } - - - /** - * Create a filter - * @param filter Filter - * @return APIResponse - */ - public APIResponse addFilters(Filters filter){ - HashMap params = new HashMap<>(); - params.put("phrase", filter.getPhrase()); - StringBuilder parameters = new StringBuilder(); - for(String context: filter.getContext()) - parameters.append("context[]=").append(context).append("&"); - if( parameters.length() > 0) { - parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1).substring(10)); - params.put("context[]", parameters.toString()); - } - params.put("irreversible", String.valueOf(filter.isIrreversible())); - params.put("whole_word", String.valueOf(filter.isWhole_word())); - params.put("expires_in", String.valueOf(filter.getExpires_in())); - ArrayList filters = new ArrayList<>(); - try { - String response = new HttpsConnection(context, this.instance).post(getAbsoluteUrl("/filters"), 60, params, prefKeyOauthTokenT); - Filters resfilter = parseFilter(new JSONObject(response)); - filters.add(resfilter); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } catch (KeyManagementException e) { - e.printStackTrace(); - } catch (JSONException e) { - e.printStackTrace(); - } - apiResponse.setFilters(filters); - return apiResponse; - } - - /** - * Delete a filter - * @param filter Filter - * @return APIResponse - */ - public int deleteFilters(Filters filter){ - - try { - HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - httpsConnection.delete(getAbsoluteUrl(String.format("/filters/%s", filter.getId())), 60, null, prefKeyOauthTokenT); - actionCode = httpsConnection.getActionCode(); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } catch (KeyManagementException e) { - e.printStackTrace(); - } - return actionCode; - } - - /** - * Delete a filter - * @param filter Filter - * @return APIResponse - */ - public APIResponse updateFilters(Filters filter){ - HashMap params = new HashMap<>(); - params.put("phrase", filter.getPhrase()); - StringBuilder parameters = new StringBuilder(); - for(String context: filter.getContext()) - parameters.append("context[]=").append(context).append("&"); - if( parameters.length() > 0) { - parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1).substring(10)); - params.put("context[]", parameters.toString()); - } - params.put("irreversible", String.valueOf(filter.isIrreversible())); - params.put("whole_word", String.valueOf(filter.isWhole_word())); - params.put("expires_in", String.valueOf(filter.getExpires_in())); - ArrayList filters = new ArrayList<>(); - try { - String response = new HttpsConnection(context, this.instance).put(getAbsoluteUrl(String.format("/filters/%s", filter.getId())), 60, params, prefKeyOauthTokenT); - Filters resfilter = parseFilter(new JSONObject(response)); - filters.add(resfilter); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } catch (KeyManagementException e) { - e.printStackTrace(); - } catch (JSONException e) { - e.printStackTrace(); - } - apiResponse.setFilters(filters); - return apiResponse; - } - /** * Get lists for the user * @return APIResponse @@ -1512,6 +1359,200 @@ public class PeertubeAPI { } + /** + * Posts a Playlist + * @param playlist Playlist, the playlist + * @return APIResponse + */ + public APIResponse createPlaylist(Playlist playlist){ + + HashMap params = new HashMap<>(); + params.put("displayName",playlist.getDisplayName()); + if( playlist.getDescription() != null) + params.put("description",playlist.getDescription()); + if( playlist.getVideoChannelId() != null) + params.put("videoChannelId",playlist.getVideoChannelId()); + if( playlist.getPrivacy() != null) { + Map.Entry privacyM = playlist.getPrivacy().entrySet().iterator().next(); + Integer idPrivacy = privacyM.getKey(); + params.put("privacy", String.valueOf(idPrivacy)); + } + + List playlists = new ArrayList<>(); + Playlist playlistReply; + try { + String response = new HttpsConnection(context, this.instance).post(getAbsoluteUrl("/video-playlists"), 60, params, prefKeyOauthTokenT); + playlistReply = parsePlaylist(context, new JSONObject(response)); + playlists.add(playlistReply); + } catch (HttpsConnection.HttpsConnectionException e) { + setError(e.getStatusCode(), e); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (KeyManagementException e) { + e.printStackTrace(); + } catch (JSONException e) { + e.printStackTrace(); + } + apiResponse.setPlaylists(playlists); + return apiResponse; + } + + + /** + * Delete a Playlist + * @param playlistId String, the playlist id + * @return int + */ + public int deletePlaylist(String playlistId){ + try { + HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); + httpsConnection.delete(getAbsoluteUrl(String.format("/video-playlists/%s", playlistId)), 60, null, prefKeyOauthTokenT); + actionCode = httpsConnection.getActionCode(); + } catch (HttpsConnection.HttpsConnectionException e) { + setError(e.getStatusCode(), e); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (KeyManagementException e) { + e.printStackTrace(); + } + return actionCode; + } + + /** + * Update a Playlist + * @param playlist Playlist, the playlist + * @return APIResponse + */ + public APIResponse updatePlaylist(Playlist playlist){ + + HashMap params = new HashMap<>(); + params.put("displayName",playlist.getDisplayName()); + if( playlist.getDescription() != null) + params.put("description",playlist.getDescription()); + if( playlist.getVideoChannelId() != null) + params.put("videoChannelId",playlist.getVideoChannelId()); + if( playlist.getPrivacy() != null) { + Map.Entry privacyM = playlist.getPrivacy().entrySet().iterator().next(); + Integer idPrivacy = privacyM.getKey(); + params.put("privacy", String.valueOf(idPrivacy)); + } + + List playlists = new ArrayList<>(); + Playlist playlistReply; + try { + String response = new HttpsConnection(context, this.instance).post(getAbsoluteUrl(String.format("/video-playlists/%s", playlist.getId())), 60, params, prefKeyOauthTokenT); + playlistReply = parsePlaylist(context, new JSONObject(response)); + playlists.add(playlistReply); + } catch (HttpsConnection.HttpsConnectionException e) { + setError(e.getStatusCode(), e); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (KeyManagementException e) { + e.printStackTrace(); + } catch (JSONException e) { + e.printStackTrace(); + } + apiResponse.setPlaylists(playlists); + return apiResponse; + } + + /** + * Delete video in a Playlist + * @param playlistId String, the playlist id + * @param videoId String, the video id + * @return int + */ + public int deleteVideoPlaylist(String playlistId, String videoId){ + try { + HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); + httpsConnection.delete(getAbsoluteUrl(String.format("/video-playlists/%s/videos/%s", playlistId, videoId)), 60, null, prefKeyOauthTokenT); + actionCode = httpsConnection.getActionCode(); + } catch (HttpsConnection.HttpsConnectionException e) { + setError(e.getStatusCode(), e); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (KeyManagementException e) { + e.printStackTrace(); + } + return actionCode; + } + + /** + * Add video in a Playlist + * @param playlistId String, the playlist id + * @param videoId String, the video id + * @return int + */ + public int addVideoPlaylist(String playlistId, String videoId){ + try { + HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); + HashMap params = new HashMap<>(); + params.put("videoId", videoId); + httpsConnection.post(getAbsoluteUrl(String.format("/video-playlists/%s/videos", playlistId)), 60, params, prefKeyOauthTokenT); + actionCode = httpsConnection.getActionCode(); + } catch (HttpsConnection.HttpsConnectionException e) { + setError(e.getStatusCode(), e); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (KeyManagementException e) { + e.printStackTrace(); + } + return actionCode; + } + + + + /** + * Retrieves status for the account *synchronously* + * + * @param playlistid String Id of the playlist + * @param max_id String id max + * @param since_id String since the id + * @return APIResponse + */ + @SuppressWarnings("SameParameterValue") + public APIResponse getPlaylistVideos(String playlistid, String max_id, String since_id) { + + HashMap params = new HashMap<>(); + if (max_id != null) + params.put("start", max_id); + if (since_id != null) + params.put("since_id", since_id); + params.put("count", String.valueOf(tootPerPage)); + params.put("sort","-updatedAt"); + List peertubes = new ArrayList<>(); + try { + HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); + String response = httpsConnection.get(getAbsoluteUrl(String.format("/video-playlists/%s/videos", playlistid)), 60, params, prefKeyOauthTokenT); + JSONArray jsonArray = new JSONObject(response).getJSONArray("data"); + peertubes = parsePeertube(jsonArray); + + } catch (HttpsConnection.HttpsConnectionException e) { + setError(e.getStatusCode(), e); + e.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (KeyManagementException e) { + e.printStackTrace(); + } catch (JSONException e) { + e.printStackTrace(); + } + apiResponse.setPeertubes(peertubes); + return apiResponse; + } + /** * Parse json response for several howto diff --git a/app/src/main/java/app/fedilab/android/drawers/PlaylistAdapter.java b/app/src/main/java/app/fedilab/android/drawers/PlaylistAdapter.java new file mode 100644 index 000000000..9e418b60e --- /dev/null +++ b/app/src/main/java/app/fedilab/android/drawers/PlaylistAdapter.java @@ -0,0 +1,125 @@ +package app.fedilab.android.drawers; +/* Copyright 2019 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.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.drawable.Drawable; +import android.os.Bundle; +import android.support.v4.content.ContextCompat; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.BaseAdapter; +import android.widget.LinearLayout; +import android.widget.RelativeLayout; +import android.widget.TextView; + +import java.util.List; + +import app.fedilab.android.R; +import app.fedilab.android.activities.PlaylistsActivity; +import app.fedilab.android.client.Entities.Playlist; +import app.fedilab.android.helper.Helper; + + +/** + * Created by Thomas on 26/05/2019. + * Adapter for playlists + */ +public class PlaylistAdapter extends BaseAdapter { + + private List playlists; + private LayoutInflater layoutInflater; + private Context context; + + public PlaylistAdapter(Context context, List lists, RelativeLayout textviewNoAction){ + this.playlists = lists; + layoutInflater = LayoutInflater.from(context); + this.context = context; + } + + @Override + public int getCount() { + return playlists.size(); + } + + @Override + public Object getItem(int position) { + return playlists.get(position); + } + + @Override + public long getItemId(int position) { + return position; + } + + + @Override + public View getView(final int position, View convertView, ViewGroup parent) { + + final Playlist playlist = playlists.get(position); + final ViewHolder holder; + if (convertView == null) { + convertView = layoutInflater.inflate(R.layout.drawer_search, parent, false); + holder = new ViewHolder(); + holder.search_title = convertView.findViewById(R.id.search_keyword); + holder.search_container = convertView.findViewById(R.id.search_container); + convertView.setTag(holder); + } else { + holder = (ViewHolder) convertView.getTag(); + } + SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); + + if( theme == Helper.THEME_LIGHT){ + holder.search_container.setBackgroundResource(R.color.mastodonC3__); + Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right,R.color.black); + }else if(theme == Helper.THEME_DARK){ + holder.search_container.setBackgroundResource(R.color.mastodonC1_); + Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right,R.color.dark_text); + }else if(theme == Helper.THEME_BLACK) { + holder.search_container.setBackgroundResource(R.color.black_2); + Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right,R.color.dark_text); + } + Drawable next = ContextCompat.getDrawable(context, R.drawable.ic_keyboard_arrow_right); + holder.search_title.setText(playlist.getDisplayName()); + assert next != null; + final float scale = context.getResources().getDisplayMetrics().density; + next.setBounds(0,0,(int) (30 * scale + 0.5f),(int) (30 * scale + 0.5f)); + holder.search_title.setCompoundDrawables(null, null, next, null); + + holder.search_container.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + Intent intent = new Intent(context, PlaylistsActivity.class); + Bundle b = new Bundle(); + b.putParcelable("playlist", playlist); + intent.putExtras(b); + context.startActivity(intent); + } + }); + return convertView; + } + + private class ViewHolder { + LinearLayout search_container; + TextView search_title; + } + + +} \ No newline at end of file diff --git a/app/src/main/java/app/fedilab/android/fragments/DisplayPlaylistsFragment.java b/app/src/main/java/app/fedilab/android/fragments/DisplayPlaylistsFragment.java index d44c6d467..88b38f9fe 100644 --- a/app/src/main/java/app/fedilab/android/fragments/DisplayPlaylistsFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/DisplayPlaylistsFragment.java @@ -32,41 +32,57 @@ import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; +import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.Toast; +import com.jaredrummler.materialspinner.MaterialSpinner; + import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import app.fedilab.android.R; import app.fedilab.android.activities.ListActivity; import app.fedilab.android.activities.MainActivity; -import app.fedilab.android.asynctasks.ManageListsAsyncTask; import app.fedilab.android.asynctasks.ManagePlaylistsAsyncTask; +import app.fedilab.android.asynctasks.RetrievePeertubeChannelsAsyncTask; import app.fedilab.android.client.APIResponse; -import app.fedilab.android.drawers.ListAdapter; +import app.fedilab.android.client.Entities.Account; +import app.fedilab.android.client.Entities.Playlist; +import app.fedilab.android.drawers.PlaylistAdapter; import app.fedilab.android.helper.Helper; -import app.fedilab.android.interfaces.OnListActionInterface; import app.fedilab.android.interfaces.OnPlaylistActionInterface; +import app.fedilab.android.interfaces.OnRetrievePeertubeInterface; import es.dmoral.toasty.Toasty; +import static app.fedilab.android.asynctasks.RetrievePeertubeInformationAsyncTask.peertubeInformation; + /** * Created by Thomas on 26/05/2019. * Fragment to display Playlists */ -public class DisplayPlaylistsFragment extends Fragment implements OnPlaylistActionInterface { +public class DisplayPlaylistsFragment extends Fragment implements OnPlaylistActionInterface, OnRetrievePeertubeInterface { private Context context; private AsyncTask asyncTask; - private List lists; + private List playlists; private RelativeLayout mainLoader; private FloatingActionButton add_new; - private ListAdapter listAdapter; + private PlaylistAdapter playlistAdapter; private RelativeLayout textviewNoAction; + private HashMap privacyToSend; + private HashMap channelToSend; + private MaterialSpinner set_upload_channel; + private MaterialSpinner set_upload_privacy; + private HashMap channels; @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { @@ -75,7 +91,7 @@ public class DisplayPlaylistsFragment extends Fragment implements OnPlaylistActi View rootView = inflater.inflate(R.layout.fragment_playlists, container, false); context = getContext(); - lists = new ArrayList<>(); + playlists = new ArrayList<>(); ListView lv_playlist = rootView.findViewById(R.id.lv_playlist); @@ -84,66 +100,121 @@ public class DisplayPlaylistsFragment extends Fragment implements OnPlaylistActi RelativeLayout nextElementLoader = rootView.findViewById(R.id.loading_next_items); mainLoader.setVisibility(View.VISIBLE); nextElementLoader.setVisibility(View.GONE); - lists = new ArrayList<>(); - listAdapter = new ListAdapter(context, lists, textviewNoAction); - lv_playlist.setAdapter(listAdapter); + playlists = new ArrayList<>(); + playlistAdapter = new PlaylistAdapter(context, playlists, textviewNoAction); + lv_playlist.setAdapter(playlistAdapter); asyncTask = new ManagePlaylistsAsyncTask(context, ManagePlaylistsAsyncTask.action.GET_PLAYLIST, null, null, null,DisplayPlaylistsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); try { add_new = ((MainActivity) context).findViewById(R.id.add_new); }catch (Exception ignored){} - if( add_new != null) - add_new.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - int style; - if (theme == Helper.THEME_DARK) { - style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ - style = R.style.DialogBlack; - }else { - style = R.style.Dialog; + + + LinkedHashMap translations = null; + if( peertubeInformation.getTranslations() != null) + translations = new LinkedHashMap<>(peertubeInformation.getTranslations()); + + LinkedHashMap privaciesInit = new LinkedHashMap<>(peertubeInformation.getPrivacies()); + Map.Entry entryInt = privaciesInit.entrySet().iterator().next(); + privacyToSend = new HashMap<>(); + privacyToSend.put(entryInt.getKey(), entryInt.getValue()); + LinkedHashMap privacies = new LinkedHashMap<>(peertubeInformation.getPrivacies()); + //Populate privacies + String[] privaciesA = new String[privacies.size()]; + Iterator it = privacies.entrySet().iterator(); + int i = 0; + while (it.hasNext()) { + Map.Entry pair = (Map.Entry)it.next(); + if( translations == null || translations.size() == 0 || !translations.containsKey((String)pair.getValue())) + privaciesA[i] = (String)pair.getValue(); + else + privaciesA[i] = translations.get((String)pair.getValue()); + it.remove(); + i++; + } + + + + + if( add_new != null){ + add_new.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); + int style; + if (theme == Helper.THEME_DARK) { + style = R.style.DialogDark; + } else if (theme == Helper.THEME_BLACK){ + style = R.style.DialogBlack; + }else { + style = R.style.Dialog; + } + AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, style); + LayoutInflater inflater = ((Activity)context).getLayoutInflater(); + @SuppressLint("InflateParams") View dialogView = inflater.inflate(R.layout.add_playlist, null); + dialogBuilder.setView(dialogView); + EditText display_name = dialogView.findViewById(R.id.display_name); + EditText description = dialogView.findViewById(R.id.description); + set_upload_channel = dialogView.findViewById(R.id.set_upload_channel); + set_upload_privacy = dialogView.findViewById(R.id.set_upload_privacy); + + Helper.changeMaterialSpinnerColor(context, set_upload_privacy); + Helper.changeMaterialSpinnerColor(context, set_upload_channel); + + new RetrievePeertubeChannelsAsyncTask(context, DisplayPlaylistsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + channels = new HashMap<>(); + + display_name.setFilters(new InputFilter[]{new InputFilter.LengthFilter(120)}); + description.setFilters(new InputFilter[]{new InputFilter.LengthFilter(1000)}); + + dialogBuilder.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + if( display_name.getText() != null && display_name.getText().toString().trim().length() > 0 ) { + Playlist playlist = new Playlist(); + playlist.setDisplayName(display_name.getText().toString().trim()); + if( description.getText() != null ){ + playlist.setDescription(description.getText().toString().trim()); + } + if( channelToSend != null) { + Map.Entry channelM = channelToSend.entrySet().iterator().next(); + String idChannel = channelM.getValue(); + playlist.setVideoChannelId(idChannel); + } + if( privacyToSend != null){ + playlist.setPrivacy(privacyToSend); + } + new ManagePlaylistsAsyncTask(context, ManagePlaylistsAsyncTask.action.CREATE_PLAYLIST, playlist, null, null, DisplayPlaylistsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + } + dialog.dismiss(); + add_new.setEnabled(false); + } + }); + dialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + dialog.dismiss(); + } + }); + + + AlertDialog alertDialog = dialogBuilder.create(); + alertDialog.setTitle(getString(R.string.action_lists_create)); + alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() { + @Override + public void onDismiss(DialogInterface dialogInterface) { + //Hide keyboard + InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); + assert imm != null; + imm.hideSoftInputFromWindow(display_name.getWindowToken(), 0); + } + }); + if( alertDialog.getWindow() != null ) + alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); + alertDialog.show(); } - AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, style); - LayoutInflater inflater = ((Activity)context).getLayoutInflater(); - @SuppressLint("InflateParams") View dialogView = inflater.inflate(R.layout.add_list, null); - dialogBuilder.setView(dialogView); - final EditText editText = dialogView.findViewById(R.id.add_list); - editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(255)}); - dialogBuilder.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int id) { - if( editText.getText() != null && editText.getText().toString().trim().length() > 0 ) - new ManagePlaylistsAsyncTask(context, ManagePlaylistsAsyncTask.action.CREATE_PLAYLIST, null, null, null, editText.getText().toString().trim(), DisplayPlaylistsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - dialog.dismiss(); - add_new.setEnabled(false); - } - }); - dialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int id) { - dialog.dismiss(); - } - }); - - - AlertDialog alertDialog = dialogBuilder.create(); - alertDialog.setTitle(getString(R.string.action_lists_create)); - alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() { - @Override - public void onDismiss(DialogInterface dialogInterface) { - //Hide keyboard - InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); - assert imm != null; - imm.hideSoftInputFromWindow(editText.getWindowToken(), 0); - } - }); - if( alertDialog.getWindow() != null ) - alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); - alertDialog.show(); - } - }); + }); + } return rootView; } @@ -181,8 +252,8 @@ public class DisplayPlaylistsFragment extends Fragment implements OnPlaylistActi } if( actionType == ManagePlaylistsAsyncTask.action.GET_PLAYLIST) { if (apiResponse.getLists() != null && apiResponse.getLists().size() > 0) { - this.lists.addAll(apiResponse.getLists()); - listAdapter.notifyDataSetChanged(); + this.playlists.addAll(apiResponse.getPlaylists()); + playlistAdapter.notifyDataSetChanged(); textviewNoAction.setVisibility(View.GONE); } else { textviewNoAction.setVisibility(View.VISIBLE); @@ -197,15 +268,102 @@ public class DisplayPlaylistsFragment extends Fragment implements OnPlaylistActi b.putString("title", title); intent.putExtras(b); context.startActivity(intent); - this.lists.add(0, apiResponse.getLists().get(0)); - listAdapter.notifyDataSetChanged(); + this.playlists.add(0, apiResponse.getPlaylists().get(0)); + playlistAdapter.notifyDataSetChanged(); textviewNoAction.setVisibility(View.GONE); }else{ Toasty.error(context, apiResponse.getError().getError(),Toast.LENGTH_LONG).show(); } - }else if( actionType == ManagePlaylistsAsyncTask.action.DELETE_LIST){ - if( this.lists.size() == 0) + }else if( actionType == ManagePlaylistsAsyncTask.action.DELETE_PLAYLIST){ + if( this.playlists.size() == 0) textviewNoAction.setVisibility(View.VISIBLE); } } + + + @Override + public void onRetrievePeertube(APIResponse apiResponse) { + + } + + @Override + public void onRetrievePeertubeComments(APIResponse apiResponse) { + + } + + @Override + public void onRetrievePeertubeChannels(APIResponse apiResponse) { + if (apiResponse.getError() != null || apiResponse.getAccounts() == null || apiResponse.getAccounts().size() == 0) { + if (apiResponse.getError() != null && apiResponse.getError().getError() != null) + Toasty.error(context, apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); + else + Toasty.error(context, getString(R.string.toast_error), Toast.LENGTH_LONG).show(); + return; + } + + //Populate channels + List accounts = apiResponse.getAccounts(); + String[] channelName = new String[accounts.size()]; + String[] channelId = new String[accounts.size()]; + int i = 0; + for (Account account : accounts) { + channels.put(account.getUsername(), account.getId()); + channelName[i] = account.getUsername(); + channelId[i] = account.getId(); + i++; + } + + channelToSend = new HashMap<>(); + channelToSend.put(channelName[0], channelId[0]); + ArrayAdapter adapterChannel = new ArrayAdapter<>(context, + android.R.layout.simple_spinner_dropdown_item, channelName); + set_upload_channel.setAdapter(adapterChannel); + + LinkedHashMap translations = null; + if (peertubeInformation.getTranslations() != null) + translations = new LinkedHashMap<>(peertubeInformation.getTranslations()); + + LinkedHashMap privaciesInit = new LinkedHashMap<>(peertubeInformation.getPrivacies()); + Map.Entry entryInt = privaciesInit.entrySet().iterator().next(); + privacyToSend = new HashMap<>(); + privacyToSend.put(entryInt.getKey(), entryInt.getValue()); + LinkedHashMap privacies = new LinkedHashMap<>(peertubeInformation.getPrivacies()); + //Populate privacies + String[] privaciesA = new String[privacies.size()]; + Iterator it = privacies.entrySet().iterator(); + i = 0; + while (it.hasNext()) { + Map.Entry pair = (Map.Entry) it.next(); + if (translations == null || translations.size() == 0 || !translations.containsKey((String) pair.getValue())) + privaciesA[i] = (String) pair.getValue(); + else + privaciesA[i] = translations.get((String) pair.getValue()); + it.remove(); + i++; + } + + ArrayAdapter adapterPrivacies = new ArrayAdapter<>(context, + android.R.layout.simple_spinner_dropdown_item, privaciesA); + set_upload_privacy.setAdapter(adapterPrivacies); + + //Manage privacies + set_upload_privacy.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener() { + @Override + public void onItemSelected(MaterialSpinner view, int position, long id, String item) { + LinkedHashMap privaciesCheck = new LinkedHashMap<>(peertubeInformation.getPrivacies()); + Iterator it = privaciesCheck.entrySet().iterator(); + int i = 0; + while (it.hasNext()) { + Map.Entry pair = (Map.Entry) it.next(); + if (i == position) { + privacyToSend = new HashMap<>(); + privacyToSend.put((Integer) pair.getKey(), (String) pair.getValue()); + break; + } + it.remove(); + i++; + } + } + }); + } } diff --git a/app/src/main/res/layout/add_playlist.xml b/app/src/main/res/layout/add_playlist.xml new file mode 100644 index 000000000..dea09134b --- /dev/null +++ b/app/src/main/res/layout/add_playlist.xml @@ -0,0 +1,77 @@ + + + + + + + + + + + + + + + + + + + + \ 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 88b6a56a3..20c8ad376 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -952,6 +952,9 @@ Remember the position in Home timeline History Playlists + Display name + Privacy + Create %d vote