Add layout for playlists

This commit is contained in:
tom79 2019-05-26 17:56:02 +02:00
parent 00c8c4fa88
commit f76750420d
7 changed files with 656 additions and 254 deletions

View File

@ -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<Peertube> 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<Status> statuses = apiResponse.getStatuses();
max_id = apiResponse.getMax_id();
flag_loading = (max_id == null);

View File

@ -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<Void, Void, Void> {
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<Void, Void, Void> {
private int statusCode;
private action apiAction;
private WeakReference<Context> 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<Void, Void, Void> {
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;
}

View File

@ -1333,159 +1333,6 @@ public class PeertubeAPI {
/**
* Get filters for the user
* @return APIResponse
*/
public APIResponse getFilters(){
List<Filters> 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> 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<String, String> 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> 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<String, String> 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> 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<String, String> 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<Integer, String> privacyM = playlist.getPrivacy().entrySet().iterator().next();
Integer idPrivacy = privacyM.getKey();
params.put("privacy", String.valueOf(idPrivacy));
}
List<Playlist> 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<String, String> 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<Integer, String> privacyM = playlist.getPrivacy().entrySet().iterator().next();
Integer idPrivacy = privacyM.getKey();
params.put("privacy", String.valueOf(idPrivacy));
}
List<Playlist> 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<String, String> 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<String, String> 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<Peertube> 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

View File

@ -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 <http://www.gnu.org/licenses>. */
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<Playlist> playlists;
private LayoutInflater layoutInflater;
private Context context;
public PlaylistAdapter(Context context, List<Playlist> 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;
}
}

View File

@ -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<Void, Void, Void> asyncTask;
private List<app.fedilab.android.client.Entities.List> lists;
private List<Playlist> playlists;
private RelativeLayout mainLoader;
private FloatingActionButton add_new;
private ListAdapter listAdapter;
private PlaylistAdapter playlistAdapter;
private RelativeLayout textviewNoAction;
private HashMap<Integer, String> privacyToSend;
private HashMap<String, String> channelToSend;
private MaterialSpinner set_upload_channel;
private MaterialSpinner set_upload_privacy;
private HashMap<String, String> 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<String, String> translations = null;
if( peertubeInformation.getTranslations() != null)
translations = new LinkedHashMap<>(peertubeInformation.getTranslations());
LinkedHashMap<Integer, String> privaciesInit = new LinkedHashMap<>(peertubeInformation.getPrivacies());
Map.Entry<Integer,String> entryInt = privaciesInit.entrySet().iterator().next();
privacyToSend = new HashMap<>();
privacyToSend.put(entryInt.getKey(), entryInt.getValue());
LinkedHashMap<Integer, String> 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<String, String> 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<Account> 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<String> adapterChannel = new ArrayAdapter<>(context,
android.R.layout.simple_spinner_dropdown_item, channelName);
set_upload_channel.setAdapter(adapterChannel);
LinkedHashMap<String, String> translations = null;
if (peertubeInformation.getTranslations() != null)
translations = new LinkedHashMap<>(peertubeInformation.getTranslations());
LinkedHashMap<Integer, String> privaciesInit = new LinkedHashMap<>(peertubeInformation.getPrivacies());
Map.Entry<Integer, String> entryInt = privaciesInit.entrySet().iterator().next();
privacyToSend = new HashMap<>();
privacyToSend.put(entryInt.getKey(), entryInt.getValue());
LinkedHashMap<Integer, String> 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<String> 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<String>() {
@Override
public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
LinkedHashMap<Integer, String> 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++;
}
}
});
}
}

View File

@ -0,0 +1,77 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<TextView
android:layout_marginTop="10dp"
android:labelFor="@+id/display_name"
android:text="@string/display_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:layout_marginTop="5dp"
android:id="@+id/display_name"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="1"
/>
<TextView
android:layout_marginTop="10dp"
android:labelFor="@+id/description"
android:layout_width="match_parent"
android:text="@string/description"
android:layout_height="wrap_content" />
<EditText
android:layout_marginTop="5dp"
android:id="@+id/description"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="5"
/>
<!-- Videos channels -->
<LinearLayout
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:gravity="center"
android:textSize="16sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/channel"/>
<com.jaredrummler.materialspinner.MaterialSpinner
android:textSize="16sp"
android:id="@+id/set_upload_channel"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<!-- Videos Privacy -->
<LinearLayout
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:gravity="center"
android:textSize="16sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/action_privacy"/>
<com.jaredrummler.materialspinner.MaterialSpinner
android:textSize="16sp"
android:id="@+id/set_upload_privacy"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>

View File

@ -952,6 +952,9 @@
<string name="set_remember_position">Remember the position in Home timeline</string>
<string name="history">History</string>
<string name="playlists">Playlists</string>
<string name="display_name">Display name</string>
<string name="privacy">Privacy</string>
<string name="create">Create</string>
<plurals name="number_of_vote">
<item quantity="one">%d vote</item>