diff --git a/app/build.gradle b/app/build.gradle index 4b7aa4a..d87e06b 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -10,8 +10,8 @@ android { minSdkVersion 21 targetSdkVersion 30 - versionCode 11 - versionName "1.1.1" + versionCode 10 + versionName "1.1.0" multiDexEnabled true testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } @@ -117,4 +117,7 @@ dependencies { implementation "com.google.code.gson:gson:2.8.6" implementation 'androidx.media:media:1.2.0' + implementation 'com.squareup.retrofit2:retrofit:2.9.0' + implementation 'com.squareup.retrofit2:converter-gson:2.9.0' + } \ No newline at end of file diff --git a/app/src/main/java/app/fedilab/fedilabtube/AccountActivity.java b/app/src/main/java/app/fedilab/fedilabtube/AccountActivity.java index e70a9b5..8c5c421 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/AccountActivity.java +++ b/app/src/main/java/app/fedilab/fedilabtube/AccountActivity.java @@ -43,14 +43,14 @@ import org.jetbrains.annotations.NotNull; import java.util.List; -import app.fedilab.fedilabtube.client.entities.Account; +import app.fedilab.fedilabtube.client.RetrofitPeertubeAPI; +import app.fedilab.fedilabtube.client.data.AccountData.Account; import app.fedilab.fedilabtube.drawer.OwnAccountsAdapter; import app.fedilab.fedilabtube.fragment.DisplayAccountsFragment; import app.fedilab.fedilabtube.fragment.DisplayNotificationsFragment; import app.fedilab.fedilabtube.helper.Helper; import app.fedilab.fedilabtube.sqlite.AccountDAO; import app.fedilab.fedilabtube.sqlite.Sqlite; -import app.fedilab.fedilabtube.viewmodel.AccountsVM; public class AccountActivity extends AppCompatActivity { @@ -96,19 +96,19 @@ public class AccountActivity extends AppCompatActivity { TextView username = findViewById(R.id.username); TextView displayname = findViewById(R.id.displayname); - setTitle(String.format("@%s", account.getUsername())); + setTitle(String.format("@%s", account.getName())); - Helper.loadGiF(AccountActivity.this, account, profile_picture); - username.setText(String.format("@%s", account.getUsername())); - displayname.setText(account.getDisplay_name()); + Helper.loadGiF(AccountActivity.this, account.getAvatar().getPath(), profile_picture); + username.setText(String.format("@%s", account.getName())); + displayname.setText(account.getDisplayName()); - instanceView.setText(account.getInstance()); + instanceView.setText(account.getHost()); Button logout_button = findViewById(R.id.logout_button); Account finalAccount = account; logout_button.setOnClickListener(v -> { AlertDialog.Builder dialogBuilderLogoutAccount = new AlertDialog.Builder(AccountActivity.this); - dialogBuilderLogoutAccount.setMessage(getString(R.string.logout_account_confirmation, finalAccount.getUsername(), finalAccount.getInstance())); + dialogBuilderLogoutAccount.setMessage(getString(R.string.logout_account_confirmation, finalAccount.getName(), finalAccount.getHost())); dialogBuilderLogoutAccount.setPositiveButton(R.string.action_logout, (dialog, id) -> { Helper.logoutCurrentUser(AccountActivity.this, finalAccount); dialog.dismiss(); @@ -233,7 +233,7 @@ public class AccountActivity extends AppCompatActivity { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, account.getToken()); - editor.putString(Helper.PREF_INSTANCE, account.getInstance()); + editor.putString(Helper.PREF_INSTANCE, account.getHost()); editor.putString(Helper.PREF_KEY_ID, account.getId()); editor.apply(); dialog.dismiss(); @@ -270,15 +270,15 @@ public class AccountActivity extends AppCompatActivity { case 2: DisplayAccountsFragment displayAccountsFragment = new DisplayAccountsFragment(); if (position == 1) { - bundle.putSerializable("accountFetch", AccountsVM.accountFetch.MUTED); + bundle.putSerializable("accountFetch", RetrofitPeertubeAPI.DataType.MUTED); } else { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(AccountActivity.this); Account account = new AccountDAO(AccountActivity.this, db).getUniqAccount(userId, instance); - bundle.putString("name", account.getUsername() + "@" + account.getInstance()); - bundle.putSerializable("accountFetch", AccountsVM.accountFetch.CHANNEL); + bundle.putString("name", account.getName() + "@" + account.getHost()); + bundle.putSerializable("accountFetch", RetrofitPeertubeAPI.DataType.CHANNEL); } displayAccountsFragment.setArguments(bundle); return displayAccountsFragment; diff --git a/app/src/main/java/app/fedilab/fedilabtube/AllPlaylistsActivity.java b/app/src/main/java/app/fedilab/fedilabtube/AllPlaylistsActivity.java index 1bb7d9e..9984bb3 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/AllPlaylistsActivity.java +++ b/app/src/main/java/app/fedilab/fedilabtube/AllPlaylistsActivity.java @@ -15,6 +15,7 @@ package app.fedilab.fedilabtube; * see . */ import android.content.Context; +import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.Looper; @@ -48,12 +49,13 @@ import java.util.List; import java.util.Map; import app.fedilab.fedilabtube.client.APIResponse; -import app.fedilab.fedilabtube.client.HttpsConnection; -import app.fedilab.fedilabtube.client.PeertubeAPI; -import app.fedilab.fedilabtube.client.entities.Account; -import app.fedilab.fedilabtube.client.entities.Playlist; -import app.fedilab.fedilabtube.client.entities.PlaylistElement; +import app.fedilab.fedilabtube.client.RetrofitPeertubeAPI; +import app.fedilab.fedilabtube.client.data.AccountData.Account; +import app.fedilab.fedilabtube.client.data.PlaylistData.Playlist; +import app.fedilab.fedilabtube.client.entities.Item; +import app.fedilab.fedilabtube.client.entities.PlaylistParams; import app.fedilab.fedilabtube.drawer.PlaylistAdapter; +import app.fedilab.fedilabtube.helper.Helper; import app.fedilab.fedilabtube.viewmodel.ChannelsVM; import app.fedilab.fedilabtube.viewmodel.PlaylistsVM; import es.dmoral.toasty.Toasty; @@ -93,7 +95,7 @@ public class AllPlaylistsActivity extends AppCompatActivity { idChannel = null; PlaylistsVM viewModel = new ViewModelProvider(AllPlaylistsActivity.this).get(PlaylistsVM.class); - viewModel.manage(PlaylistsVM.action.GET_PLAYLIST, null, null, null).observe(AllPlaylistsActivity.this, apiResponse -> manageVIewPlaylists(PlaylistsVM.action.GET_PLAYLIST, apiResponse)); + viewModel.manage(PlaylistsVM.action.GET_PLAYLISTS, null, null).observe(AllPlaylistsActivity.this, apiResponse -> manageVIewPlaylists(PlaylistsVM.action.GET_PLAYLISTS, apiResponse)); FloatingActionButton add_new = findViewById(R.id.add_new); @@ -135,7 +137,7 @@ public class AllPlaylistsActivity extends AppCompatActivity { Toasty.error(AllPlaylistsActivity.this, apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); return; } - if (actionType == PlaylistsVM.action.GET_PLAYLIST) { + if (actionType == PlaylistsVM.action.GET_PLAYLISTS) { if (apiResponse.getPlaylists() != null && apiResponse.getPlaylists().size() > 0) { playlists.addAll(apiResponse.getPlaylists()); playlistAdapter.notifyDataSetChanged(); @@ -158,9 +160,10 @@ public class AllPlaylistsActivity extends AppCompatActivity { set_upload_channel = dialogView.findViewById(R.id.set_upload_channel); set_upload_privacy = dialogView.findViewById(R.id.set_upload_privacy); - + SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); + String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); ChannelsVM viewModelC = new ViewModelProvider(AllPlaylistsActivity.this).get(ChannelsVM.class); - viewModelC.get().observe(AllPlaylistsActivity.this, this::manageVIewChannels); + viewModelC.get(RetrofitPeertubeAPI.DataType.CHANNELS_FOR_ACCOUNT, userId).observe(AllPlaylistsActivity.this, this::manageVIewChannels); display_name.setFilters(new InputFilter[]{new InputFilter.LengthFilter(120)}); description.setFilters(new InputFilter[]{new InputFilter.LengthFilter(1000)}); @@ -178,64 +181,51 @@ public class AllPlaylistsActivity extends AppCompatActivity { Button button = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE); button.setOnClickListener(view -> { if (display_name.getText() != null && display_name.getText().toString().trim().length() > 0) { - PlaylistElement playlistElement = new PlaylistElement(); + PlaylistParams playlistElement = new PlaylistParams(); playlistElement.setDisplayName(display_name.getText().toString().trim()); if (description.getText() != null && description.getText().toString().trim().length() > 0) { playlistElement.setDescription(description.getText().toString().trim()); } playlistElement.setVideoChannelId(idChannel); - String idPrivacy; String label; Map.Entry privacyM = privacyToSend.entrySet().iterator().next(); - idPrivacy = String.valueOf(privacyM.getKey()); + Item privacyItem = new Item(); + privacyItem.setId(privacyM.getKey()); + privacyItem.setLabel(privacyM.getValue()); label = privacyM.getValue(); if ((label.trim().compareTo("Public") == 0 && (playlistElement.getVideoChannelId() == null || playlistElement.getVideoChannelId().trim().compareTo("null") == 0))) { Toasty.error(AllPlaylistsActivity.this, getString(R.string.error_channel_mandatory), Toast.LENGTH_LONG).show(); } else { if (privacyToSend != null) { - playlistElement.setPrivacy(idPrivacy); + playlistElement.setPrivacy((int) privacyItem.getId()); } new Thread(() -> { - try { - String playlistId; - if (playlistToEdit == null) { - playlistId = new PeertubeAPI(AllPlaylistsActivity.this).createPlaylist(playlistElement); - } else { - playlistId = playlistToEdit.getId(); - playlistElement.setPlaylistId(playlistId); - new PeertubeAPI(AllPlaylistsActivity.this).updatePlaylist(playlistElement); - } - Handler mainHandler = new Handler(Looper.getMainLooper()); - Runnable myRunnable = () -> { - Playlist playlist; - if (playlistToEdit == null) { - playlist = new Playlist(); - } else { - playlist = playlistToEdit; - } - playlist.setId(playlistId); - playlist.setDescription(playlistElement.getDescription()); - playlist.setDisplayName(playlistElement.getDisplayName()); - playlist.setVideoChannelId(playlistElement.getVideoChannelId()); - playlist.setPrivacy(privacyToSend); - if (playlistToEdit == null) { - playlists.add(playlist); - } - playlistAdapter.notifyDataSetChanged(); - }; - mainHandler.post(myRunnable); - } catch (HttpsConnection.HttpsConnectionException e) { - e.printStackTrace(); - Handler mainHandler = new Handler(Looper.getMainLooper()); - Runnable myRunnable = () -> { - if (e.getMessage() != null) { - Toasty.error(AllPlaylistsActivity.this, e.getMessage(), Toast.LENGTH_LONG).show(); - } else { - Toasty.error(AllPlaylistsActivity.this, getString(R.string.toast_error), Toast.LENGTH_LONG).show(); - } - }; - mainHandler.post(myRunnable); + String playlistId; + if (playlistToEdit == null) { + APIResponse apiResponse = new RetrofitPeertubeAPI(AllPlaylistsActivity.this).createOrUpdatePlaylist(PlaylistsVM.action.CREATE_PLAYLIST, null, playlistElement, null); + playlistId = apiResponse.getActionReturn(); + } else { + playlistId = playlistToEdit.getId(); + new RetrofitPeertubeAPI(AllPlaylistsActivity.this).createOrUpdatePlaylist(PlaylistsVM.action.UPDATE_PLAYLIST, playlistId, playlistElement, null); } + Handler mainHandler = new Handler(Looper.getMainLooper()); + Runnable myRunnable = () -> { + Playlist playlist; + if (playlistToEdit == null) { + playlist = new Playlist(); + } else { + playlist = playlistToEdit; + } + playlist.setId(playlistId); + playlist.setDescription(playlistElement.getDescription()); + playlist.setDisplayName(playlistElement.getDisplayName()); + playlist.setPrivacy(privacyItem); + if (playlistToEdit == null) { + playlists.add(playlist); + } + playlistAdapter.notifyDataSetChanged(); + }; + mainHandler.post(myRunnable); }).start(); alertDialog.dismiss(); } @@ -280,7 +270,7 @@ public class AllPlaylistsActivity extends AppCompatActivity { channelId[0] = "null"; for (Account account : channels) { - channelName[i] = account.getUsername(); + channelName[i] = account.getName(); channelId[i] = account.getId(); i++; } @@ -318,13 +308,9 @@ public class AllPlaylistsActivity extends AppCompatActivity { set_upload_privacy.setAdapter(adapterPrivacies); if (playlistToEdit != null) { - it = playlistToEdit.getPrivacy().entrySet().iterator(); - Map.Entry pair = null; - while (it.hasNext()) { - pair = it.next(); - } - if (pair != null) { - set_upload_privacy.setSelection(pair.getKey() - 1); + Item privacy = playlistToEdit.getPrivacy(); + if (privacy.getId() > 0) { + set_upload_privacy.setSelection((int) privacy.getId() - 1); } } else { set_upload_privacy.setSelection(2); @@ -356,13 +342,10 @@ public class AllPlaylistsActivity extends AppCompatActivity { }); if (playlistToEdit != null) { - it = playlistToEdit.getPrivacy().entrySet().iterator(); - Map.Entry pair = null; - while (it.hasNext()) { - pair = it.next(); - } - if (pair != null) { - set_upload_privacy.setSelection(pair.getKey() - 1); + Item privacy = playlistToEdit.getPrivacy(); + + if (privacy.getId() > 0) { + set_upload_privacy.setSelection((int) privacy.getId() - 1); } } @@ -383,7 +366,7 @@ public class AllPlaylistsActivity extends AppCompatActivity { int position = 0; int k = 1; for (Account ac : channels) { - if (playlistToEdit.getVideoChannelId() != null && ac.getId().compareTo(playlistToEdit.getVideoChannelId()) == 0) { + if (playlistToEdit.getId() != null && ac.getId().compareTo(playlistToEdit.getId()) == 0) { position = k; break; } diff --git a/app/src/main/java/app/fedilab/fedilabtube/InstancePickerActivity.java b/app/src/main/java/app/fedilab/fedilabtube/InstancePickerActivity.java index c2a24cf..e471e5b 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/InstancePickerActivity.java +++ b/app/src/main/java/app/fedilab/fedilabtube/InstancePickerActivity.java @@ -41,21 +41,19 @@ import java.util.List; import java.util.Map; import app.fedilab.fedilabtube.client.APIResponse; -import app.fedilab.fedilabtube.client.entities.Instance; +import app.fedilab.fedilabtube.client.data.InstanceData; import app.fedilab.fedilabtube.client.entities.InstanceParams; import app.fedilab.fedilabtube.drawer.InstanceAdapter; import app.fedilab.fedilabtube.helper.RoundedBackgroundSpan; import app.fedilab.fedilabtube.viewmodel.InstancesVM; import es.dmoral.toasty.Toasty; - import static app.fedilab.fedilabtube.MainActivity.peertubeInformation; public class InstancePickerActivity extends AppCompatActivity { - private RelativeLayout mainLoader, textviewNoAction; boolean[] checkedItemsCategory; int[] itemsKeyCategory; String[] itemsLabelCategory; @@ -63,6 +61,7 @@ public class InstancePickerActivity extends AppCompatActivity { String[] itemsKeyLanguage; String[] itemsLabelLanguage; InstanceParams instanceParams; + private RelativeLayout mainLoader, textviewNoAction; private TextView categories_view, languages_view; private InstancesVM viewModel; @@ -82,7 +81,7 @@ public class InstancePickerActivity extends AppCompatActivity { Button pickup_categories = findViewById(R.id.pickup_categories); Button pickup_languages = findViewById(R.id.pickup_languages); categories_view = findViewById(R.id.categories_view); - languages_view = findViewById(R.id.languages_view); + languages_view = findViewById(R.id.languages_view); Spinner sensitive = findViewById(R.id.sensitive); String[] channelSensitive = new String[]{"do_not_list", "blur", "display", "no_opinion"}; @@ -270,7 +269,7 @@ public class InstancePickerActivity extends AppCompatActivity { Toasty.error(InstancePickerActivity.this, apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); return; } - List instances = apiResponse.getInstances(); + List instances = apiResponse.getInstances(); RecyclerView lv_instances = findViewById(R.id.lv_instances); if ((instances == null || instances.size() == 0)) { textviewNoAction.setVisibility(View.VISIBLE); diff --git a/app/src/main/java/app/fedilab/fedilabtube/MainActivity.java b/app/src/main/java/app/fedilab/fedilabtube/MainActivity.java index 16c7b91..a1dcc5a 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/MainActivity.java +++ b/app/src/main/java/app/fedilab/fedilabtube/MainActivity.java @@ -43,15 +43,14 @@ import com.google.android.material.bottomnavigation.BottomNavigationView; import org.jetbrains.annotations.NotNull; -import app.fedilab.fedilabtube.client.PeertubeAPI; -import app.fedilab.fedilabtube.client.entities.Account; -import app.fedilab.fedilabtube.client.entities.InstanceNodeInfo; +import app.fedilab.fedilabtube.client.RetrofitPeertubeAPI; +import app.fedilab.fedilabtube.client.data.AccountData.Account; import app.fedilab.fedilabtube.client.entities.PeertubeInformation; import app.fedilab.fedilabtube.helper.Helper; import app.fedilab.fedilabtube.services.RetrieveInfoService; import app.fedilab.fedilabtube.sqlite.AccountDAO; import app.fedilab.fedilabtube.sqlite.Sqlite; -import app.fedilab.fedilabtube.viewmodel.FeedsVM; +import app.fedilab.fedilabtube.viewmodel.TimelineVM; import es.dmoral.toasty.Toasty; import static app.fedilab.fedilabtube.helper.Helper.academies; @@ -165,7 +164,7 @@ public class MainActivity extends AppCompatActivity { SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); Account account = new AccountDAO(MainActivity.this, db).getUniqAccount(userId, instance); if (account != null) { - new Thread(() -> new PeertubeAPI(MainActivity.this).refreshToken(account.getToken(), account.getInstance())).start(); + new Thread(() -> new RetrofitPeertubeAPI(MainActivity.this).refreshToken(account.getToken(), account.getHost())).start(); } } else { instanceItem.setVisible(true); @@ -206,14 +205,14 @@ public class MainActivity extends AppCompatActivity { } else if (item.getItemId() == R.id.action_myvideos) { Intent intent = new Intent(MainActivity.this, MyVideosActivity.class); Bundle bundle = new Bundle(); - bundle.putSerializable("type", FeedsVM.Type.MYVIDEOS); + bundle.putSerializable("type", TimelineVM.Type.MYVIDEOS); intent.putExtras(bundle); startActivity(intent); return true; } else if (item.getItemId() == R.id.action_history) { Intent intent = new Intent(MainActivity.this, MyVideosActivity.class); Bundle bundle = new Bundle(); - bundle.putSerializable("type", FeedsVM.Type.PEERTUBE_HISTORY); + bundle.putSerializable("type", TimelineVM.Type.PEERTUBE_HISTORY); intent.putExtras(bundle); startActivity(intent); return true; @@ -286,7 +285,7 @@ public class MainActivity extends AppCompatActivity { (dialog, which) -> new Thread(() -> { try { String newInstance = input.getText().toString().trim(); - InstanceNodeInfo instanceNodeInfo = new PeertubeAPI(MainActivity.this).displayNodeInfo(newInstance); + InstanceNodeInfo instanceNodeInfo = new RetrofitPeertubeAPI(MainActivity.this).displayNodeInfo(newInstance); if (instanceNodeInfo.getName() != null && instanceNodeInfo.getName().trim().toLowerCase().compareTo("peertube") == 0) { SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(Helper.PREF_INSTANCE, newInstance); diff --git a/app/src/main/java/app/fedilab/fedilabtube/MyVideosActivity.java b/app/src/main/java/app/fedilab/fedilabtube/MyVideosActivity.java index 0db01de..af1723f 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/MyVideosActivity.java +++ b/app/src/main/java/app/fedilab/fedilabtube/MyVideosActivity.java @@ -20,13 +20,13 @@ import android.view.MenuItem; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.FragmentTransaction; -import app.fedilab.fedilabtube.fragment.DisplayStatusFragment; -import app.fedilab.fedilabtube.viewmodel.FeedsVM; +import app.fedilab.fedilabtube.fragment.DisplayVideosFragment; +import app.fedilab.fedilabtube.viewmodel.TimelineVM; public class MyVideosActivity extends AppCompatActivity { - private FeedsVM.Type type; + private TimelineVM.Type type; @Override protected void onCreate(Bundle savedInstanceState) { @@ -39,23 +39,23 @@ public class MyVideosActivity extends AppCompatActivity { Bundle b = getIntent().getExtras(); if (b != null) - type = (FeedsVM.Type) b.get("type"); + type = (TimelineVM.Type) b.get("type"); - if (type == FeedsVM.Type.MYVIDEOS) { + if (type == TimelineVM.Type.MYVIDEOS) { setTitle(R.string.my_videos); - } else if (type == FeedsVM.Type.PSUBSCRIPTIONS) { + } else if (type == TimelineVM.Type.PSUBSCRIPTIONS) { setTitle(R.string.subscriptions); - } else if (type == FeedsVM.Type.PEERTUBE_HISTORY) { + } else if (type == TimelineVM.Type.PEERTUBE_HISTORY) { setTitle(R.string.my_history); } if (savedInstanceState == null) { - DisplayStatusFragment displayStatusFragment = new DisplayStatusFragment(); + DisplayVideosFragment displayVideosFragment = new DisplayVideosFragment(); Bundle bundle = new Bundle(); bundle.putSerializable("type", type); - displayStatusFragment.setArguments(bundle); + displayVideosFragment.setArguments(bundle); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); - ft.add(R.id.container, displayStatusFragment).commit(); + ft.add(R.id.container, displayVideosFragment).commit(); } } diff --git a/app/src/main/java/app/fedilab/fedilabtube/PeertubeActivity.java b/app/src/main/java/app/fedilab/fedilabtube/PeertubeActivity.java index d58e0ad..35ead4a 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/PeertubeActivity.java +++ b/app/src/main/java/app/fedilab/fedilabtube/PeertubeActivity.java @@ -81,6 +81,7 @@ import com.google.android.exoplayer2.util.MimeTypes; import com.google.android.exoplayer2.util.Util; import org.jetbrains.annotations.NotNull; + import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; @@ -93,24 +94,24 @@ import javax.net.ssl.HttpsURLConnection; import app.fedilab.fedilabtube.client.APIResponse; import app.fedilab.fedilabtube.client.PeertubeAPI; +import app.fedilab.fedilabtube.client.RetrofitPeertubeAPI; import app.fedilab.fedilabtube.client.TLSSocketFactory; -import app.fedilab.fedilabtube.client.entities.Account; +import app.fedilab.fedilabtube.client.data.AccountData; +import app.fedilab.fedilabtube.client.data.CommentData; +import app.fedilab.fedilabtube.client.data.VideoData; import app.fedilab.fedilabtube.client.entities.Caption; -import app.fedilab.fedilabtube.client.entities.Peertube; +import app.fedilab.fedilabtube.client.entities.File; import app.fedilab.fedilabtube.client.entities.Playlist; import app.fedilab.fedilabtube.client.entities.PlaylistElement; -import app.fedilab.fedilabtube.client.entities.Status; -import app.fedilab.fedilabtube.client.entities.StatusDrawerParams; -import app.fedilab.fedilabtube.drawer.StatusListAdapter; +import app.fedilab.fedilabtube.drawer.CommentListAdapter; import app.fedilab.fedilabtube.helper.CacheDataSourceFactory; import app.fedilab.fedilabtube.helper.FullScreenMediaController; import app.fedilab.fedilabtube.helper.Helper; import app.fedilab.fedilabtube.sqlite.AccountDAO; -import app.fedilab.fedilabtube.sqlite.PeertubeFavoritesDAO; import app.fedilab.fedilabtube.sqlite.Sqlite; import app.fedilab.fedilabtube.viewmodel.CaptionsVM; import app.fedilab.fedilabtube.viewmodel.CommentVM; -import app.fedilab.fedilabtube.viewmodel.FeedsVM; +import app.fedilab.fedilabtube.viewmodel.TimelineVM; import app.fedilab.fedilabtube.viewmodel.PlaylistsVM; import app.fedilab.fedilabtube.viewmodel.PostActionsVM; import app.fedilab.fedilabtube.webview.CustomWebview; @@ -133,7 +134,7 @@ public class PeertubeActivity extends AppCompatActivity { private RelativeLayout loader; private TextView peertube_view_count, peertube_playlist, peertube_bookmark, peertube_like_count, peertube_dislike_count, peertube_description, peertube_title, more_actions; private ScrollView peertube_information_container; - private Peertube peertube; + private VideoData.Video peertube; private PlayerView playerView; private SimpleExoPlayer player; private boolean fullScreenMode; @@ -189,8 +190,8 @@ public class PeertubeActivity extends AppCompatActivity { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(PeertubeActivity.this); - Account account = new AccountDAO(PeertubeActivity.this, db).getUniqAccount(userId, instance); - Helper.loadGiF(PeertubeActivity.this, account, my_pp); + AccountData.Account account = new AccountDAO(PeertubeActivity.this, db).getUniqAccount(userId, instance); + Helper.loadGiF(PeertubeActivity.this, account.getAvatar().getPath(), my_pp); if (Helper.isTablet(PeertubeActivity.this)) { @@ -306,7 +307,7 @@ public class PeertubeActivity extends AppCompatActivity { peertube_bookmark.setVisibility(View.GONE); - FeedsVM feedsViewModel = new ViewModelProvider(PeertubeActivity.this).get(FeedsVM.class); + TimelineVM feedsViewModel = new ViewModelProvider(PeertubeActivity.this).get(TimelineVM.class); feedsViewModel.getVideo(peertubeInstance, videoId).observe(PeertubeActivity.this, this::manageVIewVideo); CaptionsVM captionsViewModel = new ViewModelProvider(PeertubeActivity.this).get(CaptionsVM.class); @@ -394,12 +395,12 @@ public class PeertubeActivity extends AppCompatActivity { } else { if (type == PeertubeAPI.reportType.VIDEO) { PostActionsVM viewModel = new ViewModelProvider(PeertubeActivity.this).get(PostActionsVM.class); - viewModel.post(PeertubeAPI.StatusAction.REPORT_VIDEO, peertube.getId(), report_content.getText().toString(), null).observe(PeertubeActivity.this, apiResponse -> manageVIewPostActions(PeertubeAPI.StatusAction.REPORT_VIDEO, apiResponse)); + viewModel.post(RetrofitPeertubeAPI.ActionType.REPORT_VIDEO, peertube.getId(), report_content.getText().toString(), null).observe(PeertubeActivity.this, apiResponse -> manageVIewPostActions(PeertubeAPI.StatusAction.REPORT_VIDEO, apiResponse)); alertDialog.dismiss(); dialog.dismiss(); } else if (type == PeertubeAPI.reportType.ACCOUNT) { PostActionsVM viewModel = new ViewModelProvider(PeertubeActivity.this).get(PostActionsVM.class); - viewModel.post(PeertubeAPI.StatusAction.REPORT_ACCOUNT, peertube.getAccount().getId(), report_content.getText().toString(), null).observe(PeertubeActivity.this, apiResponse -> manageVIewPostActions(PeertubeAPI.StatusAction.REPORT_ACCOUNT, apiResponse)); + viewModel.post(RetrofitPeertubeAPI.ActionType.REPORT_ACCOUNT, peertube.getAccount().getId(), report_content.getText().toString(), null).observe(PeertubeActivity.this, apiResponse -> manageVIewPostActions(PeertubeAPI.StatusAction.REPORT_ACCOUNT, apiResponse)); alertDialog.dismiss(); dialog.dismiss(); } @@ -461,7 +462,7 @@ public class PeertubeActivity extends AppCompatActivity { String comment = add_comment_write.getText().toString(); if (comment.trim().length() > 0) { PostActionsVM viewModel = new ViewModelProvider(PeertubeActivity.this).get(PostActionsVM.class); - viewModel.post(PeertubeAPI.StatusAction.PEERTUBECOMMENT, peertube.getAccount().getId(), comment, null).observe(PeertubeActivity.this, apiResponse1 -> manageVIewPostActions(PeertubeAPI.StatusAction.PEERTUBECOMMENT, apiResponse1)); + viewModel.post(RetrofitPeertubeAPI.ActionType.PEERTUBECOMMENT, peertube.getAccount().getId(), comment, null).observe(PeertubeActivity.this, apiResponse1 -> manageVIewPostActions(PeertubeAPI.StatusAction.PEERTUBECOMMENT, apiResponse1)); add_comment_write.setText(""); add_comment_read.setVisibility(View.VISIBLE); add_comment_write.setVisibility(View.GONE); @@ -549,9 +550,9 @@ public class PeertubeActivity extends AppCompatActivity { setTitle(peertube.getName()); peertube_description.setText(peertube.getDescription()); peertube_title.setText(peertube.getName()); - peertube_dislike_count.setText(String.valueOf(peertube.getDislike())); - peertube_like_count.setText(String.valueOf(peertube.getLike())); - peertube_view_count.setText(String.valueOf(peertube.getView())); + peertube_dislike_count.setText(String.valueOf(peertube.getDislikes())); + peertube_like_count.setText(String.valueOf(peertube.getLikes())); + peertube_view_count.setText(String.valueOf(peertube.getViews())); video_id = peertube.getId(); changeColor(); @@ -561,7 +562,7 @@ public class PeertubeActivity extends AppCompatActivity { if (isLoggedIn(PeertubeActivity.this)) { String newState = peertube.getMyRating().equals("like") ? "none" : "like"; PostActionsVM viewModel = new ViewModelProvider(PeertubeActivity.this).get(PostActionsVM.class); - viewModel.post(PeertubeAPI.StatusAction.RATEVIDEO, peertube.getId(), newState, null).observe(PeertubeActivity.this, apiResponse1 -> manageVIewPostActions(PeertubeAPI.StatusAction.RATEVIDEO, apiResponse1)); + viewModel.post(RetrofitPeertubeAPI.ActionType.RATEVIDEO, peertube.getId(), newState, null).observe(PeertubeActivity.this, apiResponse1 -> manageVIewPostActions(PeertubeAPI.StatusAction.RATEVIDEO, apiResponse1)); peertube.setMyRating(newState); int count = Integer.parseInt(peertube_like_count.getText().toString()); if (newState.compareTo("none") == 0) { @@ -582,7 +583,7 @@ public class PeertubeActivity extends AppCompatActivity { if (isLoggedIn(PeertubeActivity.this)) { String newState = peertube.getMyRating().equals("dislike") ? "none" : "dislike"; PostActionsVM viewModel = new ViewModelProvider(PeertubeActivity.this).get(PostActionsVM.class); - viewModel.post(PeertubeAPI.StatusAction.RATEVIDEO, peertube.getId(), newState, null).observe(PeertubeActivity.this, apiResponse1 -> manageVIewPostActions(PeertubeAPI.StatusAction.RATEVIDEO, apiResponse1)); + viewModel.post(RetrofitPeertubeAPI.ActionType.RATEVIDEO, peertube.getId(), newState, null).observe(PeertubeActivity.this, apiResponse1 -> manageVIewPostActions(PeertubeAPI.StatusAction.RATEVIDEO, apiResponse1)); peertube.setMyRating(newState); int count = Integer.parseInt(peertube_dislike_count.getText().toString()); if (newState.compareTo("none") == 0) { @@ -644,10 +645,10 @@ public class PeertubeActivity extends AppCompatActivity { if (ContextCompat.checkSelfPermission(PeertubeActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(PeertubeActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(PeertubeActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, Helper.EXTERNAL_STORAGE_REQUEST_CODE); } else { - Helper.manageDownloads(PeertubeActivity.this, peertube.getFileDownloadUrl(null, PeertubeActivity.this)); + Helper.manageDownloads(PeertubeActivity.this, peertube.getFileDownloadUrl(null)); } } else { - Helper.manageDownloads(PeertubeActivity.this, peertube.getFileDownloadUrl(null, PeertubeActivity.this)); + Helper.manageDownloads(PeertubeActivity.this, peertube.getFileDownloadUrl(null)); } break; case R.id.action_share: @@ -655,7 +656,7 @@ public class PeertubeActivity extends AppCompatActivity { sendIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.shared_via)); String url; - url = "https://" + peertube.getInstance() + "/videos/watch/" + peertube.getUuid(); + url = peertube.getFiles().get(0).getFileDownloadUrl(); boolean share_details = sharedpreferences.getBoolean(Helper.SET_SHARE_DETAILS, true); String extra_text; if (share_details) { @@ -767,31 +768,6 @@ public class PeertubeActivity extends AppCompatActivity { popup.show(); }); - SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - List peertubes = new PeertubeFavoritesDAO(PeertubeActivity.this, db).getSinglePeertube(peertube); - - Drawable img; - - if (peertubes == null || peertubes.size() == 0) - img = ContextCompat.getDrawable(PeertubeActivity.this, R.drawable.ic_baseline_bookmark_border_24); - else - img = ContextCompat.getDrawable(PeertubeActivity.this, R.drawable.ic_baseline_bookmark_24); - peertube_bookmark.setCompoundDrawablesWithIntrinsicBounds(null, img, null, null); - - peertube_bookmark.setOnClickListener(v -> { - List peertubes1 = new PeertubeFavoritesDAO(PeertubeActivity.this, db).getSinglePeertube(peertube); - if (peertubes1 == null || peertubes1.size() == 0) { - new PeertubeFavoritesDAO(PeertubeActivity.this, db).insert(peertube); - Toasty.success(PeertubeActivity.this, getString(R.string.bookmark_add_peertube), Toast.LENGTH_SHORT).show(); - } else { - new PeertubeFavoritesDAO(PeertubeActivity.this, db).remove(peertube); - Toasty.success(PeertubeActivity.this, getString(R.string.bookmark_remove_peertube), Toast.LENGTH_SHORT).show(); - } - if (peertubes1 != null && peertubes1.size() > 0) //Was initially in cache - peertube_bookmark.setCompoundDrawablesWithIntrinsicBounds(null, ContextCompat.getDrawable(PeertubeActivity.this, R.drawable.ic_baseline_bookmark_border_24), null, null); - else - peertube_bookmark.setCompoundDrawablesWithIntrinsicBounds(null, ContextCompat.getDrawable(PeertubeActivity.this, R.drawable.ic_baseline_bookmark_24), null, null); - }); } @@ -821,25 +797,20 @@ public class PeertubeActivity extends AppCompatActivity { Toasty.error(PeertubeActivity.this, apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); return; } - List statuses = new ArrayList<>(); - for (Status status : apiResponse.getStatuses()) { - if (status.getContent() != null && status.getContent().trim().length() > 0) { - statuses.add(status); + List comments = new ArrayList<>(); + for (CommentData.Comment comment : apiResponse.getComments()) { + if (comment.getDescription() != null && comment.getDescription().trim().length() > 0) { + comments.add(comment); } } RecyclerView lv_comments = findViewById(R.id.peertube_comments); - if (statuses.size() > 0) { + if (comments.size() > 0) { lv_comments.setVisibility(View.VISIBLE); - SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); - String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - StatusDrawerParams statusDrawerParams = new StatusDrawerParams(); - statusDrawerParams.setTargetedId(userId); - statusDrawerParams.setStatuses(statuses); - StatusListAdapter statusListAdapter = new StatusListAdapter(statusDrawerParams); + CommentListAdapter commentListAdapter = new CommentListAdapter(comments); LinearLayoutManager mLayoutManager = new LinearLayoutManager(PeertubeActivity.this); lv_comments.setLayoutManager(mLayoutManager); lv_comments.setNestedScrollingEnabled(false); - lv_comments.setAdapter(statusListAdapter); + lv_comments.setAdapter(commentListAdapter); } } @@ -926,8 +897,11 @@ public class PeertubeActivity extends AppCompatActivity { AlertDialog.Builder builderSingle = new AlertDialog.Builder(PeertubeActivity.this); builderSingle.setTitle(R.string.pickup_resolution); final ArrayAdapter arrayAdapter = new ArrayAdapter<>(PeertubeActivity.this, android.R.layout.select_dialog_item); - for (String resolution : peertube.getResolution()) - arrayAdapter.add(resolution + "p"); + for (File file : peertube.getFiles()) { + if (file.getResolutions() != null) { + arrayAdapter.add(file.getResolutions().getLabel() + "p"); + } + } builderSingle.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()); builderSingle.setAdapter(arrayAdapter, (dialog, which) -> { String res = Objects.requireNonNull(arrayAdapter.getItem(which)).substring(0, Objects.requireNonNull(arrayAdapter.getItem(which)).length() - 1); diff --git a/app/src/main/java/app/fedilab/fedilabtube/PeertubeEditUploadActivity.java b/app/src/main/java/app/fedilab/fedilabtube/PeertubeEditUploadActivity.java index e135638..ae80376 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/PeertubeEditUploadActivity.java +++ b/app/src/main/java/app/fedilab/fedilabtube/PeertubeEditUploadActivity.java @@ -58,11 +58,11 @@ import java.util.UUID; import app.fedilab.fedilabtube.client.APIResponse; import app.fedilab.fedilabtube.client.PeertubeAPI; -import app.fedilab.fedilabtube.client.entities.Account; +import app.fedilab.fedilabtube.client.data.AccountData.Account; import app.fedilab.fedilabtube.client.entities.Peertube; import app.fedilab.fedilabtube.helper.Helper; import app.fedilab.fedilabtube.viewmodel.ChannelsVM; -import app.fedilab.fedilabtube.viewmodel.FeedsVM; +import app.fedilab.fedilabtube.viewmodel.TimelineVM; import app.fedilab.fedilabtube.viewmodel.PostActionsVM; import es.dmoral.toasty.Toasty; import mabbas007.tagsedittext.TagsEditText; @@ -219,7 +219,7 @@ public class PeertubeEditUploadActivity extends AppCompatActivity { String peertubeInstance = Helper.getLiveInstance(PeertubeEditUploadActivity.this); - FeedsVM feedsViewModel = new ViewModelProvider(PeertubeEditUploadActivity.this).get(FeedsVM.class); + TimelineVM feedsViewModel = new ViewModelProvider(PeertubeEditUploadActivity.this).get(TimelineVM.class); feedsViewModel.getVideo(peertubeInstance, videoId).observe(PeertubeEditUploadActivity.this, this::manageVIewVideo); channels = new LinkedHashMap<>(); @@ -525,7 +525,7 @@ public class PeertubeEditUploadActivity extends AppCompatActivity { List tags = p_video_tags.getTags(); peertube.setTags(tags); set_upload_submit.setEnabled(false); - FeedsVM feedsViewModel = new ViewModelProvider(PeertubeEditUploadActivity.this).get(FeedsVM.class); + TimelineVM feedsViewModel = new ViewModelProvider(PeertubeEditUploadActivity.this).get(TimelineVM.class); feedsViewModel.updateVideo(peertube).observe(PeertubeEditUploadActivity.this, this::manageVIewVideo); }); diff --git a/app/src/main/java/app/fedilab/fedilabtube/PeertubeUploadActivity.java b/app/src/main/java/app/fedilab/fedilabtube/PeertubeUploadActivity.java index 90ad2f0..45f8ec8 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/PeertubeUploadActivity.java +++ b/app/src/main/java/app/fedilab/fedilabtube/PeertubeUploadActivity.java @@ -54,7 +54,7 @@ import java.util.Map; import java.util.UUID; import app.fedilab.fedilabtube.client.APIResponse; -import app.fedilab.fedilabtube.client.entities.Account; +import app.fedilab.fedilabtube.client.data.AccountData.Account; import app.fedilab.fedilabtube.helper.Helper; import app.fedilab.fedilabtube.viewmodel.ChannelsVM; import es.dmoral.toasty.Toasty; diff --git a/app/src/main/java/app/fedilab/fedilabtube/SearchActivity.java b/app/src/main/java/app/fedilab/fedilabtube/SearchActivity.java index 05d64f5..4df50cf 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/SearchActivity.java +++ b/app/src/main/java/app/fedilab/fedilabtube/SearchActivity.java @@ -21,7 +21,7 @@ import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.FragmentTransaction; -import app.fedilab.fedilabtube.fragment.DisplayStatusFragment; +import app.fedilab.fedilabtube.fragment.DisplayVideosFragment; import es.dmoral.toasty.Toasty; @@ -48,12 +48,12 @@ public class SearchActivity extends AppCompatActivity { if (savedInstanceState == null) { - DisplayStatusFragment displayStatusFragment = new DisplayStatusFragment(); + DisplayVideosFragment displayVideosFragment = new DisplayVideosFragment(); Bundle bundle = new Bundle(); bundle.putString("search_peertube", search); - displayStatusFragment.setArguments(bundle); + displayVideosFragment.setArguments(bundle); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); - ft.add(R.id.container, displayStatusFragment).commit(); + ft.add(R.id.container, displayVideosFragment).commit(); } } diff --git a/app/src/main/java/app/fedilab/fedilabtube/ShowAccountActivity.java b/app/src/main/java/app/fedilab/fedilabtube/ShowAccountActivity.java index ef6656b..e076ff2 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/ShowAccountActivity.java +++ b/app/src/main/java/app/fedilab/fedilabtube/ShowAccountActivity.java @@ -52,13 +52,13 @@ import java.util.List; import app.fedilab.fedilabtube.client.APIResponse; import app.fedilab.fedilabtube.client.PeertubeAPI; -import app.fedilab.fedilabtube.client.entities.Account; +import app.fedilab.fedilabtube.client.data.AccountData.Account; import app.fedilab.fedilabtube.client.entities.Relationship; import app.fedilab.fedilabtube.fragment.DisplayAccountsFragment; -import app.fedilab.fedilabtube.fragment.DisplayStatusFragment; +import app.fedilab.fedilabtube.fragment.DisplayVideosFragment; import app.fedilab.fedilabtube.helper.Helper; import app.fedilab.fedilabtube.viewmodel.AccountsVM; -import app.fedilab.fedilabtube.viewmodel.FeedsVM; +import app.fedilab.fedilabtube.viewmodel.TimelineVM; import app.fedilab.fedilabtube.viewmodel.PostActionsVM; import app.fedilab.fedilabtube.viewmodel.RelationshipVM; import es.dmoral.toasty.Toasty; @@ -231,8 +231,8 @@ public class ShowAccountActivity extends AppCompatActivity { switch (tab.getPosition()) { case 0: if (fragment != null) { - DisplayStatusFragment displayStatusFragment = ((DisplayStatusFragment) fragment); - displayStatusFragment.scrollToTop(); + DisplayVideosFragment displayVideosFragment = ((DisplayVideosFragment) fragment); + displayVideosFragment.scrollToTop(); } break; case 1: @@ -433,13 +433,13 @@ public class ShowAccountActivity extends AppCompatActivity { public Fragment getItem(int position) { Bundle bundle = new Bundle(); if (position == 0) { - DisplayStatusFragment displayStatusFragment = new DisplayStatusFragment(); + DisplayVideosFragment displayVideosFragment = new DisplayVideosFragment(); bundle = new Bundle(); - bundle.putSerializable("type", FeedsVM.Type.USER); + bundle.putSerializable("type", TimelineVM.Type.USER); bundle.putString("targetedid", account.getAcct()); bundle.putBoolean("ischannel", ischannel); - displayStatusFragment.setArguments(bundle); - return displayStatusFragment; + displayVideosFragment.setArguments(bundle); + return displayVideosFragment; } DisplayAccountsFragment displayAccountsFragment = new DisplayAccountsFragment(); bundle.putString("targetedid", account.getId()); diff --git a/app/src/main/java/app/fedilab/fedilabtube/client/APIResponse.java b/app/src/main/java/app/fedilab/fedilabtube/client/APIResponse.java index 058d170..b51cd36 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/client/APIResponse.java +++ b/app/src/main/java/app/fedilab/fedilabtube/client/APIResponse.java @@ -15,43 +15,48 @@ package app.fedilab.fedilabtube.client; * see . */ import java.util.List; +import java.util.Map; -import app.fedilab.fedilabtube.client.entities.Account; -import app.fedilab.fedilabtube.client.entities.Caption; +import app.fedilab.fedilabtube.client.data.AccountData; +import app.fedilab.fedilabtube.client.data.CaptionData; +import app.fedilab.fedilabtube.client.data.ChannelData; +import app.fedilab.fedilabtube.client.data.CommentData; +import app.fedilab.fedilabtube.client.data.InstanceData; +import app.fedilab.fedilabtube.client.data.NotificationData; +import app.fedilab.fedilabtube.client.data.PlaylistData; +import app.fedilab.fedilabtube.client.data.VideoData; import app.fedilab.fedilabtube.client.entities.Error; -import app.fedilab.fedilabtube.client.entities.Instance; -import app.fedilab.fedilabtube.client.entities.Peertube; -import app.fedilab.fedilabtube.client.entities.PeertubeNotification; -import app.fedilab.fedilabtube.client.entities.Playlist; -import app.fedilab.fedilabtube.client.entities.PlaylistElement; -import app.fedilab.fedilabtube.client.entities.Relationship; -import app.fedilab.fedilabtube.client.entities.Status; +import app.fedilab.fedilabtube.client.entities.OverviewVideo; +import app.fedilab.fedilabtube.client.entities.Rating; @SuppressWarnings({"unused", "RedundantSuppression"}) public class APIResponse { - private List accounts = null; - private List statuses = null; + private List accounts = null; + private List channels = null; private String targetedId = null; - private List peertubes = null; - private List peertubeNotifications = null; - private List playlists = null; + private String actionReturn = null; + private Rating rating; + private OverviewVideo overviewVideo = null; + private List peertubes = null; + private List comments = null; + private List peertubeNotifications = null; + private List playlists = null; private List domains = null; - private List relationships = null; - private List captions = null; + private List> relationships = null; + private List captions = null; private Error error = null; private String since_id, max_id; - private List playlistForVideos; - private List instances; + private List instances; private String stringData; private int statusCode; private String captionText; - public List getAccounts() { + public List getAccounts() { return accounts; } - public void setAccounts(List accounts) { + public void setAccounts(List accounts) { this.accounts = accounts; } @@ -89,40 +94,32 @@ public class APIResponse { } - public List getPeertubes() { + public List getPeertubes() { return peertubes; } - public void setPeertubes(List peertubes) { + public void setPeertubes(List peertubes) { this.peertubes = peertubes; } - public List getPeertubeNotifications() { + public List getPeertubeNotifications() { return peertubeNotifications; } - public void setPeertubeNotifications(List peertubeNotifications) { + public void setPeertubeNotifications(List peertubeNotifications) { this.peertubeNotifications = peertubeNotifications; } - public List getPlaylists() { + public List getPlaylists() { return playlists; } - public void setPlaylists(List playlists) { + public void setPlaylists(List playlists) { this.playlists = playlists; } - public List getPlaylistForVideos() { - return playlistForVideos; - } - - public void setPlaylistForVideos(List playlistForVideos) { - this.playlistForVideos = playlistForVideos; - } - public String getTargetedId() { return targetedId; @@ -133,15 +130,6 @@ public class APIResponse { } - - public List getStatuses() { - return statuses; - } - - public void setStatuses(List statuses) { - this.statuses = statuses; - } - public String getStringData() { return stringData; } @@ -158,27 +146,27 @@ public class APIResponse { this.statusCode = statusCode; } - public List getRelationships() { + public List> getRelationships() { return relationships; } - public void setRelationships(List relationships) { + public void setRelationships(List> relationships) { this.relationships = relationships; } - public List getInstances() { + public List getInstances() { return instances; } - public void setInstances(List instances) { + public void setInstances(List instances) { this.instances = instances; } - public List getCaptions() { + public List getCaptions() { return captions; } - public void setCaptions(List captions) { + public void setCaptions(List captions) { this.captions = captions; } @@ -189,4 +177,44 @@ public class APIResponse { public void setCaptionText(String captionText) { this.captionText = captionText; } + + public List getChannels() { + return channels; + } + + public void setChannels(List channels) { + this.channels = channels; + } + + public List getComments() { + return comments; + } + + public void setComments(List comments) { + this.comments = comments; + } + + public Rating getRating() { + return rating; + } + + public void setRating(Rating rating) { + this.rating = rating; + } + + public OverviewVideo getOverviewVideo() { + return overviewVideo; + } + + public void setOverviewVideo(OverviewVideo overviewVideo) { + this.overviewVideo = overviewVideo; + } + + public String getActionReturn() { + return actionReturn; + } + + public void setActionReturn(String actionReturn) { + this.actionReturn = actionReturn; + } } diff --git a/app/src/main/java/app/fedilab/fedilabtube/client/HttpsConnection.java b/app/src/main/java/app/fedilab/fedilabtube/client/HttpsConnection.java index 088bcf2..e81e0e8 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/client/HttpsConnection.java +++ b/app/src/main/java/app/fedilab/fedilabtube/client/HttpsConnection.java @@ -53,7 +53,7 @@ import javax.net.ssl.HttpsURLConnection; import app.fedilab.fedilabtube.MainActivity; import app.fedilab.fedilabtube.R; -import app.fedilab.fedilabtube.client.entities.Account; +import app.fedilab.fedilabtube.client.data.AccountData.Account; import app.fedilab.fedilabtube.helper.Helper; import app.fedilab.fedilabtube.sqlite.AccountDAO; import app.fedilab.fedilabtube.sqlite.Sqlite; diff --git a/app/src/main/java/app/fedilab/fedilabtube/client/PeertubeAPI.java b/app/src/main/java/app/fedilab/fedilabtube/client/PeertubeAPI.java deleted file mode 100644 index 82150cd..0000000 --- a/app/src/main/java/app/fedilab/fedilabtube/client/PeertubeAPI.java +++ /dev/null @@ -1,2395 +0,0 @@ -package app.fedilab.fedilabtube.client; -/* 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 . */ - -import android.app.Activity; -import android.content.Context; -import android.content.SharedPreferences; -import android.database.sqlite.SQLiteDatabase; -import android.os.Build; -import android.text.Html; -import android.text.SpannableString; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -import app.fedilab.fedilabtube.BuildConfig; -import app.fedilab.fedilabtube.R; -import app.fedilab.fedilabtube.client.entities.Account; -import app.fedilab.fedilabtube.client.entities.AccountCreation; -import app.fedilab.fedilabtube.client.entities.Caption; -import app.fedilab.fedilabtube.client.entities.ChannelCreation; -import app.fedilab.fedilabtube.client.entities.Error; -import app.fedilab.fedilabtube.client.entities.Instance; -import app.fedilab.fedilabtube.client.entities.InstanceNodeInfo; -import app.fedilab.fedilabtube.client.entities.InstanceParams; -import app.fedilab.fedilabtube.client.entities.NodeInfo; -import app.fedilab.fedilabtube.client.entities.Peertube; -import app.fedilab.fedilabtube.client.entities.PeertubeAccountNotification; -import app.fedilab.fedilabtube.client.entities.PeertubeActorFollow; -import app.fedilab.fedilabtube.client.entities.PeertubeComment; -import app.fedilab.fedilabtube.client.entities.PeertubeInformation; -import app.fedilab.fedilabtube.client.entities.PeertubeNotification; -import app.fedilab.fedilabtube.client.entities.PeertubeVideoNotification; -import app.fedilab.fedilabtube.client.entities.Playlist; -import app.fedilab.fedilabtube.client.entities.PlaylistElement; -import app.fedilab.fedilabtube.client.entities.Relationship; -import app.fedilab.fedilabtube.client.entities.Status; -import app.fedilab.fedilabtube.helper.Helper; -import app.fedilab.fedilabtube.sqlite.AccountDAO; -import app.fedilab.fedilabtube.sqlite.Sqlite; - -/** - * Created by Thomas on 02/01/2019. - * Manage Calls to the Peertube REST API - */ - -public class PeertubeAPI { - - - private Account account; - private Context context; - private int tootPerPage; - private int actionCode; - private String instance; - private String prefKeyOauthTokenT; - private APIResponse apiResponse; - private Error APIError; - - public PeertubeAPI(Context context) { - this.context = context; - SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - tootPerPage = Helper.VIDEOS_PER_PAGE; - Helper.getLiveInstance(context); - this.instance = Helper.getLiveInstance(context); - this.prefKeyOauthTokenT = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); - apiResponse = new APIResponse(); - APIError = null; - } - - public PeertubeAPI(Context context, String instance, String token) { - this.context = context; - if (context == null) { - apiResponse = new APIResponse(); - APIError = new Error(); - return; - } - SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - tootPerPage = Helper.VIDEOS_PER_PAGE; - if (instance != null) - this.instance = instance; - else - this.instance = Helper.getLiveInstance(context); - - if (token != null) - this.prefKeyOauthTokenT = token; - else - this.prefKeyOauthTokenT = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); - apiResponse = new APIResponse(); - APIError = null; - } - - /** - * Parse json response for unique how to - * - * @param resobj JSONObject - * @return Peertube - */ - private static PeertubeNotification parsePeertubeNotifications(JSONObject resobj) { - PeertubeNotification peertubeNotification = new PeertubeNotification(); - try { - peertubeNotification.setId(resobj.getString("id")); - peertubeNotification.setType(resobj.getInt("type")); - peertubeNotification.setUpdatedAt(Helper.mstStringToDate(resobj.getString("updatedAt"))); - peertubeNotification.setCreatedAt(Helper.mstStringToDate(resobj.getString("createdAt"))); - peertubeNotification.setRead(resobj.getBoolean("read")); - - if (resobj.has("comment")) { - PeertubeComment peertubeComment = new PeertubeComment(); - JSONObject comment = resobj.getJSONObject("comment"); - if (comment.has("account")) { - JSONObject account = comment.getJSONObject("account"); - PeertubeAccountNotification peertubeAccountNotification = new PeertubeAccountNotification(); - peertubeAccountNotification.setDisplayName(account.getString("displayName")); - peertubeAccountNotification.setName(account.getString("name")); - peertubeAccountNotification.setId(account.getString("id")); - if (account.has("host")) { - peertubeAccountNotification.setHost(account.getString("host")); - } - peertubeAccountNotification.setAvatar(account.getJSONObject("avatar").getString("path")); - peertubeComment.setPeertubeAccountNotification(peertubeAccountNotification); - } - if (comment.has("video")) { - JSONObject video = comment.getJSONObject("video"); - PeertubeVideoNotification peertubeVideoNotification = new PeertubeVideoNotification(); - peertubeVideoNotification.setUuid(video.getString("uuid")); - peertubeVideoNotification.setName(video.getString("name")); - peertubeVideoNotification.setId(video.getString("id")); - peertubeComment.setPeertubeVideoNotification(peertubeVideoNotification); - } - peertubeComment.setId(comment.getString("id")); - peertubeComment.setThreadId(comment.getString("threadId")); - peertubeNotification.setPeertubeComment(peertubeComment); - } - - if (resobj.has("video")) { - PeertubeVideoNotification peertubeVideoNotification = new PeertubeVideoNotification(); - JSONObject video = resobj.getJSONObject("video"); - peertubeVideoNotification.setUuid(video.getString("uuid")); - peertubeVideoNotification.setName(video.getString("name")); - peertubeVideoNotification.setId(video.getString("id")); - if (video.has("channel")) { - PeertubeAccountNotification peertubeAccountNotification = new PeertubeAccountNotification(); - JSONObject channel = video.getJSONObject("channel"); - peertubeAccountNotification.setDisplayName(channel.getString("displayName")); - peertubeAccountNotification.setName(channel.getString("name")); - peertubeAccountNotification.setId(channel.getString("id")); - peertubeAccountNotification.setHost(channel.getString("host")); - if (channel.has("avatar")) { - peertubeAccountNotification.setAvatar(channel.getJSONObject("avatar").getString("path")); - } - peertubeVideoNotification.setPeertubeAccountNotification(peertubeAccountNotification); - } - peertubeNotification.setPeertubeVideoNotification(peertubeVideoNotification); - } - - if (resobj.has("actorFollow")) { - PeertubeActorFollow peertubeActorFollow = new PeertubeActorFollow(); - JSONObject actorFollow = resobj.getJSONObject("actorFollow"); - - JSONObject follower = actorFollow.getJSONObject("follower"); - JSONObject following = actorFollow.getJSONObject("following"); - - PeertubeAccountNotification peertubeAccountNotification = new PeertubeAccountNotification(); - peertubeAccountNotification.setDisplayName(follower.getString("displayName")); - peertubeAccountNotification.setName(follower.getString("name")); - peertubeAccountNotification.setId(follower.getString("id")); - if (follower.has("host")) { - peertubeAccountNotification.setHost(follower.getString("host")); - } - if (follower.has("avatar")) { - peertubeAccountNotification.setAvatar(follower.getJSONObject("avatar").getString("path")); - } - peertubeActorFollow.setFollower(peertubeAccountNotification); - - PeertubeAccountNotification peertubeAccounFollowingNotification = new PeertubeAccountNotification(); - peertubeAccounFollowingNotification.setDisplayName(following.getString("displayName")); - peertubeAccounFollowingNotification.setName(following.getString("name")); - try { - peertubeAccounFollowingNotification.setId(following.getString("id")); - } catch (Exception ignored) { - } - if (following.has("avatar")) { - peertubeAccounFollowingNotification.setAvatar(following.getJSONObject("avatar").getString("path")); - } - peertubeActorFollow.setFollowing(peertubeAccounFollowingNotification); - peertubeActorFollow.setId(actorFollow.getString("id")); - peertubeNotification.setPeertubeActorFollow(peertubeActorFollow); - - } - - } catch (JSONException | ParseException e) { - e.printStackTrace(); - } - - return peertubeNotification; - } - - /** - * Parse json response for unique how to - * - * @param resobj JSONObject - * @return Peertube - */ - public static Peertube parsePeertube(JSONObject resobj) { - Peertube peertube = new Peertube(); - if (resobj.has("video") && !resobj.isNull("video")) { - try { - resobj = resobj.getJSONObject("video"); - } catch (JSONException e) { - e.printStackTrace(); - } - } else { - if (!resobj.has("name")) { - return null; - } - } - try { - peertube.setId(resobj.getString("id")); - peertube.setCache(resobj); - if (resobj.has("uuid")) { - peertube.setUuid(resobj.getString("uuid")); - } - - peertube.setName(resobj.getString("name")); - peertube.setDescription(resobj.getString("description")); - peertube.setEmbedPath(resobj.getString("embedPath")); - peertube.setPreviewPath(resobj.getString("previewPath")); - peertube.setThumbnailPath(resobj.getString("thumbnailPath")); - peertube.setAccount(parseAccountResponsePeertube(resobj.getJSONObject("account"))); - try { - peertube.setChannel(parseAccountResponsePeertube(resobj.getJSONObject("channel"))); - } catch (Exception ignored) { - } - peertube.setView(resobj.getInt("views")); - peertube.setLike(resobj.getInt("likes")); - peertube.setDislike(resobj.getInt("dislikes")); - peertube.setDuration(resobj.getInt("duration")); - peertube.setSensitive(resobj.getBoolean("nsfw")); - try { - peertube.setCommentsEnabled(resobj.getBoolean("commentsEnabled")); - } catch (Exception ignored) { - } - try { - peertube.setCreated_at(Helper.mstStringToDate(resobj.getString("createdAt"))); - } catch (ParseException e) { - e.printStackTrace(); - } - try { - LinkedHashMap langue = new LinkedHashMap<>(); - LinkedHashMap category = new LinkedHashMap<>(); - LinkedHashMap license = new LinkedHashMap<>(); - LinkedHashMap privacy = new LinkedHashMap<>(); - - if (!resobj.getJSONObject("category").isNull("id")) { - license.put(resobj.getJSONObject("category").getInt("id"), resobj.getJSONObject("category").getString("label")); - } else { - license.put(1, resobj.getJSONObject("category").getString("label")); - } - if (!resobj.getJSONObject("licence").isNull("id")) { - license.put(resobj.getJSONObject("licence").getInt("id"), resobj.getJSONObject("licence").getString("label")); - } else { - license.put(1, resobj.getJSONObject("licence").getString("label")); - } - privacy.put(resobj.getJSONObject("privacy").getInt("id"), resobj.getJSONObject("privacy").getString("label")); - langue.put(resobj.getJSONObject("language").getString("id"), resobj.getJSONObject("language").getString("label")); - peertube.setCategory(category); - peertube.setLicense(license); - peertube.setLanguage(langue); - peertube.setPrivacy(privacy); - } catch (Exception e) { - e.printStackTrace(); - } - } catch (JSONException e) { - e.printStackTrace(); - } - - return peertube; - } - - /** - * Parse json response for unique how to - * - * @param resobj JSONObject - * @return Peertube - */ - private static Peertube parseSinglePeertube(String instance, JSONObject resobj) { - Peertube peertube = new Peertube(); - try { - peertube.setId(resobj.getString("id")); - peertube.setUuid(resobj.getString("uuid")); - peertube.setName(resobj.getString("name")); - peertube.setCache(resobj); - peertube.setInstance(instance); - peertube.setHost(resobj.getJSONObject("account").getString("host")); - peertube.setDescription(resobj.getString("description")); - peertube.setEmbedPath(resobj.getString("embedPath")); - peertube.setPreviewPath(resobj.getString("previewPath")); - peertube.setThumbnailPath(resobj.getString("thumbnailPath")); - peertube.setView(resobj.getInt("views")); - peertube.setLike(resobj.getInt("likes")); - peertube.setCommentsEnabled(resobj.getBoolean("commentsEnabled")); - peertube.setDislike(resobj.getInt("dislikes")); - peertube.setDuration(resobj.getInt("duration")); - peertube.setAccount(parseAccountResponsePeertube(resobj.getJSONObject("account"))); - List tags = new ArrayList<>(); - try { - JSONArray tagsA = resobj.getJSONArray("tags"); - for (int i = 0; i < tagsA.length(); i++) { - String value = tagsA.getString(i); - tags.add(value); - } - peertube.setTags(tags); - } catch (Exception ignored) { - } - try { - peertube.setChannel(parseAccountResponsePeertube(resobj.getJSONObject("channel"))); - } catch (Exception ignored) { - } - peertube.setSensitive(resobj.getBoolean("nsfw")); - try { - peertube.setCreated_at(Helper.mstStringToDate(resobj.getString("createdAt"))); - } catch (ParseException e) { - e.printStackTrace(); - } - - try { - peertube.setCreated_at(Helper.mstStringToDate(resobj.getString("createdAt"))); - } catch (ParseException e) { - e.printStackTrace(); - } - ArrayList resolutions = new ArrayList<>(); - if (resobj.has("streamingPlaylists") && resobj.getJSONArray("streamingPlaylists").length() > 0) { - JSONArray files = resobj.getJSONArray("streamingPlaylists").getJSONObject(0).getJSONArray("files"); - - for (int j = 0; j < files.length(); j++) { - JSONObject attObj = files.getJSONObject(j); - resolutions.add(attObj.getJSONObject("resolution").getString("id")); - } - peertube.setResolution(resolutions); - } else { - JSONArray files = resobj.getJSONArray("files"); - for (int j = 0; j < files.length(); j++) { - JSONObject attObj = files.getJSONObject(j); - resolutions.add(attObj.getJSONObject("resolution").getString("id")); - } - peertube.setResolution(resolutions); - } - try { - LinkedHashMap langue = new LinkedHashMap<>(); - LinkedHashMap category = new LinkedHashMap<>(); - LinkedHashMap license = new LinkedHashMap<>(); - LinkedHashMap privacy = new LinkedHashMap<>(); - if (!resobj.getJSONObject("category").isNull("id")) { - license.put(resobj.getJSONObject("category").getInt("id"), resobj.getJSONObject("category").getString("label")); - } else { - license.put(1, resobj.getJSONObject("category").getString("label")); - } - if (!resobj.getJSONObject("licence").isNull("id")) { - license.put(resobj.getJSONObject("licence").getInt("id"), resobj.getJSONObject("licence").getString("label")); - } else { - license.put(1, resobj.getJSONObject("licence").getString("label")); - } - privacy.put(resobj.getJSONObject("privacy").getInt("id"), resobj.getJSONObject("privacy").getString("label")); - langue.put(resobj.getJSONObject("language").getString("id"), resobj.getJSONObject("language").get("label").toString()); - - peertube.setCategory(category); - peertube.setLicense(license); - peertube.setLanguage(langue); - peertube.setPrivacy(privacy); - } catch (Exception ignored) { - } - peertube.setResolution(resolutions); - } catch (JSONException e) { - e.printStackTrace(); - } - - return peertube; - } - - /** - * Parse json response for emoji - * - * @param resobj JSONObject - * @return Emojis - */ - private static Playlist parsePlaylist(Context context, JSONObject resobj) { - Playlist playlist = new Playlist(); - try { - playlist.setId(resobj.getString("id")); - playlist.setUuid(resobj.getString("uuid")); - playlist.setCreatedAt(Helper.stringToDate(context, resobj.getString("createdAt"))); - playlist.setDescription(resobj.getString("description")); - playlist.setDisplayName(resobj.getString("displayName")); - playlist.setLocal(resobj.getBoolean("isLocal")); - if (resobj.has("videoChannel") && !resobj.isNull("videoChannel")) { - playlist.setVideoChannelId(resobj.getJSONObject("videoChannel").getString("id")); - } - playlist.setThumbnailPath(resobj.getString("thumbnailPath")); - playlist.setOwnerAccount(parseAccountResponsePeertube(resobj.getJSONObject("ownerAccount"))); - playlist.setVideosLength(resobj.getInt("videosLength")); - try { - LinkedHashMap type = new LinkedHashMap<>(); - LinkedHashMap privacy = new LinkedHashMap<>(); - privacy.put(resobj.getJSONObject("privacy").getInt("id"), resobj.getJSONObject("privacy").get("label").toString()); - type.put(resobj.getJSONObject("type").getInt("id"), resobj.getJSONObject("type").get("label").toString()); - playlist.setType(type); - playlist.setPrivacy(privacy); - } catch (Exception ignored) { - } - try { - playlist.setUpdatedAt(Helper.stringToDate(context, resobj.getString("updatedAt"))); - } catch (Exception ignored) { - } - } catch (Exception ignored) { - } - return playlist; - } - - /** - * Parse json response an unique peertube account - * - * @param accountObject JSONObject - * @return Account - */ - private static Account parseAccountResponsePeertube(JSONObject accountObject) { - Account account = new Account(); - try { - account.setId(accountObject.getString("id")); - account.setUuid(accountObject.getString("id")); - account.setUsername(accountObject.getString("name")); - account.setAcct(accountObject.getString("name") + "@" + accountObject.get("host")); - account.setDisplay_name(accountObject.get("displayName").toString()); - account.setHost(accountObject.getString("host")); - account.setSocial("PEERTUBE"); - account.setInstance(accountObject.getString("host")); - if (accountObject.has("ownerAccount")) { - account.setchannelOwner(parseAccountResponsePeertube(accountObject.getJSONObject("ownerAccount"))); - } - if (accountObject.has("createdAt")) - account.setCreated_at(Helper.mstStringToDate(accountObject.getString("createdAt"))); - else - account.setCreated_at(new Date()); - if (accountObject.has("followersCount")) - account.setFollowers_count(accountObject.getInt("followersCount")); - else - account.setFollowers_count(0); - if (accountObject.has("followingCount")) - account.setFollowing_count(accountObject.getInt("followingCount")); - else - account.setFollowing_count(0); - account.setStatuses_count(0); - if (accountObject.has("description")) - account.setNote(accountObject.getString("description")); - else - account.setNote(""); - - if (accountObject.has("url")) { - account.setUrl(accountObject.getString("url")); - } - if (accountObject.has("avatar") && !accountObject.isNull("avatar")) { - account.setAvatar(accountObject.getJSONObject("avatar").getString("path")); - account.setAvatar_static(accountObject.getJSONObject("avatar").getString("path")); - } else { - account.setAvatar("null"); - account.setAvatar_static("null"); - } - account.setHeader("null"); - account.setHeader_static("null"); - - } catch (JSONException | ParseException e) { - e.printStackTrace(); - } - return account; - } - - /** - * Parse json response for peertube comments - * - * @param resobj JSONObject - * @return Peertube - */ - private static List parseSinglePeertubeComments(String instance, JSONObject resobj) { - List statuses = new ArrayList<>(); - try { - JSONArray jsonArray = resobj.getJSONArray("data"); - int i = 0; - while (i < jsonArray.length()) { - Status status = new Status(); - JSONObject comment = jsonArray.getJSONObject(i); - status.setId(comment.getString("id")); - status.setUri(comment.getString("url")); - status.setUrl(comment.getString("url")); - status.setSensitive(false); - status.setContent(comment.getString("text")); - status.setIn_reply_to_id(comment.getString("inReplyToCommentId")); - if (comment.has("account") && !comment.isNull("account")) { - status.setAccount(parseAccountResponsePeertube(instance, comment.getJSONObject("account"))); - } - status.setCreated_at(Helper.mstStringToDate(comment.getString("createdAt"))); - status.setVisibility("public"); - SpannableString spannableString; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) - spannableString = new SpannableString(Html.fromHtml(status.getContent(), Html.FROM_HTML_MODE_LEGACY)); - else - spannableString = new SpannableString(Html.fromHtml(status.getContent())); - status.setContentSpan(new SpannableString(spannableString)); - i++; - statuses.add(status); - } - } catch (JSONException | ParseException e) { - e.printStackTrace(); - } - return statuses; - } - - /** - * Parse json response an unique peertube account - * - * @param resobj JSONObject - * @return Account - */ - private static Account parseAccountResponsePeertube(String instance, JSONObject resobj) { - Account account = new Account(); - try { - account.setId(resobj.getString("id")); - account.setUsername(resobj.getString("name")); - account.setAcct(resobj.getString("name") + "@" + resobj.getString("host")); - account.setDisplay_name(resobj.get("displayName").toString()); - account.setHost(resobj.getString("host")); - if (resobj.has("createdAt")) - account.setCreated_at(Helper.mstStringToDate(resobj.getString("createdAt"))); - else - account.setCreated_at(new Date()); - - if (resobj.has("followersCount")) - account.setFollowers_count(resobj.getInt("followersCount")); - else - account.setFollowers_count(0); - if (resobj.has("followingCount")) - account.setFollowing_count(resobj.getInt("followingCount")); - else - account.setFollowing_count(0); - account.setStatuses_count(0); - if (resobj.has("description")) - account.setNote(resobj.getString("description")); - else - account.setNote(""); - account.setUrl(resobj.getString("url")); - account.setSocial("PEERTUBE"); - if (resobj.has("avatar") && !resobj.getString("avatar").equals("null")) { - account.setAvatar("https://" + instance + resobj.getJSONObject("avatar").get("path")); - account.setAvatar_static("https://" + instance + resobj.getJSONObject("avatar").get("path")); - } else - account.setAvatar(null); - account.setAvatar_static(resobj.getString("avatar")); - } catch (JSONException ignored) { - } catch (ParseException e) { - e.printStackTrace(); - } - return account; - } - - /*** - * Get info on the current Instance *synchronously* - * @return APIResponse - */ - public APIResponse getInstances(InstanceParams instanceParams) { - LinkedHashMap params = new LinkedHashMap<>(); - params.put("start", "0"); - params.put("count", "250"); - params.put("healthy", "true"); - params.put("signup", "true"); - if (instanceParams != null) { - if (instanceParams.getCategoriesOr() != null && instanceParams.getCategoriesOr().size() > 0) { - StringBuilder parameters = new StringBuilder(); - for (int category : instanceParams.getCategoriesOr()) - parameters.append("categoriesOr[]=").append(category).append("&"); - parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1).substring(15)); - params.put("categoriesOr[]", parameters.toString()); - } - - if (instanceParams.getLanguagesOr() != null && instanceParams.getLanguagesOr().size() > 0) { - StringBuilder parameters = new StringBuilder(); - for (String lang : instanceParams.getLanguagesOr()) - parameters.append("languagesOr[]=").append(lang).append("&"); - parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1).substring(14)); - params.put("languagesOr[]", parameters.toString()); - } - params.put("minUserQuota", instanceParams.getMinUserQuota()); - params.put("nsfwPolicy[]", instanceParams.getNsfwPolicy()); - } - - try { - String response = new HttpsConnection(context).get("https://instances.joinpeertube.org/api/v1/instances", 30, params, null); - JSONArray jsonArray = new JSONObject(response).getJSONArray("data"); - List instances = parseInstances(jsonArray); - apiResponse.setInstances(instances); - } catch (HttpsConnection.HttpsConnectionException e) { - e.printStackTrace(); - setError(e.getStatusCode(), e); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - return apiResponse; - } - - /** - * Update video meta data *synchronously* - * - * @param peertube Peertube - * @return APIResponse - */ - @SuppressWarnings("SameParameterValue") - public APIResponse updateVideo(Peertube peertube) { - - LinkedHashMap params = new LinkedHashMap<>(); - - params.put("name", peertube.getName()); - //Category - Map.Entry categoryM = peertube.getCategory().entrySet().iterator().next(); - Integer idCategory = categoryM.getKey(); - params.put("category", String.valueOf(idCategory)); - //License - Map.Entry licenseM = peertube.getLicense().entrySet().iterator().next(); - Integer idLicense = licenseM.getKey(); - params.put("licence", String.valueOf(idLicense)); - //language - Map.Entry languagesM = peertube.getLanguage().entrySet().iterator().next(); - String iDlanguage = languagesM.getKey(); - params.put("language", iDlanguage); - params.put("support", "null"); - params.put("description", peertube.getDescription()); - //Channel - Map.Entry channelsM = peertube.getChannelForUpdate().entrySet().iterator().next(); - String iDChannel = channelsM.getValue(); - params.put("channelId", iDChannel); - //Privacy - Map.Entry privacyM = peertube.getPrivacy().entrySet().iterator().next(); - Integer idPrivacy = privacyM.getKey(); - params.put("privacy", String.valueOf(idPrivacy)); - if (peertube.getTags() != null && peertube.getTags().size() > 0) { - StringBuilder parameters = new StringBuilder(); - parameters.append("[]&"); - for (String tag : peertube.getTags()) - parameters.append("tags=").append(tag).append("&"); - String strParam = parameters.toString(); - strParam = strParam.substring(0, strParam.length() - 1); - params.put("tags[]", strParam); - } else { - params.put("tags", "null"); - } - params.put("nsfw", String.valueOf(peertube.isSensitive())); - params.put("waitTranscoding", "true"); - params.put("commentsEnabled", String.valueOf(peertube.isCommentsEnabled())); - params.put("scheduleUpdate", "null"); - List peertubes = new ArrayList<>(); - try { - HttpsConnection httpsConnection = new HttpsConnection(context); - httpsConnection.put(getAbsoluteUrl(String.format("/videos/%s", peertube.getId())), 60, params, prefKeyOauthTokenT); - peertubes.add(peertube); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - e.printStackTrace(); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException e) { - e.printStackTrace(); - } - apiResponse.setPeertubes(peertubes); - return apiResponse; - } - - /*** - * Verifiy PeertubeInformation of the authenticated user *synchronously* - * @return Account - */ - public PeertubeInformation getPeertubeInformation() throws HttpsConnection.HttpsConnectionException { - PeertubeInformation peertubeInformation = new PeertubeInformation(); - try { - - String response = new HttpsConnection(context).get(getAbsoluteUrl("/videos/categories"), 60, null, null); - JSONObject categories = new JSONObject(response); - LinkedHashMap _pcategories = new LinkedHashMap<>(); - for (int i = 1; i <= categories.length(); i++) { - _pcategories.put(i, categories.getString(String.valueOf(i))); - - } - peertubeInformation.setCategories(_pcategories); - - response = new HttpsConnection(context).get(getAbsoluteUrl("/videos/languages"), 60, null, null); - JSONObject languages = new JSONObject(response); - LinkedHashMap _languages = new LinkedHashMap<>(); - Iterator iter = languages.keys(); - while (iter.hasNext()) { - String key = iter.next(); - try { - _languages.put(key, (String) languages.get(key)); - } catch (JSONException ignored) { - } - } - peertubeInformation.setLanguages(_languages); - - response = new HttpsConnection(context).get(getAbsoluteUrl("/videos/privacies"), 60, null, null); - JSONObject privacies = new JSONObject(response); - LinkedHashMap _pprivacies = new LinkedHashMap<>(); - for (int i = 1; i <= privacies.length(); i++) { - _pprivacies.put(i, privacies.getString(String.valueOf(i))); - - } - peertubeInformation.setPrivacies(_pprivacies); - - - response = new HttpsConnection(context).get(getAbsoluteUrl("/video-playlists/privacies"), 60, null, null); - JSONObject plprivacies = new JSONObject(response); - LinkedHashMap _plprivacies = new LinkedHashMap<>(); - for (int i = 1; i <= plprivacies.length(); i++) { - _plprivacies.put(i, plprivacies.getString(String.valueOf(i))); - - } - peertubeInformation.setPlaylistPrivacies(_plprivacies); - - response = new HttpsConnection(context).get(getAbsoluteUrl("/videos/licences"), 60, null, null); - JSONObject licences = new JSONObject(response); - LinkedHashMap _plicences = new LinkedHashMap<>(); - for (int i = 1; i <= licences.length(); i++) { - _plicences.put(i, licences.getString(String.valueOf(i))); - - } - peertubeInformation.setLicences(_plicences); - - - String instance = Helper.getLiveInstance(context); - String lang = null; - if (PeertubeInformation.langueMapped.containsKey(Locale.getDefault().getLanguage())) - lang = PeertubeInformation.langueMapped.get(Locale.getDefault().getLanguage()); - - if (lang != null) { - response = new HttpsConnection(context).get(String.format("https://" + instance + "/client/locales/%s/server.json", lang), 60, null, null); - JSONObject translations = new JSONObject(response); - LinkedHashMap _translations = new LinkedHashMap<>(); - Iterator itertrans = translations.keys(); - while (itertrans.hasNext()) { - String key = itertrans.next(); - try { - _translations.put(key, (String) translations.get(key)); - } catch (JSONException ignored) { - } - } - peertubeInformation.setTranslations(_translations); - } - - } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - return peertubeInformation; - } - - /** - * Refresh token and update user data - * - * @param token String - * @param instance String - */ - public void refreshToken(String token, String instance) { - - SQLiteDatabase db = Sqlite.getInstance(context.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - if (token == null) { - final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - String instanceC = Helper.getLiveInstance(context); - Account accountToLogout = new AccountDAO(context, db).getUniqAccount(userId, instanceC); - Helper.logoutCurrentUser((Activity) context, accountToLogout); - return; - } - - Account targetedAccount = new AccountDAO(context, db).getAccountByToken(token); - String newToken = null, newRefreshToken = null; - if (targetedAccount != null) { - HashMap values = refreshToken(targetedAccount.getClient_id(), targetedAccount.getClient_secret(), targetedAccount.getRefresh_token()); - if (values.containsKey("access_token") && values.get("access_token") != null) { - SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - //This account is currently logged in, the token is updated - if (values.get("access_token") != null) { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, values.get("access_token")); - editor.apply(); - } - } - if (values.containsKey("refresh_token") && values.get("refresh_token") != null) { - newRefreshToken = values.get("refresh_token"); - } - if (values.containsKey("access_token") && values.get("access_token") != null) { - newToken = values.get("access_token"); - } - String response; - try { - response = new HttpsConnection(context).get("https://" + instance + "/api/v1/users/me", 60, null, newToken); - JSONObject accountObject = new JSONObject(response).getJSONObject("account"); - account = parseAccountResponsePeertube(accountObject); - } catch (IOException | NoSuchAlgorithmException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } catch (HttpsConnection.HttpsConnectionException e) { - e.printStackTrace(); - //setError(e.getStatusCode(), e); - final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - String instanceC = Helper.getLiveInstance(context); - Account accountToLogout = new AccountDAO(context, db).getUniqAccount(userId, instanceC); - Helper.logoutCurrentUser((Activity) context, accountToLogout); - return; - } - if (newRefreshToken != null && newToken != null) { - account.setRefresh_token(newRefreshToken); - account.setToken(newToken); - } - account.setInstance(instance); - new AccountDAO(context, db).updateAccount(account); - } - } - - /*** - * Verifiy credential of the authenticated user *synchronously* - * @return Account - */ - public Account verifyCredentials(String token, String instance) { - account = new Account(); - try { - String response = new HttpsConnection(context).get("https://" + instance + "/api/v1/users/me", 60, null, token); - JSONObject accountObject = new JSONObject(response).getJSONObject("account"); - account = parseAccountResponsePeertube(accountObject); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - } - return account; - } - - public int report(reportType type, String id, String reason) { - actionCode = -1; - try { - HashMap params = new HashMap<>(); - switch (type) { - case VIDEO: - params.put("video", id); - break; - case ACCOUNT: - params.put("account", id); - break; - case COMMENT: - params.put("comment", id); - break; - } - params.put("reason", reason); - HttpsConnection httpsConnection = new HttpsConnection(context); - httpsConnection.post(getAbsoluteUrl("/abuses"), 30, params, null); - actionCode = httpsConnection.getActionCode(); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException e) { - e.printStackTrace(); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - e.printStackTrace(); - } - return actionCode; - } - - public APIResponse createAccount(AccountCreation accountCreation) { - apiResponse = new APIResponse(); - - try { - HashMap params = new HashMap<>(); - params.put("username", accountCreation.getUsername()); - params.put("email", accountCreation.getEmail()); - params.put("password", accountCreation.getPassword()); - new HttpsConnection(context).post(getAbsoluteUrlForInstance(accountCreation.getInstance(), "/users/register"), 30, params, null); - apiResponse.setStringData(accountCreation.getEmail()); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException e) { - e.printStackTrace(); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - e.printStackTrace(); - } - return apiResponse; - } - - /** - * Create a channel fot the authenticated user - * - * @param channelCreation channelCreation - */ - public void createChannel(ChannelCreation channelCreation) throws HttpsConnection.HttpsConnectionException { - actionCode = -1; - try { - HashMap params = new HashMap<>(); - params.put("displayName", channelCreation.getDisplayName()); - params.put("name", channelCreation.getName()); - params.put("description", channelCreation.getDescription()); - params.put("support", channelCreation.getSupport()); - HttpsConnection httpsConnection = new HttpsConnection(context); - httpsConnection.post(getAbsoluteUrl("/video-channels"), 30, params, prefKeyOauthTokenT); - actionCode = httpsConnection.getActionCode(); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException e) { - e.printStackTrace(); - } - } - - /** - * Update a channel fot the authenticated user - * - * @param acct String - * @param channelCreation ChannelCreation - */ - public void updateChannel(String acct, ChannelCreation channelCreation) throws HttpsConnection.HttpsConnectionException { - actionCode = -1; - try { - HashMap params = new HashMap<>(); - params.put("displayName", channelCreation.getDisplayName()); - params.put("name", channelCreation.getName()); - params.put("description", channelCreation.getDescription()); - params.put("support", channelCreation.getSupport()); - HttpsConnection httpsConnection = new HttpsConnection(context); - httpsConnection.put(getAbsoluteUrl(String.format("/video-channels/%s", acct)), 30, params, prefKeyOauthTokenT); - actionCode = httpsConnection.getActionCode(); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException e) { - e.printStackTrace(); - } - } - - /** - * Delete a Channel - * - * @param channelId String, the channel id - */ - public void deleteChannel(String channelId) throws HttpsConnection.HttpsConnectionException { - try { - HttpsConnection httpsConnection = new HttpsConnection(context); - httpsConnection.delete(getAbsoluteUrl(String.format("/video-channels/%s", channelId)), 60, null, prefKeyOauthTokenT); - actionCode = httpsConnection.getActionCode(); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException e) { - e.printStackTrace(); - } - } - - - /*** - * Verifiy credential of the authenticated user *synchronously* - * @return Account - */ - private HashMap refreshToken(String client_id, String client_secret, String refresh_token) { - account = new Account(); - HashMap params = new HashMap<>(); - HashMap newValues = new HashMap<>(); - params.put("grant_type", "refresh_token"); - params.put("client_id", client_id); - params.put("client_secret", client_secret); - params.put("refresh_token", refresh_token); - try { - String response = new HttpsConnection(context).post(getAbsoluteUrl("/users/token"), 60, params, null); - JSONObject resobj = new JSONObject(response); - String token = resobj.getString("access_token"); - String refresh = resobj.getString("refresh_token"); - newValues.put("access_token", token); - newValues.put("refresh_token", refresh); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - e.printStackTrace(); - } - return newValues; - } - - - /** - * Find captions for a video - * - * @param videoId String id of the video - * @return APIResponse - */ - public APIResponse getCaptions(String videoId) { - - apiResponse = new APIResponse(); - try { - String response = new HttpsConnection(context).get(getAbsoluteUrl(String.format("/videos/%s/captions", videoId)), 60, null, prefKeyOauthTokenT); - JSONArray jsonArray = new JSONObject(response).getJSONArray("data"); - List captions = parseCaption(jsonArray); - apiResponse.setCaptions(captions); - } catch (HttpsConnection.HttpsConnectionException e) { - e.printStackTrace(); - setError(e.getStatusCode(), e); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - return apiResponse; - } - - - /** - * Returns an account - * - * @param accountId String account fetched - * @return Account entity - */ - @SuppressWarnings({"unused", "RedundantSuppression"}) - public Account getAccount(String accountId) { - - account = new Account(); - try { - String response = new HttpsConnection(context).get(getAbsoluteUrl(String.format("/accounts/%s", accountId)), 60, null, prefKeyOauthTokenT); - account = parseAccountResponsePeertube(new JSONObject(response)); - } catch (HttpsConnection.HttpsConnectionException e) { - e.printStackTrace(); - setError(e.getStatusCode(), e); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - return account; - } - - - public List isFollowing(String uri) { - ArrayList uris = new ArrayList<>(); - uris.add(uri); - return isFollowing(uris); - } - - /** - * Returns a relationship between the authenticated account and an account - * - * @param uris Array String accounts uri fetched - * @return Relationship entity - */ - public List isFollowing(ArrayList uris) { - HashMap params = new HashMap<>(); - StringBuilder parameters = new StringBuilder(); - for (String uri : uris) - parameters.append("uris[]=").append(uri).append("&"); - parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1).substring(7)); - params.put("uris[]", parameters.toString()); - - try { - HttpsConnection httpsConnection = new HttpsConnection(context); - String response = httpsConnection.get(getAbsoluteUrl("/users/me/subscriptions/exist"), 60, params, prefKeyOauthTokenT); - return parseRelationShip(uris, new JSONObject(response)); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - return null; - } - - /** - * Retrieves videos for the account *synchronously* - * - * @param acct String Id of the account - * @param max_id String id max - * @return APIResponse - */ - public APIResponse getVideos(String acct, String max_id) { - return getVideos(acct, max_id, null); - } - - /** - * Retrieves history for videos for the account *synchronously* - * - * @param max_id String id max - * @return APIResponse - */ - public APIResponse getMyHistory(String max_id) { - return getMyHistory(max_id, null); - } - - /** - * Retrieves history for videos for the account *synchronously* - * - * @param max_id String id max - * @param since_id String since the id - * @return APIResponse - */ - @SuppressWarnings("SameParameterValue") - private APIResponse getMyHistory(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)); - List peertubes = new ArrayList<>(); - try { - - HttpsConnection httpsConnection = new HttpsConnection(context); - String response = httpsConnection.get(getAbsoluteUrl("/users/me/history/videos"), 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 | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - apiResponse.setPeertubes(peertubes); - return apiResponse; - } - - /** - * Retrieves videos for the account *synchronously* - * - * @param max_id String id max - * @return APIResponse - */ - public APIResponse getMyVideos(String max_id) { - return getMyVideos(max_id, null); - } - - /** - * Retrieves status for the account *synchronously* - * - * @param max_id String id max - * @param since_id String since the id - * @return APIResponse - */ - @SuppressWarnings("SameParameterValue") - private APIResponse getMyVideos(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)); - List peertubes = new ArrayList<>(); - try { - - HttpsConnection httpsConnection = new HttpsConnection(context); - String response = httpsConnection.get(getAbsoluteUrl("/users/me/videos"), 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 | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - apiResponse.setPeertubes(peertubes); - return apiResponse; - } - - /** - * Retrieves status for the account *synchronously* - * - * @param acct String Id of the account - * @param max_id String id max - * @param since_id String since the id - * @return APIResponse - */ - @SuppressWarnings("SameParameterValue") - private APIResponse getVideos(String acct, 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)); - List peertubes = new ArrayList<>(); - try { - HttpsConnection httpsConnection = new HttpsConnection(context); - String response = httpsConnection.get(getAbsoluteUrl(String.format("/accounts/%s/videos", acct)), 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 | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - apiResponse.setPeertubes(peertubes); - return apiResponse; - } - - /** - * Retrieves Peertube notifications for the account *synchronously* - * - * @param max_id String id max - * @return APIResponse - */ - public APIResponse getNotifications(String max_id) { - return getNotifications(max_id, null); - } - - /** - * Retrieves Peertube notifications since id for the account *synchronously* - * - * @param since_id String id since - * @return APIResponse - */ - public APIResponse getNotificationsSince(String since_id) { - return getNotifications(null, since_id); - } - - /** - * Retrieves Peertube notifications for the account *synchronously* - * - * @param max_id String id max - * @param since_id String since the id - * @return APIResponse - */ - @SuppressWarnings("SameParameterValue") - private APIResponse getNotifications(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)); - List peertubeNotifications = new ArrayList<>(); - try { - HttpsConnection httpsConnection = new HttpsConnection(context); - String response = httpsConnection.get(getAbsoluteUrl("/users/me/notifications"), 60, params, prefKeyOauthTokenT); - JSONArray jsonArray = new JSONObject(response).getJSONArray("data"); - peertubeNotifications = parsePeertubeNotifications(jsonArray); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - e.printStackTrace(); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - apiResponse.setPeertubeNotifications(peertubeNotifications); - return apiResponse; - } - - /** - * Retrieves videos channel for the account *synchronously* - * - * @param acct String Id of the account - * @param max_id String id max - * @return APIResponse - */ - public APIResponse getVideosChannel(String acct, String max_id) { - return getVideosChannel(acct, max_id, null); - } - - /** - * Retrieves status for the account *synchronously* - * - * @param acct String Id of the account - * @param max_id String id max - * @param since_id String since the id - * @return APIResponse - */ - @SuppressWarnings("SameParameterValue") - private APIResponse getVideosChannel(String acct, 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)); - List peertubes = new ArrayList<>(); - try { - - HttpsConnection httpsConnection = new HttpsConnection(context); - String response = httpsConnection.get(getAbsoluteUrl(String.format("/video-channels/%s/videos", acct)), 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 | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - apiResponse.setPeertubes(peertubes); - return apiResponse; - } - - /** - * Retrieves subscription videos *synchronously* - * - * @param max_id String id max - * @return APIResponse - */ - public APIResponse getSubscriptionsTL(String max_id) { - try { - return getTL(true, "/users/me/subscriptions/videos", "-publishedAt", null, max_id, null, null); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - return apiResponse; - } - } - - /** - * Retrieves subscriptions *synchronously* - * - * @param max_id String id max - * @return APIResponse - */ - public APIResponse getSubscriptionUsers(String max_id) { - List accounts = new ArrayList<>(); - try { - HttpsConnection httpsConnection = new HttpsConnection(context); - HashMap params = new HashMap<>(); - if (max_id != null) - params.put("start", max_id); - params.put("sort", "-createdAt"); - String response = httpsConnection.get(getAbsoluteUrl("/users/me/subscriptions"), 10, params, prefKeyOauthTokenT); - JSONArray jsonArray = new JSONObject(response).getJSONArray("data"); - accounts = parseAccountResponsePeertube(jsonArray); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - e.printStackTrace(); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - apiResponse.setAccounts(accounts); - return apiResponse; - } - - /** - * Retrieves muted accounts *synchronously* - * - * @param max_id String id max - * @return APIResponse - */ - public APIResponse getMuted(String max_id) { - List accounts = new ArrayList<>(); - try { - HttpsConnection httpsConnection = new HttpsConnection(context); - HashMap params = new HashMap<>(); - if (max_id != null) - params.put("start", max_id); - params.put("sort", "-createdAt"); - String response = httpsConnection.get(getAbsoluteUrl("/users/me/blocklist/accounts"), 10, params, prefKeyOauthTokenT); - JSONArray jsonArray = new JSONObject(response).getJSONArray("data"); - accounts = parseBlockedAccountResponsePeertube(jsonArray); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - e.printStackTrace(); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - apiResponse.setAccounts(accounts); - return apiResponse; - } - - /** - * Retrieves overview videos *synchronously* - * - * @param max_id String id max - * @return APIResponse - */ - public APIResponse getOverviewTL(String max_id) { - try { - return getTL(false, "/overviews/videos", null, null, max_id, null, null); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - return apiResponse; - } - } - - /** - * Retrieves most likded videos *synchronously* - * - * @param max_id String id max - * @return APIResponse - */ - public APIResponse getLikedTL(String max_id) { - try { - return getTL(false, "/videos/", "-likes", null, max_id, null, null); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - return apiResponse; - } - } - - /** - * Retrieves trending videos *synchronously* - * - * @param max_id String id max - * @return APIResponse - */ - public APIResponse getTrendingTL(String max_id) { - try { - return getTL(false, "/videos/", "-trending", null, max_id, null, null); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - return apiResponse; - } - } - - /** - * Retrieves trending videos *synchronously* - * - * @param max_id String id max - * @return APIResponse - */ - public APIResponse getRecentlyAddedTL(String max_id) { - try { - return getTL(false, "/videos/", "-publishedAt", null, max_id, null, null); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - return apiResponse; - } - } - - /** - * Retrieves local videos *synchronously* - * - * @param max_id String id max - * @return APIResponse - */ - public APIResponse getLocalTL(String max_id) { - try { - return getTL(true, "/videos/", "-publishedAt", "local", max_id, null, null); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - return apiResponse; - } - } - - /** - * Retrieves public videos *synchronously* - * - * @param max_id String id max - * @return APIResponse - */ - public APIResponse getPublicTL(String max_id) { - try { - return getTL(false, "/videos/", "-publishedAt", null, max_id, null, null); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - return apiResponse; - } - } - - /** - * Retrieves home timeline for the account *synchronously* - * - * @param max_id String id max - * @param since_id String since the id - * @return APIResponse - */ - @SuppressWarnings("SameParameterValue") - private APIResponse getTL(boolean needToken, String action, String sort, String filter, String max_id, String since_id, String min_id) throws HttpsConnection.HttpsConnectionException { - - HashMap params = new HashMap<>(); - if (max_id != null) - params.put("start", max_id); - if (since_id != null) - params.put("since_id", since_id); - if (min_id != null) - params.put("min_id", min_id); - params.put("count", String.valueOf(tootPerPage)); - if (sort != null) - params.put("sort", sort); - else - params.put("sort", "publishedAt"); - if (filter != null) - params.put("filter", filter); - - SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - Set selection = sharedpreferences.getStringSet(context.getString(R.string.set_video_language_choice), null); - if (selection != null && selection.size() > 0) { - StringBuilder parameters = new StringBuilder(); - for (String languageOneOf : selection) - parameters.append("languageOneOf[]=").append(languageOneOf).append("&"); - parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1).substring(16)); - params.put("languageOneOf[]", parameters.toString()); - } - boolean nsfw = sharedpreferences.getBoolean(Helper.SET_VIDEO_NSFW, false); - params.put("nsfw", String.valueOf(nsfw)); - List peertubes = new ArrayList<>(); - try { - HttpsConnection httpsConnection = new HttpsConnection(context); - String response = httpsConnection.get(getAbsoluteUrl(action), 60, params, needToken ? prefKeyOauthTokenT : null); - if (!action.equals("/overviews/videos")) { - JSONArray values = new JSONObject(response).getJSONArray("data"); - peertubes = parsePeertube(values); - } else { - JSONArray categories = new JSONObject(response).getJSONArray("categories"); - JSONArray channels = new JSONObject(response).getJSONArray("channels"); - JSONArray tags = new JSONObject(response).getJSONArray("tags"); - - for (int i = 0; i < categories.length(); i++) { - JSONArray categoriesVideos = categories.getJSONObject(i).getJSONArray("videos"); - List peertubeCategories = parsePeertube(categoriesVideos); - if (peertubeCategories.size() > 0) { - peertubeCategories.get(0).setHeaderType("categories"); - peertubeCategories.get(0).setHeaderTypeValue(categories.getJSONObject(i).getJSONObject("category").getString("label")); - peertubes.addAll(peertubeCategories); - } - } - - - for (int i = 0; i < channels.length(); i++) { - JSONArray channelsVideos = channels.getJSONObject(i).getJSONArray("videos"); - List peertubeChannels = parsePeertube(channelsVideos); - if (peertubeChannels.size() > 0) { - peertubeChannels.get(0).setHeaderType("channels"); - peertubeChannels.get(0).setHeaderTypeValue(channels.getJSONObject(i).getJSONObject("channel").getString("displayName")); - peertubes.addAll(peertubeChannels); - } - } - - for (int i = 0; i < tags.length(); i++) { - JSONArray tagsVideos = tags.getJSONObject(i).getJSONArray("videos"); - List peertubeTags = parsePeertube(tagsVideos); - if (peertubeTags.size() > 0) { - peertubeTags.get(0).setHeaderType("tags"); - peertubeTags.get(0).setHeaderTypeValue(tags.getJSONObject(i).getString("tag")); - peertubes.addAll(peertubeTags); - } - } - - - } - } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - apiResponse.setPeertubes(peertubes); - return apiResponse; - } - - /** - * Retrieves Peertube channel from an account *synchronously* - * Peertube channels are dealt like accounts - * - * @return APIResponse - */ - public APIResponse getPeertubeChannel(String name) { - - List accounts = new ArrayList<>(); - try { - HttpsConnection httpsConnection = new HttpsConnection(context); - String response = httpsConnection.get(getAbsoluteUrl(String.format("/accounts/%s/video-channels", name)), 60, null, null); - JSONArray jsonArray = new JSONObject(response).getJSONArray("data"); - accounts = parseAccountResponsePeertube(jsonArray); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - apiResponse.setAccounts(accounts); - return apiResponse; - } - - /** - * Retrieves Peertube channel info from an account *synchronously* - * Peertube channels are dealt like accounts - * - * @return APIResponse - */ - public APIResponse getPeertubeChannelInfo(String name) { - - List accounts = new ArrayList<>(); - try { - HttpsConnection httpsConnection = new HttpsConnection(context); - String response = httpsConnection.get(getAbsoluteUrl(String.format("/video-channels/%s", name)), 60, null, null); - JSONObject jsonObject = new JSONObject(response); - Account account = parseAccountResponsePeertube(jsonObject); - accounts.add(account); - } catch (HttpsConnection.HttpsConnectionException e) { - e.printStackTrace(); - setError(e.getStatusCode(), e); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - apiResponse.setAccounts(accounts); - return apiResponse; - } - - - /** - * Retrieves Peertube videos from an instance *synchronously* - * - * @return APIResponse - */ - public APIResponse getSinglePeertube(String instance, String videoId, String token) { - - Peertube peertube = null; - try { - HttpsConnection httpsConnection = new HttpsConnection(context); - String response = httpsConnection.get(String.format("https://" + instance + "/api/v1/videos/%s", videoId), 60, null, token); - JSONObject jsonObject = new JSONObject(response); - peertube = parseSinglePeertube(instance, jsonObject); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - List peertubes = new ArrayList<>(); - peertubes.add(peertube); - apiResponse.setPeertubes(peertubes); - return apiResponse; - } - - /** - * Retrieves rating of user on a video *synchronously* - * - * @param id String id - * @return APIResponse - */ - @SuppressWarnings("SameParameterValue") - public String getRating(String id) { - try { - HttpsConnection httpsConnection = new HttpsConnection(context); - String response = httpsConnection.get(getAbsoluteUrl(String.format("/users/me/videos/%s/rating", id)), 60, null, prefKeyOauthTokenT); - return new JSONObject(response).getString("rating"); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - return null; - } - - /** - * Makes the post action for a status - * - * @param statusAction Enum - * @param targetedId String id of the targeted Id *can be this of a status or an account* - * @return in status code - Should be equal to 200 when action is done - */ - public int postAction(StatusAction statusAction, String targetedId) { - return postAction(statusAction, targetedId, null, null); - } - - public int postRating(String targetedId, String actionMore) { - return postAction(StatusAction.RATEVIDEO, targetedId, actionMore, null); - } - - public int postComment(String targetedId, String actionMore) { - return postAction(StatusAction.PEERTUBECOMMENT, targetedId, actionMore, null); - } - - public int postReply(String targetedId, String actionMore, String targetedComment) { - return postAction(StatusAction.PEERTUBEREPLY, targetedId, actionMore, targetedComment); - } - - public int deleteComment(String targetedId, String targetedComment) { - return postAction(StatusAction.PEERTUBEDELETECOMMENT, targetedId, null, targetedComment); - } - - public int deleteVideo(String targetedId) { - return postAction(StatusAction.PEERTUBEDELETEVIDEO, targetedId, null, null); - } - - /** - * Makes the post action - * - * @param statusAction Enum - * @param targetedId String id of the targeted Id *can be this of a status or an account* - * @param actionMore String another action - * @param targetedComment String another action - * @return in status code - Should be equal to 200 when action is done - */ - private int postAction(StatusAction statusAction, String targetedId, String actionMore, String targetedComment) { - - String action; - String actionCall = "POST"; - HashMap params = null; - switch (statusAction) { - case FOLLOW: - action = "/users/me/subscriptions"; - params = new HashMap<>(); - params.put("uri", targetedId); - break; - case UNFOLLOW: - action = String.format("/users/me/subscriptions/%s", targetedId); - actionCall = "DELETE"; - break; - case MUTE: - action = "/users/me/blocklist/accounts"; - params = new HashMap<>(); - params.put("accountName", targetedId); - break; - case UNMUTE: - action = String.format("/users/me/blocklist/accounts/%s", targetedId); - actionCall = "DELETE"; - break; - case RATEVIDEO: - action = String.format("/videos/%s/rate", targetedId); - params = new HashMap<>(); - params.put("rating", actionMore); - actionCall = "PUT"; - break; - case PEERTUBECOMMENT: - action = String.format("/videos/%s/comment-threads", targetedId); - params = new HashMap<>(); - params.put("text", actionMore); - break; - case PEERTUBEDELETECOMMENT: - action = String.format("/videos/%s/comments/%s", targetedId, targetedComment); - actionCall = "DELETE"; - break; - case PEERTUBEDELETEVIDEO: - action = String.format("/videos/%s", targetedId); - actionCall = "DELETE"; - break; - case PEERTUBEREPLY: - action = String.format("/videos/%s/comment/%s", targetedId, targetedComment); - params = new HashMap<>(); - params.put("text", actionMore); - break; - default: - return -1; - } - try { - HttpsConnection httpsConnection = new HttpsConnection(context); - switch (actionCall) { - case "POST": - httpsConnection.post(getAbsoluteUrl(action), 60, params, prefKeyOauthTokenT); - break; - case "DELETE": - httpsConnection.delete(getAbsoluteUrl(action), 60, null, prefKeyOauthTokenT); - break; - default: - httpsConnection.put(getAbsoluteUrl(action), 60, params, prefKeyOauthTokenT); - break; - } - actionCode = httpsConnection.getActionCode(); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - e.printStackTrace(); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException e) { - e.printStackTrace(); - } - return actionCode; - } - - /** - * Video is in play lists - * - * @return APIResponse - */ - public APIResponse getPlaylistForVideo(String videoId) { - - HashMap params = new HashMap<>(); - params.put("videoIds", videoId); - List ids = new ArrayList<>(); - try { - String response = new HttpsConnection(context).get(getAbsoluteUrl("/users/me/video-playlists/videos-exist"), 60, params, prefKeyOauthTokenT); - JSONArray jsonArray = new JSONObject(response).getJSONArray(videoId); - try { - int i = 0; - while (i < jsonArray.length()) { - PlaylistElement playlistElement = new PlaylistElement(); - JSONObject resobj = jsonArray.getJSONObject(i); - playlistElement.setPlaylistId(resobj.getString("playlistId")); - playlistElement.setPlaylistElementId(resobj.getString("playlistElementId")); - ids.add(playlistElement); - i++; - } - } catch (JSONException e) { - setDefaultError(e); - } - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - e.printStackTrace(); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - apiResponse = new APIResponse(); - apiResponse.setPlaylistForVideos(ids); - return apiResponse; - } - - /** - * Get lists for the user - * - * @return APIResponse - */ - public APIResponse getPlayists(String username) { - - List playlists = new ArrayList<>(); - try { - String response = new HttpsConnection(context).get(getAbsoluteUrl(String.format("/accounts/%s/video-playlists", username)), 60, null, prefKeyOauthTokenT); - playlists = parsePlaylists(context, new JSONObject(response).getJSONArray("data")); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - e.printStackTrace(); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - apiResponse.setPlaylists(playlists); - return apiResponse; - } - - - /** - * Create a Playlist - * - * @param playlistElement PlaylistElement, the playlist elements - */ - public String createPlaylist(PlaylistElement playlistElement) throws HttpsConnection.HttpsConnectionException { - String playlistId = "-1"; - try { - HttpsConnection httpsConnection = new HttpsConnection(context); - LinkedHashMap params = new LinkedHashMap<>(); - params.put("displayName", playlistElement.getDisplayName()); - params.put("privacy", playlistElement.getPrivacy()); - params.put("videoChannelId", playlistElement.getVideoChannelId()); - params.put("description", playlistElement.getDescription()); - String response = httpsConnection.postBoundary(HttpsConnection.boundaryType.POST, getAbsoluteUrl("/video-playlists/"), 60, params, prefKeyOauthTokenT); - playlistId = new JSONObject(response).getJSONObject("videoPlaylist").getString("id"); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - return playlistId; - } - - /** - * Update a Playlist - * - * @param playlistElement PlaylistElement, the playlist elements - */ - public void updatePlaylist(PlaylistElement playlistElement) throws HttpsConnection.HttpsConnectionException { - try { - HttpsConnection httpsConnection = new HttpsConnection(context); - LinkedHashMap params = new LinkedHashMap<>(); - params.put("displayName", playlistElement.getDisplayName()); - params.put("privacy", playlistElement.getPrivacy()); - params.put("videoChannelId", playlistElement.getVideoChannelId()); - params.put("description", playlistElement.getDescription()); - httpsConnection.postBoundary(HttpsConnection.boundaryType.PUT, getAbsoluteUrl(String.format("/video-playlists/%s", playlistElement.getPlaylistId())), 60, params, prefKeyOauthTokenT); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException e) { - e.printStackTrace(); - } - } - - - /** - * Delete a Playlist - * - * @param playlistId String, the playlist id - * @return int - */ - public int deletePlaylist(String playlistId) { - try { - HttpsConnection httpsConnection = new HttpsConnection(context); - 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 | IOException | KeyManagementException e) { - e.printStackTrace(); - } - return actionCode; - } - - /** - * 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); - 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); - e.printStackTrace(); - } catch (NoSuchAlgorithmException | IOException | 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); - 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); - e.printStackTrace(); - } catch (NoSuchAlgorithmException | KeyManagementException | IOException 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); - 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 | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - apiResponse.setPeertubes(peertubes); - return apiResponse; - } - - /** - * Retrieves Peertube videos from an instance *synchronously* - * - * @return APIResponse - */ - public APIResponse getSinglePeertubeComments(String instance, String videoId) { - List statuses = new ArrayList<>(); - try { - HttpsConnection httpsConnection = new HttpsConnection(context); - String response = httpsConnection.get(String.format("https://" + instance + "/api/v1/videos/%s/comment-threads", videoId), 10, null, null); - JSONObject jsonObject = new JSONObject(response); - statuses = parseSinglePeertubeComments(instance, jsonObject); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - apiResponse.setStatuses(statuses); - return apiResponse; - } - - /** - * Retrieves peertube search *synchronously* - * - * @param query String search - * @return APIResponse - */ - public APIResponse searchPeertube(String query, String max_id) { - HashMap params = new HashMap<>(); - params.put("count", "50"); - if (max_id != null) - params.put("start", max_id); - if (query == null) - return null; - try { - params.put("search", URLEncoder.encode(query, "UTF-8")); - } catch (UnsupportedEncodingException e) { - params.put("search", query); - } - - List peertubes = new ArrayList<>(); - try { - HttpsConnection httpsConnection = new HttpsConnection(context); - String response = httpsConnection.get("https://" + instance + "/api/v1/search/videos", 10, params, null); - JSONArray jsonArray = new JSONObject(response).getJSONArray("data"); - peertubes = parsePeertube(jsonArray); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - e.printStackTrace(); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - apiResponse.setPeertubes(peertubes); - return apiResponse; - } - - /** - * Parse json response for peertube relationship - * - * @param jsonObject JSONObject - * @return List - */ - private List parseRelationShip(ArrayList uris, JSONObject jsonObject) { - List relationships = new ArrayList<>(); - try { - for (String uri : uris) { - Relationship relationship = new Relationship(); - relationship.setId(uri); - relationship.setFollowing(jsonObject.getBoolean(uri)); - relationships.add(relationship); - } - return relationships; - } catch (JSONException e) { - setDefaultError(e); - } - return null; - } - - /** - * Parse json response for peertube notifications - * - * @param jsonArray JSONArray - * @return List - */ - private List parsePeertubeNotifications(JSONArray jsonArray) { - List peertubeNotifications = new ArrayList<>(); - try { - int i = 0; - while (i < jsonArray.length()) { - JSONObject resobj = jsonArray.getJSONObject(i); - PeertubeNotification peertubeNotification = parsePeertubeNotifications(resobj); - i++; - peertubeNotifications.add(peertubeNotification); - } - } catch (JSONException e) { - setDefaultError(e); - } - return peertubeNotifications; - } - - /** - * Parse json response for several howto - * - * @param jsonArray JSONArray - * @return List - */ - private List parsePeertube(JSONArray jsonArray) { - - List peertubes = new ArrayList<>(); - try { - int i = 0; - while (i < jsonArray.length()) { - JSONObject resobj = jsonArray.getJSONObject(i); - Peertube peertube = parsePeertube(resobj); - i++; - if (!BuildConfig.google_restriction || (peertube != null && (peertube.getName() == null || !peertube.getName().toLowerCase().contains("youtube video downloader")))) { - peertubes.add(peertube); - } - } - } catch (JSONException e) { - setDefaultError(e); - } - return peertubes; - } - - - /** - * Parse json response for captions - * - * @param jsonArray JSONArray - * @return List - */ - private List parseCaption(JSONArray jsonArray) { - - List captions = new ArrayList<>(); - try { - int i = 0; - while (i < jsonArray.length()) { - JSONObject resobj = jsonArray.getJSONObject(i); - Caption caption = parseCaption(resobj); - captions.add(caption); - i++; - } - } catch (JSONException e) { - setDefaultError(e); - } - return captions; - } - - private Caption parseCaption(JSONObject resobj) { - Caption caption = new Caption(); - try { - caption.setCaptionPath(resobj.getString("captionPath")); - if (resobj.has("language")) { - JSONObject resobjLang = resobj.getJSONObject("language"); - HashMap language = new HashMap<>(); - language.put(resobjLang.getString("id"), resobjLang.getString("label")); - caption.setLanguage(language); - } - } catch (JSONException e) { - e.printStackTrace(); - } - return caption; - } - - - /** - * Parse json array response for instances - * - * @param jsonArray JSONArray - * @return List - */ - private List parseInstances(JSONArray jsonArray) { - List instances = new ArrayList<>(); - try { - int i = 0; - while (i < jsonArray.length()) { - JSONObject resobj = jsonArray.getJSONObject(i); - Instance instance = parseInstance(resobj); - i++; - instances.add(instance); - } - } catch (JSONException e) { - setDefaultError(e); - } - return instances; - } - - - /** - * Parse json response an unique instance - * - * @param resobj JSONObject - * @return Instance - */ - private Instance parseInstance(JSONObject resobj) { - - Instance instance = new Instance(); - try { - instance.setAutoBlacklistUserVideosEnabled(resobj.getBoolean("autoBlacklistUserVideosEnabled")); - if (resobj.has("categories")) { - JSONArray jsonArray = resobj.getJSONArray("categories"); - LinkedHashMap categories = new LinkedHashMap<>(); - int i = 0; - while (i < jsonArray.length()) { - categories.put(i, jsonArray.getInt(i)); - i++; - } - instance.setCategories(categories); - } - instance.setCountry(resobj.getString("country")); - instance.setCreatedAt(Helper.stringToDate(context, resobj.getString("createdAt"))); - instance.setDefaultNSFWPolicy(resobj.getString("defaultNSFWPolicy")); - instance.setHealth(resobj.getInt("health")); - instance.setId(resobj.getString("id")); - instance.setHost(resobj.getString("host")); - instance.setName(resobj.getString("name")); - instance.setVersion(resobj.getString("version")); - instance.setShortDescription(resobj.getString("shortDescription")); - if (resobj.has("isNSFW")) { - instance.setNSFW(resobj.getBoolean("isNSFW")); - } else { - instance.setNSFW(false); - } - instance.setSignupAllowed(resobj.getBoolean("signupAllowed")); - instance.setSupportsIPv6(resobj.getBoolean("supportsIPv6")); - instance.setTotalInstanceFollowers(resobj.getInt("totalInstanceFollowers")); - - instance.setTotalInstanceFollowing(resobj.getInt("totalInstanceFollowing")); - instance.setTotalLocalVideos(resobj.getInt("totalLocalVideos")); - instance.setTotalUsers(resobj.getInt("totalUsers")); - instance.setTotalVideos(resobj.getInt("totalVideos")); - instance.setUserVideoQuota(resobj.getString("userVideoQuota")); - - if (resobj.has("languages")) { - JSONArray jsonArray = resobj.getJSONArray("languages"); - LinkedHashMap languages = new LinkedHashMap<>(); - int i = 0; - while (i < jsonArray.length()) { - languages.put(i, jsonArray.getString(i)); - i++; - } - instance.setLanguages(languages); - } - - } catch (JSONException e) { - setDefaultError(e); - } - return instance; - } - - /** - * Parse Playlists - * - * @param jsonArray JSONArray - * @return List of lists - */ - private List parsePlaylists(Context context, JSONArray jsonArray) { - List playlists = new ArrayList<>(); - try { - int i = 0; - while (i < jsonArray.length()) { - JSONObject resobj = jsonArray.getJSONObject(i); - Playlist playlist = parsePlaylist(context, resobj); - playlists.add(playlist); - i++; - } - } catch (JSONException e) { - setDefaultError(e); - } - return playlists; - } - - - private List parseBlockedAccountResponsePeertube(JSONArray jsonArray) { - List accounts = new ArrayList<>(); - try { - int i = 0; - while (i < jsonArray.length()) { - if (jsonArray.getJSONObject(i).has("blockedAccount")) { - JSONObject resobj = jsonArray.getJSONObject(i).getJSONObject("blockedAccount"); - Account account = parseAccountResponsePeertube(resobj); - accounts.add(account); - } - i++; - } - } catch (JSONException e) { - setDefaultError(e); - } - return accounts; - } - - private List parseAccountResponsePeertube(JSONArray jsonArray) { - List accounts = new ArrayList<>(); - try { - int i = 0; - while (i < jsonArray.length()) { - JSONObject resobj = jsonArray.getJSONObject(i); - Account account = parseAccountResponsePeertube(resobj); - accounts.add(account); - i++; - } - } catch (JSONException e) { - setDefaultError(e); - } - return accounts; - } - - public InstanceNodeInfo displayNodeInfo(String domain) { - if (domain == null) { - return null; - } - String response; - InstanceNodeInfo instanceNodeInfo = new InstanceNodeInfo(); - if (domain.startsWith("http://")) { - domain = domain.replace("http://", ""); - } - if (domain.startsWith("https://")) { - domain = domain.replace("https://", ""); - } - try { - response = new HttpsConnection(context).get("https://" + domain + "/.well-known/nodeinfo", 30, null, null); - JSONArray jsonArray = new JSONObject(response).getJSONArray("links"); - ArrayList nodeInfos = new ArrayList<>(); - try { - int i = 0; - while (i < jsonArray.length()) { - - JSONObject resobj = jsonArray.getJSONObject(i); - NodeInfo nodeInfo = new NodeInfo(); - nodeInfo.setHref(resobj.getString("href")); - nodeInfo.setRel(resobj.getString("rel")); - i++; - nodeInfos.add(nodeInfo); - } - if (nodeInfos.size() > 0) { - NodeInfo nodeInfo = nodeInfos.get(nodeInfos.size() - 1); - response = new HttpsConnection(context).get(nodeInfo.getHref(), 30, null, null); - JSONObject resobj = new JSONObject(response); - JSONObject jsonObject = resobj.getJSONObject("software"); - String name = jsonObject.getString("name").toUpperCase(); - if (name.compareTo("CORGIDON") == 0) { - name = "MASTODON"; - } - instanceNodeInfo.setName(name); - instanceNodeInfo.setVersion(jsonObject.getString("version")); - instanceNodeInfo.setOpenRegistrations(resobj.getBoolean("openRegistrations")); - } - } catch (JSONException e) { - e.printStackTrace(); - } - } catch (IOException | JSONException | NoSuchAlgorithmException | KeyManagementException | HttpsConnection.HttpsConnectionException e) { - e.printStackTrace(); - } - return instanceNodeInfo; - } - - /** - * Set the error message - * - * @param statusCode int code - * @param error Throwable error - */ - private void setError(int statusCode, Throwable error) { - APIError = new Error(); - APIError.setStatusCode(statusCode); - String message = statusCode + " - " + error.getMessage(); - try { - JSONObject jsonObject = new JSONObject(Objects.requireNonNull(error.getMessage())); - String errorM = jsonObject.getString("error"); - message = "Error " + statusCode + " : " + errorM; - } catch (JSONException e) { - if (error.getMessage() != null && error.getMessage().split(".").length > 0) { - String errorM = error.getMessage().split(".")[0]; - message = "Error " + statusCode + " : " + errorM; - } - } - APIError.setError(message); - apiResponse.setError(APIError); - } - - private void setDefaultError(Exception e) { - APIError = new Error(); - if (e.getLocalizedMessage() != null && e.getLocalizedMessage().trim().length() > 0) - APIError.setError(e.getLocalizedMessage()); - else if (e.getMessage() != null && e.getMessage().trim().length() > 0) - APIError.setError(e.getMessage()); - else - APIError.setError(context.getString(R.string.toast_error)); - apiResponse.setError(APIError); - } - - public Error getError() { - return APIError; - } - - private String getAbsoluteUrl(String action) { - return Helper.instanceWithProtocol(context) + "/api/v1" + action; - } - - - @SuppressWarnings("SameParameterValue") - private String getAbsoluteUrlForInstance(String instance, String action) { - return "https://" + instance + "/api/v1" + action; - } - - public enum reportType { - ACCOUNT, - COMMENT, - VIDEO - } - - - public enum StatusAction { - FOLLOW, - UNFOLLOW, - MUTE, - UNMUTE, - RATEVIDEO, - PEERTUBECOMMENT, - PEERTUBEREPLY, - PEERTUBEDELETECOMMENT, - PEERTUBEDELETEVIDEO, - REPORT_ACCOUNT, - REPORT_VIDEO - } - -} diff --git a/app/src/main/java/app/fedilab/fedilabtube/client/PeertubeService.java b/app/src/main/java/app/fedilab/fedilabtube/client/PeertubeService.java new file mode 100644 index 0000000..0ab556d --- /dev/null +++ b/app/src/main/java/app/fedilab/fedilabtube/client/PeertubeService.java @@ -0,0 +1,260 @@ +package app.fedilab.fedilabtube.client; +/* 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 . */ + +import java.util.List; +import java.util.Map; + +import app.fedilab.fedilabtube.client.data.AccountData; +import app.fedilab.fedilabtube.client.data.CaptionData; +import app.fedilab.fedilabtube.client.data.ChannelData; +import app.fedilab.fedilabtube.client.data.CommentData; +import app.fedilab.fedilabtube.client.data.InstanceData; +import app.fedilab.fedilabtube.client.data.NotificationData; +import app.fedilab.fedilabtube.client.data.PlaylistData; +import app.fedilab.fedilabtube.client.data.VideoData; +import app.fedilab.fedilabtube.client.entities.CaptionsParams; +import app.fedilab.fedilabtube.client.entities.ChannelParams; +import app.fedilab.fedilabtube.client.entities.OverviewVideo; +import app.fedilab.fedilabtube.client.entities.PlaylistExist; +import app.fedilab.fedilabtube.client.entities.PlaylistParams; +import app.fedilab.fedilabtube.client.entities.Rating; +import app.fedilab.fedilabtube.client.entities.RefreshToken; +import app.fedilab.fedilabtube.client.entities.Report; +import app.fedilab.fedilabtube.client.entities.VideoParams; +import okhttp3.MultipartBody; +import retrofit2.Call; +import retrofit2.http.Body; +import retrofit2.http.DELETE; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.POST; +import retrofit2.http.PUT; +import retrofit2.http.Part; +import retrofit2.http.Path; +import retrofit2.http.Query; +import retrofit2.http.QueryMap; + + +public interface PeertubeService { + @GET("instances") + Call getInstances(@QueryMap Map params, @Query("nsfwPolicy[]") String nsfwPolicy, @Query("categoriesOr[]") List categories, @Query("languagesOr[]") List languages); + + //Server settings + @GET("videos/categories") + Call> getCategories(); + + @GET("videos/languages") + Call> getLanguages(); + + @GET("videos/privacies") + Call> getPrivacies(); + + @GET("video-playlists/privacies") + Call> getPlaylistsPrivacies(); + + @GET("videos/licences") + Call> getLicences(); + + //This one doesn't use api/v1 path + @GET("client/locales/{local}/server.json") + Call> getTranslations(@Path("local") String local); + + //TOKEN + //Refresh + @POST("users/token") + Call refreshToken(@Query("grant_type") String grantType, @Query("client_id") String clientId, @Query("client_secret") String clientSecret, @Query("refresh_token") String refreshToken); + + @GET("users/me") + Call verifyCredentials(@Header("Authorization") String credentials); + + //Timelines Authenticated + //Subscriber timeline + @GET("users/me/subscriptions/videos?sort=-publishedAt") + Call> getSubscriptionVideos(@Query("start") String maxId, @Query("languageOneOf") List languageOneOf); + + //Overview videos + @GET("overviews/videos") + Call getOverviewVideos(@Query("start") String maxId, @Query("languageOneOf") List languageOneOf); + + //Most liked videos + @GET("videos?sort=-likes") + Call> getMostLikedVideos(@Query("start") String maxId, @Query("languageOneOf") List languageOneOf); + + //Most liked videos + @GET("videos?sort=-trending") + Call> getTrendingVideos(@Query("start") String maxId, @Query("languageOneOf") List languageOneOf); + + //Recently added videos + @GET("videos?sort=-publishedAt") + Call> getRecentlyAddedVideos(@Query("start") String maxId, @Query("languageOneOf") List languageOneOf); + + //Local videos + @GET("videos?sort=-publishedAt&filter=local") + Call> getLocalVideos(@Query("start") String maxId, @Query("languageOneOf") List languageOneOf); + + //History + @GET("users/me/history/videos") + Call> getHistory(@Query("start") String maxId); + + //Search + @GET("search/videos") + Call> searchVideos(@Query("search") String search, @Query("start") String maxId); + + //Get notifications + @GET("users/me/notifications") + Call> getNotifications(@Header("Authorization") String credentials, @Query("start") String maxId, @Query("since_id") String sinceId); + + //Get/Post/Update/Delete video + //Get a video + @GET("videos/{id}") + Call getVideo(@Path("id") String id); + + //Get my video + @GET("users/me/videos?sort=-publishedAt") + Call getMyVideo(@Header("Authorization") String credentials, @Query("start") String maxId); + + //Get my video + @GET("accounts/{name}/videos?sort=-publishedAt") + Call getVideosForAccount(@Query("start") String maxId); + + @POST("videos/upload") + Call addVideo(@Header("Authorization") String credentials, @Body VideoParams videoParams, @Part MultipartBody.Part videofile, @Part MultipartBody.Part thumbnailfile, @Part MultipartBody.Part previewfile); + + @PUT("videos/{id}") + Call updateVideo(@Header("Authorization") String credentials, @Path("id") String videoId, @Body VideoParams videoParams, @Part MultipartBody.Part thumbnailfile, @Part MultipartBody.Part previewfile); + + @DELETE("videos/{id}") + Call deleteVideo(@Header("Authorization") String credentials, @Path("id") String videoId); + + + //Post/Update/Delete channel + //Channels for account + @GET("accounts/{accountId}/video-channels") + Call getChannelsForAccount(@Path("accountId") String accountId); + + //Get a channel + @GET("video-channels/{name}") + Call getChannel(@Path("name") String name); + + @GET("video-channels/{channelHandle}/videos") + Call> getChannelVideos(@Path("channelHandle") String channelHandle, @Query("start") String maxId); + + @POST("video-channels") + Call addChannel(@Header("Authorization") String credentials, @Body ChannelParams channelParams); + + @PUT("video-channels/{channelHandle}") + Call updateChannel(@Header("Authorization") String credentials, @Path("channelHandle") String channelHandle, @Body ChannelParams channelParams); + + @DELETE("video-channels/{channelHandle}") + Call deleteChannel(@Header("Authorization") String credentials, @Path("channelHandle") String channelHandle); + + + //Get/Post/Update/Delete playlist + @GET("video-playlists") + Call> getPlaylists(); + + @GET("video-playlists/{id}") + Call getPlaylist(@Path("id") String id); + + @GET("video-playlists/{id}/videos") + Call> getVideosPlayList(@Path("id") String id); + + @GET("users/me/video-playlists/videos-exist") + Call> getVideoExistsInPlaylist(@Query("videoIds") List videoIds); + + @POST("video-playlists") + Call addPlaylist(@Header("Authorization") String credentials, @Body PlaylistParams playlistParams, @Part MultipartBody.Part thumbnailfile); + + @POST("video-playlists/{id}/videos") + Call addVideoInPlaylist(@Header("Authorization") String credentials, @Path("id") String id, @Query("videoId") String videoId); + + @PUT("video-playlists/{id}") + Call updatePlaylist(@Header("Authorization") String credentials, @Path("id") String videoId, @Body PlaylistParams playlistParams, @Part MultipartBody.Part thumbnailfil); + + @DELETE("video-playlists/{id}") + Call deletePlaylist(@Header("Authorization") String credentials, @Path("id") String playlistId); + + @DELETE("video-playlists/{id}/videos/{playlistElementId}") + Call deleteVideoInPlaylist(@Header("Authorization") String credentials, @Path("id") String videoId, @Path("playlistElementId") String playlistElementId); + + //Get/Update/Delete captions + @GET("videos/{id}/captions") + Call> getCaptions(@Path("id") String videoId); + + @PUT("videos/{id}/captions/{captionLanguage}") + Call updateCaptions(@Header("Authorization") String credentials, @Path("id") String videoId, @Path("captionLanguage") String captionLanguage, @Body CaptionsParams captionsParams, @Part MultipartBody.Part captionfile); + + @DELETE("videos/{id}/captions/{captionLanguage}") + Call deleteCaptions(@Header("Authorization") String credentials, @Path("id") String videoId, @Path("captionLanguage") String captionLanguage); + + + //Subscribe/Unsubscribe + //subscribers + @GET("users/me/subscriptions") + Call getSubscription(@Header("Authorization") String credentials, @Query("start") String maxId); + + @GET("users/me/subscriptions/exist") + Call>> getSubscriptionsExist(@Header("Authorization") String credentials, @Query("uris") List uris); + + @POST("users/me/subscriptions") + Call follow(@Header("Authorization") String credentials, @Query("uri") String uri); + + @DELETE("users/me/subscriptions/{subscriptionHandle}") + Call unfollow(@Header("Authorization") String credentials, @Path("subscriptionHandle") String subscriptionHandle); + + //Mute/Unmute + //Muted accounts + @GET("users/me/blocklist/accounts") + Call getMuted(@Header("Authorization") String credentials, @Query("start") String maxId); + + @POST("users/me/blocklist/accounts") + Call mute(@Header("Authorization") String credentials, @Query("accountName") String accountName); + + @DELETE("users/me/blocklist/accounts/{accountName}") + Call unmute(@Header("Authorization") String credentials, @Path("accountName") String accountName); + + + //Get video rating + @GET("users/me/videos/{id}/rating") + Call getRating(@Header("Authorization") String credentials, @Path("id") String id); + + //Like/unlike + @PUT("videos/{id}/rate") + Call rate(@Header("Authorization") String credentials, @Path("id") String id, @Query("rating") String rating); + + + //Comment + @GET("videos/{id}/comment-threads") + Call> getComments(String credentials, @Path("id") String id); + + @GET("videos/{id}/comment-threads/{threadId}") + Call> getReplies(String credentials, @Path("id") String id, @Path("threadId") String threadId); + + @POST("videos/{id}/comment-threads") + Call postComment(@Header("Authorization") String credentials, @Path("id") String id, @Query("text") String text); + + @POST("videos/{id}/comments/{commentId}") + Call postReply(@Header("Authorization") String credentials, @Path("id") String id, @Path("commentId") String commentId, @Query("text") String text); + + @DELETE("videos/{id}/comments/{commentId}") + Call deleteComment(@Header("Authorization") String credentials, @Path("id") String id, @Path("commentId") String commentId); + + @POST("abuse") + Call report(@Header("Authorization") String credentials, @Body Report report); + + @POST("abuse") + Call register(@Query("email") String email, @Query("password") String password, @Query("username") String username, @Query("displayName") String displayName); +} diff --git a/app/src/main/java/app/fedilab/fedilabtube/client/RetrofitPeertubeAPI.java b/app/src/main/java/app/fedilab/fedilabtube/client/RetrofitPeertubeAPI.java new file mode 100644 index 0000000..4b0d719 --- /dev/null +++ b/app/src/main/java/app/fedilab/fedilabtube/client/RetrofitPeertubeAPI.java @@ -0,0 +1,1138 @@ +package app.fedilab.fedilabtube.client; +/* 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 . */ + +import android.content.Context; +import android.content.SharedPreferences; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +import app.fedilab.fedilabtube.R; +import app.fedilab.fedilabtube.client.data.AccountData; +import app.fedilab.fedilabtube.client.data.CaptionData; +import app.fedilab.fedilabtube.client.data.ChannelData; +import app.fedilab.fedilabtube.client.data.CommentData; +import app.fedilab.fedilabtube.client.data.InstanceData; +import app.fedilab.fedilabtube.client.data.NotificationData; +import app.fedilab.fedilabtube.client.data.PlaylistData; +import app.fedilab.fedilabtube.client.data.VideoData; +import app.fedilab.fedilabtube.client.entities.AccountCreation; +import app.fedilab.fedilabtube.client.entities.ChannelParams; +import app.fedilab.fedilabtube.client.entities.Error; +import app.fedilab.fedilabtube.client.entities.InstanceParams; +import app.fedilab.fedilabtube.client.entities.OverviewVideo; +import app.fedilab.fedilabtube.client.entities.PeertubeInformation; +import app.fedilab.fedilabtube.client.entities.PlaylistParams; +import app.fedilab.fedilabtube.client.entities.Rating; +import app.fedilab.fedilabtube.client.entities.RefreshToken; +import app.fedilab.fedilabtube.client.entities.Report; +import app.fedilab.fedilabtube.helper.Helper; +import app.fedilab.fedilabtube.viewmodel.ChannelsVM; +import app.fedilab.fedilabtube.viewmodel.CommentVM; +import app.fedilab.fedilabtube.viewmodel.PlaylistsVM; +import okhttp3.MediaType; +import okhttp3.MultipartBody; +import okhttp3.RequestBody; +import retrofit2.Call; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +public class RetrofitPeertubeAPI { + + private String finalUrl; + private Context _context; + private String instance; + private String token; + private Set selection; + + public RetrofitPeertubeAPI(Context context) { + _context = context; + instance = Helper.getLiveInstance(context); + finalUrl = "https://" + Helper.getLiveInstance(context) + "/api/v1/"; + } + + public RetrofitPeertubeAPI(Context context, String instance, String token) { + _context = context; + this.instance = instance; + this.token = token; + finalUrl = "https://" + instance + "/api/v1/"; + } + + private PeertubeService init() { + Retrofit retrofit = new Retrofit.Builder() + .baseUrl(finalUrl) + .addConverterFactory(GsonConverterFactory.create()) + .build(); + SharedPreferences sharedpreferences = _context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); + selection = sharedpreferences.getStringSet(_context.getString(R.string.set_video_language_choice), null); + return retrofit.create(PeertubeService.class); + } + + private PeertubeService initTranslation() { + Retrofit retrofit = new Retrofit.Builder() + .baseUrl("https://" + instance) + .addConverterFactory(GsonConverterFactory.create()) + .build(); + return retrofit.create(PeertubeService.class); + } + + + /*** + * Verifiy credential of the authenticated user *synchronously* + * @return Account + */ + private RefreshToken refreshToken(String client_id, String client_secret, String refresh_token) { + PeertubeService peertubeService = init(); + Call refreshTokenCall = peertubeService.refreshToken("refresh_token", client_id, client_secret, refresh_token); + try { + Response response = refreshTokenCall.execute(); + if (response.isSuccessful()) { + return response.body(); + } else { + Error error = new Error(); + error.setStatusCode(response.code()); + if (response.errorBody() != null) { + error.setError(response.message()); + } else { + error.setError(_context.getString(R.string.toast_error)); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + /** + * Retrieve notifications + * + * @param max_id String pagination + * @param since_id String pagination + * @return APIResponse + */ + public APIResponse getNotifications(String max_id, String since_id) { + APIResponse apiResponse = new APIResponse(); + PeertubeService peertubeService = init(); + Call> notificationsCall = peertubeService.getNotifications(token, max_id, since_id); + try { + Response> response = notificationsCall.execute(); + if (response.isSuccessful()) { + apiResponse.setPeertubeNotifications(response.body()); + } else { + Error error = new Error(); + error.setStatusCode(response.code()); + if (response.errorBody() != null) { + error.setError(response.message()); + } else { + error.setError(_context.getString(R.string.toast_error)); + } + apiResponse.setError(error); + } + } catch (IOException e) { + Error error = new Error(); + error.setError(_context.getString(R.string.toast_error)); + apiResponse.setError(error); + e.printStackTrace(); + } + return apiResponse; + } + + public APIResponse getTL(TimelineType timelineType, String max_id) { + APIResponse apiResponse = new APIResponse(); + PeertubeService peertubeService = init(); + Call> videoCall = null; + switch (timelineType) { + case SUBSCRIBTIONS: + videoCall = peertubeService.getSubscriptionVideos(max_id, new ArrayList<>(selection)); + break; + case MOST_LIKED: + videoCall = peertubeService.getMostLikedVideos(max_id, new ArrayList<>(selection)); + break; + case LOCAL: + videoCall = peertubeService.getLocalVideos(max_id, new ArrayList<>(selection)); + break; + case TRENDING: + videoCall = peertubeService.getTrendingVideos(max_id, new ArrayList<>(selection)); + break; + case HISTORY: + videoCall = peertubeService.getHistory(max_id); + break; + case RECENT: + videoCall = peertubeService.getRecentlyAddedVideos(max_id, new ArrayList<>(selection)); + break; + } + if (videoCall != null) { + try { + Response> response = videoCall.execute(); + if (response.isSuccessful()) { + apiResponse.setPeertubes(response.body()); + } else { + Error error = new Error(); + error.setStatusCode(response.code()); + if (response.errorBody() != null) { + error.setError(response.message()); + } else { + error.setError(_context.getString(R.string.toast_error)); + } + apiResponse.setError(error); + } + } catch (IOException e) { + Error error = new Error(); + error.setError(_context.getString(R.string.toast_error)); + apiResponse.setError(error); + e.printStackTrace(); + } + } + return apiResponse; + } + + /** + * Retrieves overview videos videos *synchronously* + * + * @param max_id String id max + * @return APIResponse + */ + public APIResponse getOverviewVideo(String max_id) { + APIResponse apiResponse = new APIResponse(); + PeertubeService peertubeService = init(); + Call overviewVideoCall = peertubeService.getOverviewVideos(max_id, new ArrayList<>(selection)); + try { + Response response = overviewVideoCall.execute(); + if (response.isSuccessful()) { + apiResponse.setOverviewVideo(response.body()); + } else { + Error error = new Error(); + error.setStatusCode(response.code()); + if (response.errorBody() != null) { + error.setError(response.message()); + } else { + error.setError(_context.getString(R.string.toast_error)); + } + apiResponse.setError(error); + } + } catch (IOException e) { + Error error = new Error(); + error.setError(_context.getString(R.string.toast_error)); + apiResponse.setError(error); + e.printStackTrace(); + } + return apiResponse; + } + + /** + * Check if users via their uris are following the authenticated user + * + * @param uris List + * @return APIResponse + */ + public APIResponse isFollowing(List uris) { + APIResponse apiResponse = new APIResponse(); + PeertubeService peertubeService = init(); + Call>> followingCall = peertubeService.getSubscriptionsExist(token, uris); + try { + Response>> response = followingCall.execute(); + if (response.isSuccessful()) { + apiResponse.setRelationships(response.body()); + } else { + Error error = new Error(); + error.setStatusCode(response.code()); + if (response.errorBody() != null) { + error.setError(response.message()); + } else { + error.setError(_context.getString(R.string.toast_error)); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + return apiResponse; + } + + /** + * Find captions for a video + * + * @param videoId String id of the video + * @return APIResponse + */ + public APIResponse getCaptions(String videoId) { + + APIResponse apiResponse = new APIResponse(); + PeertubeService peertubeService = init(); + Call> captions = peertubeService.getCaptions(videoId); + try { + Response> response = captions.execute(); + if (response.isSuccessful()) { + apiResponse.setCaptions(response.body()); + } else { + Error error = new Error(); + error.setStatusCode(response.code()); + if (response.errorBody() != null) { + error.setError(response.message()); + } else { + error.setError(_context.getString(R.string.toast_error)); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + return apiResponse; + } + + /** + * Returns informations about Peertube such privacies, licenses, etc. + * + * @return PeertubeInformation information about peertube + */ + public PeertubeInformation getPeertubeInformation() { + PeertubeInformation peertubeInformation = new PeertubeInformation(); + PeertubeService peertubeService = init(); + Call> categories = peertubeService.getCategories(); + try { + Response> response = categories.execute(); + if (response.isSuccessful()) { + peertubeInformation.setCategories(response.body()); + } else { + Error error = new Error(); + error.setStatusCode(response.code()); + if (response.errorBody() != null) { + error.setError(response.message()); + } else { + error.setError(_context.getString(R.string.toast_error)); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + Call> languages = peertubeService.getLanguages(); + try { + Response> response = languages.execute(); + if (response.isSuccessful()) { + peertubeInformation.setLanguages(response.body()); + } else { + Error error = new Error(); + error.setStatusCode(response.code()); + if (response.errorBody() != null) { + error.setError(response.message()); + } else { + error.setError(_context.getString(R.string.toast_error)); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + Call> privacies = peertubeService.getPrivacies(); + try { + Response> response = privacies.execute(); + if (response.isSuccessful()) { + peertubeInformation.setPrivacies(response.body()); + } else { + Error error = new Error(); + error.setStatusCode(response.code()); + if (response.errorBody() != null) { + error.setError(response.message()); + } else { + error.setError(_context.getString(R.string.toast_error)); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + Call> playlistsPrivacies = peertubeService.getPlaylistsPrivacies(); + try { + Response> response = playlistsPrivacies.execute(); + if (response.isSuccessful()) { + peertubeInformation.setPlaylistPrivacies(response.body()); + } else { + Error error = new Error(); + error.setStatusCode(response.code()); + if (response.errorBody() != null) { + error.setError(response.message()); + } else { + error.setError(_context.getString(R.string.toast_error)); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + Call> licenses = peertubeService.getLicences(); + try { + Response> response = licenses.execute(); + if (response.isSuccessful()) { + peertubeInformation.setLicences(response.body()); + } else { + Error error = new Error(); + error.setStatusCode(response.code()); + if (response.errorBody() != null) { + error.setError(response.message()); + } else { + error.setError(_context.getString(R.string.toast_error)); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + String lang = null; + if (PeertubeInformation.langueMapped.containsKey(Locale.getDefault().getLanguage())) + lang = PeertubeInformation.langueMapped.get(Locale.getDefault().getLanguage()); + + Call> translations = initTranslation().getTranslations(lang); + try { + Response> response = translations.execute(); + if (response.isSuccessful()) { + peertubeInformation.setTranslations(response.body()); + } else { + Error error = new Error(); + error.setStatusCode(response.code()); + if (response.errorBody() != null) { + error.setError(response.message()); + } else { + error.setError(_context.getString(R.string.toast_error)); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + return peertubeInformation; + } + + /** + * Get instances + * + * @param instanceParams InstanceParams + * @return APIResponse + */ + public APIResponse getInstances(InstanceParams instanceParams) { + PeertubeService peertubeService = init(); + LinkedHashMap params = new LinkedHashMap<>(); + params.put("start", "0"); + params.put("count", "250"); + params.put("healthy", "true"); + params.put("signup", "true"); + params.put("minUserQuota", instanceParams.getMinUserQuota()); + Call instancesCall = peertubeService.getInstances(params, instanceParams.getNsfwPolicy(), instanceParams.getCategoriesOr(), instanceParams.getLanguagesOr()); + APIResponse apiResponse = new APIResponse(); + try { + Response response = instancesCall.execute(); + if (!response.isSuccessful()) { + Error error = new Error(); + error.setStatusCode(response.code()); + if (response.errorBody() != null) { + error.setError(response.message()); + } else { + error.setError(_context.getString(R.string.toast_error)); + } + apiResponse.setError(error); + } else { + InstanceData instanceData = response.body(); + if (instanceData != null) { + apiResponse.setInstances(instanceData.data); + } + } + } catch (IOException e) { + Error error = new Error(); + error.setError(_context.getString(R.string.toast_error)); + apiResponse.setError(error); + e.printStackTrace(); + } + return apiResponse; + } + + /** + * Retrieves peertube search *synchronously* + * + * @param query String search + * @return APIResponse + */ + public APIResponse searchPeertube(String query, String max_id) { + PeertubeService peertubeService = init(); + Call> searchVideosCall = peertubeService.searchVideos(query, max_id); + APIResponse apiResponse = new APIResponse(); + try { + Response> response = searchVideosCall.execute(); + if (response.isSuccessful()) { + apiResponse.setPeertubes(response.body()); + } else { + Error error = new Error(); + error.setStatusCode(response.code()); + if (response.errorBody() != null) { + error.setError(response.message()); + } else { + error.setError(_context.getString(R.string.toast_error)); + } + apiResponse.setError(error); + } + } catch (IOException e) { + Error error = new Error(); + error.setError(_context.getString(R.string.toast_error)); + apiResponse.setError(error); + e.printStackTrace(); + } + return apiResponse; + } + + /*** + * Verifiy credential of the authenticated user *synchronously* + * @return Account + */ + public AccountData.Account verifyCredentials(String token, String instance) { + PeertubeService peertubeService = init(); + Call accountCall = peertubeService.verifyCredentials(token); + APIResponse apiResponse = new APIResponse(); + try { + Response response = accountCall.execute(); + if (response.isSuccessful()) { + return response.body(); + } else { + Error error = new Error(); + error.setStatusCode(response.code()); + if (response.errorBody() != null) { + error.setError(response.message()); + } else { + error.setError(_context.getString(R.string.toast_error)); + } + apiResponse.setError(error); + } + } catch (IOException e) { + Error error = new Error(); + error.setError(_context.getString(R.string.toast_error)); + apiResponse.setError(error); + e.printStackTrace(); + } + return null; + } + + public APIResponse report(Report report) { + PeertubeService peertubeService = init(); + Call report1 = peertubeService.report(token, report); + APIResponse apiResponse = new APIResponse(); + try { + Response response = report1.execute(); + if (response.isSuccessful()) { + apiResponse.setActionReturn(response.body()); + } else { + Error error = new Error(); + error.setStatusCode(response.code()); + if (response.errorBody() != null) { + error.setError(response.message()); + } else { + error.setError(_context.getString(R.string.toast_error)); + } + apiResponse.setError(error); + } + } catch (IOException e) { + Error error = new Error(); + error.setError(_context.getString(R.string.toast_error)); + apiResponse.setError(error); + e.printStackTrace(); + } + return apiResponse; + } + + public APIResponse createAccount(AccountCreation accountCreation) { + PeertubeService peertubeService = init(); + Call report1 = peertubeService.register(accountCreation.getEmail(), accountCreation.getPassword(), accountCreation.getUsername(), accountCreation.getDisplayName()); + APIResponse apiResponse = new APIResponse(); + try { + Response response = report1.execute(); + if (response.isSuccessful()) { + apiResponse.setActionReturn(accountCreation.getEmail()); + } else { + Error error = new Error(); + error.setStatusCode(response.code()); + if (response.errorBody() != null) { + error.setError(response.message()); + } else { + error.setError(_context.getString(R.string.toast_error)); + } + apiResponse.setError(error); + } + } catch (IOException e) { + Error error = new Error(); + error.setError(_context.getString(R.string.toast_error)); + apiResponse.setError(error); + e.printStackTrace(); + } + return apiResponse; + } + + public APIResponse post(ActionType actionType, String id, String element) { + PeertubeService peertubeService = init(); + Call postCall = null; + APIResponse apiResponse = new APIResponse(); + switch (actionType) { + case FOLLOW: + postCall = peertubeService.follow(token, id); + break; + case UNFOLLOW: + postCall = peertubeService.unfollow(token, id); + break; + case MUTE: + postCall = peertubeService.mute(token, id); + break; + case UNMUTE: + postCall = peertubeService.unmute(token, id); + break; + case RATEVIDEO: + postCall = peertubeService.rate(token, id, element); + break; + case PEERTUBEDELETEVIDEO: + postCall = peertubeService.deleteVideo(token, id); + break; + case DELETE_CHANNEL: + postCall = peertubeService.deleteChannel(token, id); + break; + } + if (postCall != null) { + try { + Response response = postCall.execute(); + if (response.isSuccessful()) { + apiResponse.setActionReturn(response.body()); + } else { + Error error = new Error(); + error.setStatusCode(response.code()); + if (response.errorBody() != null) { + error.setError(response.message()); + } else { + error.setError(_context.getString(R.string.toast_error)); + } + apiResponse.setError(error); + } + } catch (IOException e) { + Error error = new Error(); + error.setError(_context.getString(R.string.toast_error)); + apiResponse.setError(error); + e.printStackTrace(); + } + } + return apiResponse; + } + + /** + * Get accounts data + * + * @param accountDataType AccountDataType (type of requested data) + * @param maxId String (pagination) + * @return APIResponse + */ + public APIResponse getAccountData(DataType accountDataType, String maxId) { + PeertubeService peertubeService = init(); + Call accountDataCall = null; + switch (accountDataType) { + case SUBSCRIBER: + accountDataCall = peertubeService.getSubscription("Bearer " + token, maxId); + break; + case MUTED: + accountDataCall = peertubeService.getMuted("Bearer " + token, maxId); + break; + } + APIResponse apiResponse = new APIResponse(); + if (accountDataCall != null) { + try { + Response response = accountDataCall.execute(); + if (!response.isSuccessful()) { + Error error = new Error(); + error.setStatusCode(response.code()); + if (response.errorBody() != null) { + error.setError(response.message()); + } else { + error.setError(_context.getString(R.string.toast_error)); + } + apiResponse.setError(error); + } else { + AccountData accountData = response.body(); + if (accountData != null) { + apiResponse.setAccounts(accountData.data); + } + } + } catch (IOException e) { + Error error = new Error(); + error.setError(_context.getString(R.string.toast_error)); + apiResponse.setError(error); + e.printStackTrace(); + } + } + return apiResponse; + } + + /** + * Create or update a channel + * + * @param apiAction ChannelsVM.action + * @param channelId String + * @param channelParams PlaylistParams + * @return APIResponse + */ + public APIResponse createOrUpdateChannel(ChannelsVM.action apiAction, String channelId, ChannelParams channelParams, File thumbnail) { + PeertubeService peertubeService = init(); + + APIResponse apiResponse = new APIResponse(); + MultipartBody.Part body = null; + if (thumbnail != null) { + RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), thumbnail); + body = MultipartBody.Part.createFormData("image", thumbnail.getName(), requestFile); + } + try { + if (apiAction == ChannelsVM.action.CREATE_CHANNEL) { + Call stringCall = peertubeService.addChannel(token, channelParams); + Response response = stringCall.execute(); + if (response.isSuccessful()) { + apiResponse.setActionReturn(response.body()); + } else { + Error error = generateError(response.code(), response.message()); + apiResponse.setError(error); + } + + } else if (apiAction == ChannelsVM.action.UPDATE_CHANNEL) { + Call stringCall = peertubeService.updateChannel(token, channelId, channelParams); + Response response = stringCall.execute(); + if (response.isSuccessful()) { + apiResponse.setActionReturn(response.body()); + } else { + Error error = generateError(response.code(), response.message()); + apiResponse.setError(error); + } + } + } catch (IOException e) { + Error error = new Error(); + error.setError(_context.getString(R.string.toast_error)); + apiResponse.setError(error); + e.printStackTrace(); + } + return apiResponse; + } + + /** + * Get channel data + * + * @param accountDataType AccountDataType (type of requested data) + * @param element String (pagination or name for the channel) + * @return APIResponse + */ + public APIResponse getChannelData(DataType accountDataType, String element) { + PeertubeService peertubeService = init(); + + APIResponse apiResponse = new APIResponse(); + switch (accountDataType) { + case CHANNELS_FOR_ACCOUNT: + Call channelDataCall = peertubeService.getChannelsForAccount(element); + try { + Response response = channelDataCall.execute(); + if (!response.isSuccessful()) { + Error error = new Error(); + error.setStatusCode(response.code()); + if (response.errorBody() != null) { + error.setError(response.message()); + } else { + error.setError(_context.getString(R.string.toast_error)); + } + apiResponse.setError(error); + } else { + ChannelData channelData = response.body(); + if (channelData != null) { + apiResponse.setChannels(channelData.data); + } + } + } catch (IOException e) { + Error error = new Error(); + error.setError(_context.getString(R.string.toast_error)); + apiResponse.setError(error); + e.printStackTrace(); + } + break; + case CHANNEL: + Call channelCall = peertubeService.getChannel(element); + try { + Response response = channelCall.execute(); + if (!response.isSuccessful()) { + Error error = new Error(); + error.setStatusCode(response.code()); + if (response.errorBody() != null) { + error.setError(response.message()); + } else { + error.setError(_context.getString(R.string.toast_error)); + } + apiResponse.setError(error); + } else { + ChannelData.Channel channelData = response.body(); + if (channelData != null) { + List channelList = new ArrayList<>(); + channelList.add(channelData); + apiResponse.setChannels(channelList); + } + } + } catch (IOException e) { + Error error = new Error(); + error.setError(_context.getString(R.string.toast_error)); + apiResponse.setError(error); + e.printStackTrace(); + } + break; + } + return apiResponse; + } + + /** + * Create or update a playlist + * + * @param apiAction PlaylistsVM.action + * @param playlistId String + * @param playlistParams PlaylistParams + * @return APIResponse + */ + public APIResponse createOrUpdatePlaylist(PlaylistsVM.action apiAction, String playlistId, PlaylistParams playlistParams, File thumbnail) { + PeertubeService peertubeService = init(); + + APIResponse apiResponse = new APIResponse(); + MultipartBody.Part body = null; + if (thumbnail != null) { + RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), thumbnail); + body = MultipartBody.Part.createFormData("image", thumbnail.getName(), requestFile); + } + try { + if (apiAction == PlaylistsVM.action.CREATE_PLAYLIST) { + Call stringCall = peertubeService.addPlaylist(token, playlistParams, body); + Response response = stringCall.execute(); + if (response.isSuccessful()) { + apiResponse.setActionReturn(response.body()); + } else { + Error error = generateError(response.code(), response.message()); + apiResponse.setError(error); + } + + } else if (apiAction == PlaylistsVM.action.UPDATE_PLAYLIST) { + Call stringCall = peertubeService.updatePlaylist(token, playlistId, playlistParams, body); + Response response = stringCall.execute(); + if (response.isSuccessful()) { + apiResponse.setActionReturn(response.body()); + } else { + Error error = generateError(response.code(), response.message()); + apiResponse.setError(error); + } + } + } catch (IOException e) { + Error error = new Error(); + error.setError(_context.getString(R.string.toast_error)); + apiResponse.setError(error); + e.printStackTrace(); + } + return apiResponse; + } + + /** + * Retrieves playlist *synchronously* + * + * @param type PlaylistsVM.action + * @param playlistId String id of the playlist + * @param videoId String id of the video + * @return APIResponse + */ + public APIResponse playlistAction(PlaylistsVM.action type, String playlistId, String videoId) { + PeertubeService peertubeService = init(); + + APIResponse apiResponse = new APIResponse(); + try { + + if (type == PlaylistsVM.action.GET_PLAYLIST_INFO) { + Call playlistCall = peertubeService.getPlaylist(playlistId); + Response response = playlistCall.execute(); + if (response.isSuccessful()) { + List playlists = new ArrayList<>(); + playlists.add(response.body()); + apiResponse.setPlaylists(playlists); + } else { + Error error = generateError(response.code(), response.message()); + apiResponse.setError(error); + } + + } else if (type == PlaylistsVM.action.GET_PLAYLISTS) { + Call> playlistsCall = peertubeService.getPlaylists(); + Response> response = playlistsCall.execute(); + if (response.isSuccessful()) { + apiResponse.setPlaylists(response.body()); + } else { + Error error = generateError(response.code(), response.message()); + apiResponse.setError(error); + } + } else if (type == PlaylistsVM.action.GET_LIST_VIDEOS) { + Call> videosPlayList = peertubeService.getVideosPlayList(playlistId); + Response> response = videosPlayList.execute(); + if (response.isSuccessful()) { + apiResponse.setPeertubes(response.body()); + } else { + Error error = generateError(response.code(), response.message()); + apiResponse.setError(error); + } + } else if (type == PlaylistsVM.action.DELETE_PLAYLIST) { + Call stringCall = peertubeService.deletePlaylist(token, playlistId); + Response response = stringCall.execute(); + if (response.isSuccessful()) { + apiResponse.setActionReturn(response.body()); + } else { + Error error = generateError(response.code(), response.message()); + apiResponse.setError(error); + } + } else if (type == PlaylistsVM.action.ADD_VIDEOS) { + Call stringCall = peertubeService.addVideoInPlaylist(token, playlistId, videoId); + Response response = stringCall.execute(); + if (response.isSuccessful()) { + apiResponse.setActionReturn(response.body()); + } else { + Error error = generateError(response.code(), response.message()); + apiResponse.setError(error); + } + } else if (type == PlaylistsVM.action.DELETE_VIDEOS) { + Call stringCall = peertubeService.deleteVideoInPlaylist(token, playlistId, videoId); + Response response = stringCall.execute(); + if (response.isSuccessful()) { + apiResponse.setActionReturn(response.body()); + } else { + Error error = generateError(response.code(), response.message()); + apiResponse.setError(error); + } + } + + } catch (IOException e) { + Error error = new Error(); + error.setError(_context.getString(R.string.toast_error)); + apiResponse.setError(error); + e.printStackTrace(); + } + return apiResponse; + } + + public APIResponse getComments(CommentVM.action type, String videoId, String forCommentId) { + PeertubeService peertubeService = init(); + + APIResponse apiResponse = new APIResponse(); + try { + if (type == CommentVM.action.GET_THREAD) { + Call> commentsCall = peertubeService.getComments(token, videoId); + Response> response = commentsCall.execute(); + if (response.isSuccessful()) { + apiResponse.setComments(response.body()); + } else { + Error error = generateError(response.code(), response.message()); + apiResponse.setError(error); + } + } else if (type == CommentVM.action.GET_REPLIES) { + Call> commentsCall = peertubeService.getReplies(token, videoId, forCommentId); + Response> response = commentsCall.execute(); + if (response.isSuccessful()) { + apiResponse.setComments(response.body()); + } else { + Error error = generateError(response.code(), response.message()); + apiResponse.setError(error); + } + } + } catch (IOException e) { + Error error = new Error(); + error.setError(_context.getString(R.string.toast_error)); + apiResponse.setError(error); + e.printStackTrace(); + } + return apiResponse; + } + + /** + * Manage comments *synchronously* + * + * @param type (CommentVM.action + * @param videoId String id of the video + * @param toCommentId String id of the comment for replies + * @param text String text + * @return APIResponse + */ + public APIResponse commentAction(CommentVM.action type, String videoId, String toCommentId, String text) { + PeertubeService peertubeService = init(); + + APIResponse apiResponse = new APIResponse(); + try { + if (type == CommentVM.action.ADD_COMMENT) { + Call stringCall = peertubeService.postComment(token, videoId, text); + Response response = stringCall.execute(); + if (response.isSuccessful()) { + apiResponse.setActionReturn(response.body()); + } else { + Error error = generateError(response.code(), response.message()); + apiResponse.setError(error); + } + } else if (type == CommentVM.action.REPLY) { + Call stringCall = peertubeService.postReply(token, videoId, toCommentId, text); + Response response = stringCall.execute(); + if (response.isSuccessful()) { + apiResponse.setActionReturn(response.body()); + } else { + Error error = generateError(response.code(), response.message()); + apiResponse.setError(error); + } + } + } catch (IOException e) { + Error error = new Error(); + error.setError(_context.getString(R.string.toast_error)); + apiResponse.setError(error); + e.printStackTrace(); + } + return apiResponse; + } + + /** + * Retrieves playlist *synchronously* + * + * @param id String id + * @return APIResponse + */ + public APIResponse getPlayist(String id) { + PeertubeService peertubeService = init(); + Call playlistCall; + playlistCall = peertubeService.getPlaylist(id); + APIResponse apiResponse = new APIResponse(); + try { + Response response = playlistCall.execute(); + if (response.isSuccessful()) { + List playlists = new ArrayList<>(); + playlists.add(response.body()); + apiResponse.setPlaylists(playlists); + } else { + Error error = generateError(response.code(), response.message()); + apiResponse.setError(error); + } + } catch (IOException e) { + Error error = new Error(); + error.setError(_context.getString(R.string.toast_error)); + apiResponse.setError(error); + e.printStackTrace(); + } + return apiResponse; + } + + private Error generateError(int responseCode, String message) { + Error error = new Error(); + error.setStatusCode(responseCode); + if (message != null) { + error.setError(message); + } else { + error.setError(_context.getString(R.string.toast_error)); + } + return error; + } + + /** + * Retrieves rating of user on a video *synchronously* + * + * @param id String id + * @return APIResponse + */ + public APIResponse getRating(String id) { + PeertubeService peertubeService = init(); + Call rating = peertubeService.getRating(token, id); + APIResponse apiResponse = new APIResponse(); + try { + Response response = rating.execute(); + if (response.isSuccessful()) { + apiResponse.setRating(response.body()); + } else { + Error error = new Error(); + error.setStatusCode(response.code()); + if (response.errorBody() != null) { + error.setError(response.message()); + } else { + error.setError(_context.getString(R.string.toast_error)); + } + } + } catch (IOException e) { + Error error = new Error(); + error.setError(_context.getString(R.string.toast_error)); + apiResponse.setError(error); + e.printStackTrace(); + } + return apiResponse; + } + + /** + * Retrieves videos *synchronously* + * + * @param id String id + * @return APIResponse + */ + public APIResponse getVideos(String id) { + PeertubeService peertubeService = init(); + Call video = peertubeService.getVideo(id); + APIResponse apiResponse = new APIResponse(); + try { + Response response = video.execute(); + if (response.isSuccessful()) { + List videos = new ArrayList<>(); + videos.add(response.body()); + apiResponse.setPeertubes(videos); + } else { + Error error = new Error(); + error.setStatusCode(response.code()); + if (response.errorBody() != null) { + error.setError(response.message()); + } else { + error.setError(_context.getString(R.string.toast_error)); + } + } + } catch (IOException e) { + Error error = new Error(); + error.setError(_context.getString(R.string.toast_error)); + apiResponse.setError(error); + e.printStackTrace(); + } + return apiResponse; + + } + + public enum TimelineType { + SUBSCRIBTIONS, + LOCAL, + OVERVIEW, + TRENDING, + MOST_LIKED, + HISTORY, + RECENT + } + + public enum DataType { + SUBSCRIBER, + MUTED, + CHANNELS_FOR_ACCOUNT, + CHANNEL + } + + + public enum ActionType { + FOLLOW, + UNFOLLOW, + MUTE, + UNMUTE, + RATEVIDEO, + PEERTUBEDELETECOMMENT, + PEERTUBEDELETEVIDEO, + REPORT_VIDEO, + DELETE_CHANNEL + } + + +} diff --git a/app/src/main/java/app/fedilab/fedilabtube/client/TLSSocketFactory.java b/app/src/main/java/app/fedilab/fedilabtube/client/TLSSocketFactory.java deleted file mode 100644 index 528de55..0000000 --- a/app/src/main/java/app/fedilab/fedilabtube/client/TLSSocketFactory.java +++ /dev/null @@ -1,93 +0,0 @@ -package app.fedilab.fedilabtube.client; -/* 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 . */ - -import java.io.IOException; -import java.net.InetAddress; -import java.net.Socket; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.SSLSocketFactory; - - -public class TLSSocketFactory extends SSLSocketFactory { - - private SSLSocketFactory sSLSocketFactory; - private SSLContext sslContext; - - - public TLSSocketFactory() throws KeyManagementException, NoSuchAlgorithmException { - - sslContext = SSLContext.getInstance("TLS"); - sslContext.init(null, null, null); - sSLSocketFactory = sslContext.getSocketFactory(); - - } - - public SSLContext getSSLContext() { - return this.sslContext; - } - - - @Override - public String[] getDefaultCipherSuites() { - return sSLSocketFactory.getDefaultCipherSuites(); - } - - @Override - public String[] getSupportedCipherSuites() { - return sSLSocketFactory.getSupportedCipherSuites(); - } - - @Override - public Socket createSocket() throws IOException { - return enableTLSOnSocket(sSLSocketFactory.createSocket()); - } - - @Override - public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { - return enableTLSOnSocket(sSLSocketFactory.createSocket(s, host, port, autoClose)); - } - - @Override - public Socket createSocket(String host, int port) throws IOException { - return enableTLSOnSocket(sSLSocketFactory.createSocket(host, port)); - } - - @Override - public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException { - return enableTLSOnSocket(sSLSocketFactory.createSocket(host, port, localHost, localPort)); - } - - @Override - public Socket createSocket(InetAddress host, int port) throws IOException { - return enableTLSOnSocket(sSLSocketFactory.createSocket(host, port)); - } - - @Override - public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { - return enableTLSOnSocket(sSLSocketFactory.createSocket(address, port, localAddress, localPort)); - } - - private Socket enableTLSOnSocket(Socket socket) { - if ((socket instanceof SSLSocket)) { - ((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1.1", "TLSv1.2",}); - } - return socket; - } -} \ No newline at end of file diff --git a/app/src/main/java/app/fedilab/fedilabtube/client/data/AccountData.java b/app/src/main/java/app/fedilab/fedilabtube/client/data/AccountData.java new file mode 100644 index 0000000..dd669b2 --- /dev/null +++ b/app/src/main/java/app/fedilab/fedilabtube/client/data/AccountData.java @@ -0,0 +1,264 @@ +package app.fedilab.fedilabtube.client.data; +/* 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 . */ + +import android.os.Parcel; +import android.os.Parcelable; + +import com.google.gson.annotations.SerializedName; + +import java.util.Date; +import java.util.List; + +import app.fedilab.fedilabtube.client.entities.Avatar; + + +@SuppressWarnings("unused") +public class AccountData { + + @SerializedName("total") + public int total; + @SerializedName("data") + public List data; + + public static class Account implements Parcelable { + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + @Override + public Account createFromParcel(Parcel source) { + return new Account(source); + } + + @Override + public Account[] newArray(int size) { + return new Account[size]; + } + }; + @SerializedName("avatar") + private Avatar avatar; + @SerializedName("createdAt") + private Date createdAt; + @SerializedName("description") + private String description; + @SerializedName("displayName") + private String displayName; + @SerializedName("followersCount") + private int followersCount; + @SerializedName("followingCount") + private int followingCount; + @SerializedName("host") + private String host; + @SerializedName("hostRedundancyAllowed") + private boolean hostRedundancyAllowed; + @SerializedName("id") + private String id; + @SerializedName("name") + private String name; + @SerializedName("updatedAt") + private Date updatedAt; + @SerializedName("url") + private String url; + private String acct; + private String token; + private String client_id; + private String client_secret; + private String refresh_token; + private boolean selected; + + public Account() { + } + + protected Account(Parcel in) { + this.avatar = in.readParcelable(Avatar.class.getClassLoader()); + long tmpCreatedAt = in.readLong(); + this.createdAt = tmpCreatedAt == -1 ? null : new Date(tmpCreatedAt); + this.description = in.readString(); + this.displayName = in.readString(); + this.followersCount = in.readInt(); + this.followingCount = in.readInt(); + this.host = in.readString(); + this.hostRedundancyAllowed = in.readByte() != 0; + this.id = in.readString(); + this.name = in.readString(); + long tmpUpdatedAt = in.readLong(); + this.updatedAt = tmpUpdatedAt == -1 ? null : new Date(tmpUpdatedAt); + this.url = in.readString(); + } + + public Avatar getAvatar() { + return avatar; + } + + public void setAvatar(Avatar avatar) { + this.avatar = avatar; + } + + public Date getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Date createdAt) { + this.createdAt = createdAt; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public int getFollowersCount() { + return followersCount; + } + + public void setFollowersCount(int followersCount) { + this.followersCount = followersCount; + } + + public int getFollowingCount() { + return followingCount; + } + + public void setFollowingCount(int followingCount) { + this.followingCount = followingCount; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public boolean isHostRedundancyAllowed() { + return hostRedundancyAllowed; + } + + public void setHostRedundancyAllowed(boolean hostRedundancyAllowed) { + this.hostRedundancyAllowed = hostRedundancyAllowed; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Date getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Date updatedAt) { + this.updatedAt = updatedAt; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public boolean isSelected() { + return selected; + } + + public void setSelected(boolean selected) { + this.selected = selected; + } + + public String getAcct() { + return acct; + } + + public void setAcct(String acct) { + this.acct = acct; + } + + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } + + public String getClient_id() { + return client_id; + } + + public void setClient_id(String client_id) { + this.client_id = client_id; + } + + public String getClient_secret() { + return client_secret; + } + + public void setClient_secret(String client_secret) { + this.client_secret = client_secret; + } + + public String getRefresh_token() { + return refresh_token; + } + + public void setRefresh_token(String refresh_token) { + this.refresh_token = refresh_token; + } + + @Override + public int describeContents() { + return 0; + } + + @Override + public void writeToParcel(Parcel dest, int flags) { + dest.writeParcelable(this.avatar, flags); + dest.writeLong(this.createdAt != null ? this.createdAt.getTime() : -1); + dest.writeString(this.description); + dest.writeString(this.displayName); + dest.writeInt(this.followersCount); + dest.writeInt(this.followingCount); + dest.writeString(this.host); + dest.writeByte(this.hostRedundancyAllowed ? (byte) 1 : (byte) 0); + dest.writeString(this.id); + dest.writeString(this.name); + dest.writeLong(this.updatedAt != null ? this.updatedAt.getTime() : -1); + dest.writeString(this.url); + } + } +} diff --git a/app/src/main/java/app/fedilab/fedilabtube/client/data/CaptionData.java b/app/src/main/java/app/fedilab/fedilabtube/client/data/CaptionData.java new file mode 100644 index 0000000..4dc8f2f --- /dev/null +++ b/app/src/main/java/app/fedilab/fedilabtube/client/data/CaptionData.java @@ -0,0 +1,53 @@ +package app.fedilab.fedilabtube.client.data; +/* 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 . */ + +import com.google.gson.annotations.SerializedName; + +import java.util.List; + +import app.fedilab.fedilabtube.client.entities.Item; + +@SuppressWarnings("unused") +public class CaptionData { + + @SerializedName("total") + public int total; + @SerializedName("data") + public List data; + + public static class Caption { + @SerializedName("captionPath") + private String captionPath; + @SerializedName("language") + private Item language; + + public String getCaptionPath() { + return captionPath; + } + + public void setCaptionPath(String captionPath) { + this.captionPath = captionPath; + } + + public Item getLanguage() { + return language; + } + + public void setLanguage(Item language) { + this.language = language; + } + } +} diff --git a/app/src/main/java/app/fedilab/fedilabtube/client/data/ChannelData.java b/app/src/main/java/app/fedilab/fedilabtube/client/data/ChannelData.java new file mode 100644 index 0000000..363f735 --- /dev/null +++ b/app/src/main/java/app/fedilab/fedilabtube/client/data/ChannelData.java @@ -0,0 +1,271 @@ +package app.fedilab.fedilabtube.client.data; +/* 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 . */ + +import android.os.Parcel; +import android.os.Parcelable; + +import com.google.gson.annotations.SerializedName; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import app.fedilab.fedilabtube.client.entities.Avatar; +import app.fedilab.fedilabtube.client.entities.ViewsPerDay; + +@SuppressWarnings("unused") +public class ChannelData { + + @SerializedName("total") + public int total; + @SerializedName("data") + public List data; + + public static class Channel implements Parcelable { + public static final Creator CREATOR = new Creator() { + @Override + public Channel createFromParcel(Parcel source) { + return new Channel(source); + } + + @Override + public Channel[] newArray(int size) { + return new Channel[size]; + } + }; + @SerializedName("avatar") + private Avatar avatar; + @SerializedName("createdAt") + private Date createdAt; + @SerializedName("description") + private String description; + @SerializedName("displayName") + private String displayName; + @SerializedName("followersCount") + private int followersCount; + @SerializedName("followingCount") + private int followingCount; + @SerializedName("host") + private String host; + @SerializedName("hostRedundancyAllowed") + private boolean hostRedundancyAllowed; + @SerializedName("id") + private String id; + @SerializedName("isLocal") + private boolean isLocal; + @SerializedName("name") + private String name; + @SerializedName("ownerAccount") + private AccountData.Account ownerAccount; + @SerializedName("support") + private String support; + @SerializedName("updatedAt") + private Date updatedAt; + @SerializedName("url") + private String url; + @SerializedName("viewsPerDay") + private List viewsPerDays; + private String acct; + + public Channel() { + } + + protected Channel(Parcel in) { + this.avatar = in.readParcelable(Avatar.class.getClassLoader()); + long tmpCreatedAt = in.readLong(); + this.createdAt = tmpCreatedAt == -1 ? null : new Date(tmpCreatedAt); + this.description = in.readString(); + this.displayName = in.readString(); + this.followersCount = in.readInt(); + this.followingCount = in.readInt(); + this.host = in.readString(); + this.hostRedundancyAllowed = in.readByte() != 0; + this.id = in.readString(); + this.isLocal = in.readByte() != 0; + this.name = in.readString(); + this.ownerAccount = in.readParcelable(AccountData.Account.class.getClassLoader()); + this.support = in.readString(); + long tmpUpdatedAt = in.readLong(); + this.updatedAt = tmpUpdatedAt == -1 ? null : new Date(tmpUpdatedAt); + this.url = in.readString(); + this.viewsPerDays = new ArrayList<>(); + in.readList(this.viewsPerDays, ViewsPerDay.class.getClassLoader()); + this.acct = in.readString(); + } + + public Avatar getAvatar() { + return avatar; + } + + public void setAvatar(Avatar avatar) { + this.avatar = avatar; + } + + public Date getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Date createdAt) { + this.createdAt = createdAt; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public int getFollowersCount() { + return followersCount; + } + + public void setFollowersCount(int followersCount) { + this.followersCount = followersCount; + } + + public int getFollowingCount() { + return followingCount; + } + + public void setFollowingCount(int followingCount) { + this.followingCount = followingCount; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public boolean isHostRedundancyAllowed() { + return hostRedundancyAllowed; + } + + public void setHostRedundancyAllowed(boolean hostRedundancyAllowed) { + this.hostRedundancyAllowed = hostRedundancyAllowed; + } + + public String getAcct() { + return acct; + } + + public void setAcct(String acct) { + this.acct = acct; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public boolean isLocal() { + return isLocal; + } + + public void setLocal(boolean local) { + isLocal = local; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public AccountData.Account getOwnerAccount() { + return ownerAccount; + } + + public void setOwnerAccount(AccountData.Account ownerAccount) { + this.ownerAccount = ownerAccount; + } + + public String getSupport() { + return support; + } + + public void setSupport(String support) { + this.support = support; + } + + public Date getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Date updatedAt) { + this.updatedAt = updatedAt; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public List getViewsPerDays() { + return viewsPerDays; + } + + public void setViewsPerDays(List viewsPerDays) { + this.viewsPerDays = viewsPerDays; + } + + @Override + public int describeContents() { + return 0; + } + + @Override + public void writeToParcel(Parcel dest, int flags) { + dest.writeParcelable(this.avatar, flags); + dest.writeLong(this.createdAt != null ? this.createdAt.getTime() : -1); + dest.writeString(this.description); + dest.writeString(this.displayName); + dest.writeInt(this.followersCount); + dest.writeInt(this.followingCount); + dest.writeString(this.host); + dest.writeByte(this.hostRedundancyAllowed ? (byte) 1 : (byte) 0); + dest.writeString(this.id); + dest.writeByte(this.isLocal ? (byte) 1 : (byte) 0); + dest.writeString(this.name); + dest.writeParcelable(this.ownerAccount, flags); + dest.writeString(this.support); + dest.writeLong(this.updatedAt != null ? this.updatedAt.getTime() : -1); + dest.writeString(this.url); + dest.writeList(this.viewsPerDays); + dest.writeString(this.acct); + } + } +} diff --git a/app/src/main/java/app/fedilab/fedilabtube/client/data/CommentData.java b/app/src/main/java/app/fedilab/fedilabtube/client/data/CommentData.java new file mode 100644 index 0000000..835332a --- /dev/null +++ b/app/src/main/java/app/fedilab/fedilabtube/client/data/CommentData.java @@ -0,0 +1,198 @@ +package app.fedilab.fedilabtube.client.data; +/* 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 . */ + +import com.google.gson.annotations.SerializedName; + +import java.util.Date; +import java.util.List; + +@SuppressWarnings("unused") +public class CommentData { + + @SerializedName("total") + public int total; + @SerializedName("data") + public List data; + + + public static class Comment { + + @SerializedName("account") + private AccountData.Account account; + @SerializedName("createdAt") + private Date createdAt; + @SerializedName("description") + private String description; + @SerializedName("displayName") + private String displayName; + @SerializedName("followersCount") + private int followersCount; + @SerializedName("followingCount") + private int followingCount; + @SerializedName("host") + private String host; + @SerializedName("hostRedundancyAllowed") + private boolean hostRedundancyAllowed; + @SerializedName("id") + private String id; + @SerializedName("name") + private String name; + @SerializedName("updatedAt") + private String updatedAt; + @SerializedName("url") + private String url; + + + public AccountData.Account getAccount() { + return account; + } + + public void setAccount(AccountData.Account account) { + this.account = account; + } + + public Date getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Date createdAt) { + this.createdAt = createdAt; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public int getFollowersCount() { + return followersCount; + } + + public void setFollowersCount(int followersCount) { + this.followersCount = followersCount; + } + + public int getFollowingCount() { + return followingCount; + } + + public void setFollowingCount(int followingCount) { + this.followingCount = followingCount; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public boolean isHostRedundancyAllowed() { + return hostRedundancyAllowed; + } + + public void setHostRedundancyAllowed(boolean hostRedundancyAllowed) { + this.hostRedundancyAllowed = hostRedundancyAllowed; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(String updatedAt) { + this.updatedAt = updatedAt; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + } + + public static class NotificationComment { + @SerializedName("id") + private String id; + @SerializedName("threadId") + private String threadId; + @SerializedName("video") + private VideoData.Video video; + @SerializedName("account") + private AccountData.Account account; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getThreadId() { + return threadId; + } + + public void setThreadId(String threadId) { + this.threadId = threadId; + } + + public VideoData.Video getVideo() { + return video; + } + + public void setVideo(VideoData.Video video) { + this.video = video; + } + + public AccountData.Account getAccount() { + return account; + } + + public void setAccount(AccountData.Account account) { + this.account = account; + } + } +} diff --git a/app/src/main/java/app/fedilab/fedilabtube/client/data/InstanceData.java b/app/src/main/java/app/fedilab/fedilabtube/client/data/InstanceData.java new file mode 100644 index 0000000..1069ef4 --- /dev/null +++ b/app/src/main/java/app/fedilab/fedilabtube/client/data/InstanceData.java @@ -0,0 +1,243 @@ +package app.fedilab.fedilabtube.client.data; + +import android.text.SpannableStringBuilder; + +import com.google.gson.annotations.SerializedName; + +import java.util.Date; +import java.util.List; + +@SuppressWarnings("unused") +public class InstanceData { + + @SerializedName("total") + public int total; + @SerializedName("data") + public List data; + + + public static class Instance { + + @SerializedName("autoBlacklistUserVideosEnabled") + private boolean autoBlacklistUserVideosEnabled; + @SerializedName("categories") + private List categories; + @SerializedName("country") + private String country; + @SerializedName("createdAt") + private Date createdAt; + @SerializedName("defaultNSFWPolicy") + private String defaultNSFWPolicy; + @SerializedName("health") + private int health; + @SerializedName("host") + private String host; + @SerializedName("id") + private String id; + @SerializedName("languages") + private List languages; + @SerializedName("name") + private String name; + @SerializedName("shortDescription") + private String shortDescription; + @SerializedName("signupAllowed") + private boolean signupAllowed; + @SerializedName("supportsIPv6") + private boolean supportsIPv6; + @SerializedName("totalInstanceFollowers") + private int totalInstanceFollowers; + @SerializedName("totalInstanceFollowing") + private int totalInstanceFollowing; + @SerializedName("totalLocalVideos") + private int totalLocalVideos; + @SerializedName("totalUsers") + private int totalUsers; + @SerializedName("totalVideos") + private int totalVideos; + @SerializedName("userVideoQuota") + private String userVideoQuota; + @SerializedName("version") + private String version; + @SerializedName("isNSFW") + private boolean isNSFW; + private SpannableStringBuilder spannableStringBuilder; + + public boolean isAutoBlacklistUserVideosEnabled() { + return autoBlacklistUserVideosEnabled; + } + + public void setAutoBlacklistUserVideosEnabled(boolean autoBlacklistUserVideosEnabled) { + this.autoBlacklistUserVideosEnabled = autoBlacklistUserVideosEnabled; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public Date getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Date createdAt) { + this.createdAt = createdAt; + } + + public String getDefaultNSFWPolicy() { + return defaultNSFWPolicy; + } + + public void setDefaultNSFWPolicy(String defaultNSFWPolicy) { + this.defaultNSFWPolicy = defaultNSFWPolicy; + } + + public int getHealth() { + return health; + } + + public void setHealth(int health) { + this.health = health; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getShortDescription() { + return shortDescription; + } + + public void setShortDescription(String shortDescription) { + this.shortDescription = shortDescription; + } + + public boolean isSignupAllowed() { + return signupAllowed; + } + + public void setSignupAllowed(boolean signupAllowed) { + this.signupAllowed = signupAllowed; + } + + public boolean isSupportsIPv6() { + return supportsIPv6; + } + + public void setSupportsIPv6(boolean supportsIPv6) { + this.supportsIPv6 = supportsIPv6; + } + + public int getTotalInstanceFollowers() { + return totalInstanceFollowers; + } + + public void setTotalInstanceFollowers(int totalInstanceFollowers) { + this.totalInstanceFollowers = totalInstanceFollowers; + } + + public int getTotalInstanceFollowing() { + return totalInstanceFollowing; + } + + public void setTotalInstanceFollowing(int totalInstanceFollowing) { + this.totalInstanceFollowing = totalInstanceFollowing; + } + + public int getTotalLocalVideos() { + return totalLocalVideos; + } + + public void setTotalLocalVideos(int totalLocalVideos) { + this.totalLocalVideos = totalLocalVideos; + } + + public int getTotalUsers() { + return totalUsers; + } + + public void setTotalUsers(int totalUsers) { + this.totalUsers = totalUsers; + } + + public int getTotalVideos() { + return totalVideos; + } + + public void setTotalVideos(int totalVideos) { + this.totalVideos = totalVideos; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public boolean isNSFW() { + return isNSFW; + } + + public void setNSFW(boolean NSFW) { + isNSFW = NSFW; + } + + public String getUserVideoQuota() { + return userVideoQuota; + } + + public void setUserVideoQuota(String userVideoQuota) { + this.userVideoQuota = userVideoQuota; + } + + public SpannableStringBuilder getSpannableStringBuilder() { + return spannableStringBuilder; + } + + public void setSpannableStringBuilder(SpannableStringBuilder spannableStringBuilder) { + this.spannableStringBuilder = spannableStringBuilder; + } + + public List getLanguages() { + return languages; + } + + public void setLanguages(List languages) { + this.languages = languages; + } + + public List getCategories() { + return categories; + } + + public void setCategories(List categories) { + this.categories = categories; + } + } + +} + diff --git a/app/src/main/java/app/fedilab/fedilabtube/client/data/NotificationData.java b/app/src/main/java/app/fedilab/fedilabtube/client/data/NotificationData.java new file mode 100644 index 0000000..aeb5879 --- /dev/null +++ b/app/src/main/java/app/fedilab/fedilabtube/client/data/NotificationData.java @@ -0,0 +1,157 @@ +package app.fedilab.fedilabtube.client.data; + +import com.google.gson.annotations.SerializedName; + +import java.util.Date; +import java.util.List; + +import app.fedilab.fedilabtube.client.entities.ActorFollow; +import app.fedilab.fedilabtube.client.entities.VideoAbuse; +import app.fedilab.fedilabtube.client.entities.VideoBlacklist; + +/* 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 . */ +@SuppressWarnings("unused") +public class NotificationData { + + @SerializedName("total") + public int total; + @SerializedName("data") + public List data; + + public static class Notification { + @SerializedName("id") + private String id; + @SerializedName("type") + private int type; + @SerializedName("read") + private boolean read; + @SerializedName("video") + private VideoData.Video video; + @SerializedName("videoImport") + private VideoData.VideoImport videoImport; + @SerializedName("comment") + private CommentData.NotificationComment comment; + @SerializedName("videoAbuse") + private VideoAbuse videoAbuse; + @SerializedName("videoBlacklist") + private VideoBlacklist videoBlacklist; + @SerializedName("account") + private AccountData.Account account; + @SerializedName("actorFollow") + private ActorFollow actorFollow; + @SerializedName("createdAt") + private Date createdAt; + @SerializedName("updatedAt") + private Date updatedAt; + + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public int getType() { + return type; + } + + public void setType(int type) { + this.type = type; + } + + public boolean isRead() { + return read; + } + + public void setRead(boolean read) { + this.read = read; + } + + public VideoData.Video getVideo() { + return video; + } + + public void setVideo(VideoData.Video video) { + this.video = video; + } + + public VideoData.VideoImport getVideoImport() { + return videoImport; + } + + public void setVideoImport(VideoData.VideoImport videoImport) { + this.videoImport = videoImport; + } + + public CommentData.NotificationComment getComment() { + return comment; + } + + public void setComment(CommentData.NotificationComment comment) { + this.comment = comment; + } + + public VideoAbuse getVideoAbuse() { + return videoAbuse; + } + + public void setVideoAbuse(VideoAbuse videoAbuse) { + this.videoAbuse = videoAbuse; + } + + public VideoBlacklist getVideoBlacklist() { + return videoBlacklist; + } + + public void setVideoBlacklist(VideoBlacklist videoBlacklist) { + this.videoBlacklist = videoBlacklist; + } + + public AccountData.Account getAccount() { + return account; + } + + public void setAccount(AccountData.Account account) { + this.account = account; + } + + public ActorFollow getActorFollow() { + return actorFollow; + } + + public void setActorFollow(ActorFollow actorFollow) { + this.actorFollow = actorFollow; + } + + public Date getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Date createdAt) { + this.createdAt = createdAt; + } + + public Date getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Date updatedAt) { + this.updatedAt = updatedAt; + } + } +} diff --git a/app/src/main/java/app/fedilab/fedilabtube/client/data/PlaylistData.java b/app/src/main/java/app/fedilab/fedilabtube/client/data/PlaylistData.java new file mode 100644 index 0000000..25ae469 --- /dev/null +++ b/app/src/main/java/app/fedilab/fedilabtube/client/data/PlaylistData.java @@ -0,0 +1,222 @@ +package app.fedilab.fedilabtube.client.data; +/* 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 . */ + +import android.os.Parcel; +import android.os.Parcelable; + +import com.google.gson.annotations.SerializedName; + +import java.util.Date; +import java.util.List; + +import app.fedilab.fedilabtube.client.entities.Item; + +@SuppressWarnings("unused") +public class PlaylistData { + + @SerializedName("total") + public int total; + @SerializedName("data") + public List data; + + public static class Playlist implements Parcelable { + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + @Override + public Playlist createFromParcel(Parcel source) { + return new Playlist(source); + } + + @Override + public Playlist[] newArray(int size) { + return new Playlist[size]; + } + }; + @SerializedName("id") + private String id; + @SerializedName("createdAt") + private Date createdAt; + @SerializedName("updatedAt") + private Date updatedAt; + @SerializedName("description") + private String description; + @SerializedName("uuid") + private String uuid; + @SerializedName("displayName") + private String displayName; + @SerializedName("isLocal") + private boolean isLocal; + @SerializedName("videoLength") + private long videoLength; + @SerializedName("thumbnailPath") + private String thumbnailPath; + @SerializedName("privacy") + private Item privacy; + @SerializedName("type") + private Item type; + @SerializedName("ownerAccount") + private AccountData.Account ownerAccount; + @SerializedName("videoChannel") + private ChannelData.Channel videoChannel; + + public Playlist() { + } + + protected Playlist(Parcel in) { + this.id = in.readString(); + long tmpCreatedAt = in.readLong(); + this.createdAt = tmpCreatedAt == -1 ? null : new Date(tmpCreatedAt); + long tmpUpdatedAt = in.readLong(); + this.updatedAt = tmpUpdatedAt == -1 ? null : new Date(tmpUpdatedAt); + this.description = in.readString(); + this.uuid = in.readString(); + this.displayName = in.readString(); + this.isLocal = in.readByte() != 0; + this.videoLength = in.readLong(); + this.thumbnailPath = in.readString(); + this.privacy = in.readParcelable(Item.class.getClassLoader()); + this.type = in.readParcelable(Item.class.getClassLoader()); + this.ownerAccount = in.readParcelable(AccountData.Account.class.getClassLoader()); + this.videoChannel = in.readParcelable(ChannelData.Channel.class.getClassLoader()); + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Date getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Date createdAt) { + this.createdAt = createdAt; + } + + public Date getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Date updatedAt) { + this.updatedAt = updatedAt; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public boolean isLocal() { + return isLocal; + } + + public void setLocal(boolean local) { + isLocal = local; + } + + public long getVideoLength() { + return videoLength; + } + + public void setVideoLength(long videoLength) { + this.videoLength = videoLength; + } + + public String getThumbnailPath() { + return thumbnailPath; + } + + public void setThumbnailPath(String thumbnailPath) { + this.thumbnailPath = thumbnailPath; + } + + public Item getPrivacy() { + return privacy; + } + + public void setPrivacy(Item privacy) { + this.privacy = privacy; + } + + public Item getType() { + return type; + } + + public void setType(Item type) { + this.type = type; + } + + public AccountData.Account getOwnerAccount() { + return ownerAccount; + } + + public void setOwnerAccount(AccountData.Account ownerAccount) { + this.ownerAccount = ownerAccount; + } + + public ChannelData.Channel getVideoChannel() { + return videoChannel; + } + + public void setVideoChannel(ChannelData.Channel videoChannel) { + this.videoChannel = videoChannel; + } + + @Override + public int describeContents() { + return 0; + } + + @Override + public void writeToParcel(Parcel dest, int flags) { + dest.writeString(this.id); + dest.writeLong(this.createdAt != null ? this.createdAt.getTime() : -1); + dest.writeLong(this.updatedAt != null ? this.updatedAt.getTime() : -1); + dest.writeString(this.description); + dest.writeString(this.uuid); + dest.writeString(this.displayName); + dest.writeByte(this.isLocal ? (byte) 1 : (byte) 0); + dest.writeLong(this.videoLength); + dest.writeString(this.thumbnailPath); + dest.writeParcelable(this.privacy, flags); + dest.writeParcelable(this.type, flags); + dest.writeParcelable(this.ownerAccount, flags); + dest.writeParcelable(this.videoChannel, flags); + } + } + +} diff --git a/app/src/main/java/app/fedilab/fedilabtube/client/data/VideoData.java b/app/src/main/java/app/fedilab/fedilabtube/client/data/VideoData.java new file mode 100644 index 0000000..7ab78b5 --- /dev/null +++ b/app/src/main/java/app/fedilab/fedilabtube/client/data/VideoData.java @@ -0,0 +1,609 @@ +package app.fedilab.fedilabtube.client.data; +/* 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 . */ + + +import android.content.Context; +import android.content.SharedPreferences; +import android.os.Parcel; +import android.os.Parcelable; + +import com.google.gson.annotations.SerializedName; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import app.fedilab.fedilabtube.client.data.AccountData.Account; +import app.fedilab.fedilabtube.client.entities.File; +import app.fedilab.fedilabtube.client.entities.Item; +import app.fedilab.fedilabtube.helper.Helper; + + +@SuppressWarnings("unused") +public class VideoData { + + @SerializedName("total") + public int total; + @SerializedName("data") + public List