From 431c21e0664393d41f5af6ccad3b6cba3798fb17 Mon Sep 17 00:00:00 2001 From: Thomas Date: Wed, 11 Nov 2020 10:34:28 +0100 Subject: [PATCH] Last fixes --- .../app/fedilab/fedilabtube/FedilabTube.java | 2 +- .../fedilab/fedilabtube/LoginActivity.java | 7 +- .../app/fedilab/fedilabtube/MainActivity.java | 221 +++++++++--------- .../fedilabtube/ManageInstancesActivity.java | 39 +++- .../fedilabtube/MyAccountActivity.java | 47 ++-- .../fedilab/fedilabtube/PeertubeActivity.java | 191 +++++++-------- .../fedilabtube/PeertubeRegisterActivity.java | 29 ++- .../fedilabtube/PeertubeUploadActivity.java | 2 +- .../fedilabtube/ShowAccountActivity.java | 2 +- .../fedilabtube/ShowChannelActivity.java | 2 +- .../fedilabtube/client/PeertubeService.java | 4 +- .../client/RetrofitPeertubeAPI.java | 25 +- .../fedilabtube/client/data/InstanceData.java | 52 +++-- .../fedilabtube/client/data/VideoData.java | 8 +- .../fedilabtube/client/entities/File.java | 54 +++-- .../client/entities/UserSettings.java | 34 +-- .../drawer/AboutInstanceAdapter.java | 32 ++- .../drawer/CommentListAdapter.java | 16 +- .../fedilabtube/drawer/PeertubeAdapter.java | 4 +- .../fragment/SettingsFragment.java | 70 +++--- .../helper/CommentDecorationHelper.java | 11 +- .../fedilab/fedilabtube/helper/Helper.java | 17 +- .../helper/NotificationHelper.java | 1 + .../helper/SwitchAccountHelper.java | 9 +- .../services/RetrieveInfoService.java | 2 +- .../fedilabtube/sqlite/AccountDAO.java | 3 +- .../fedilab/fedilabtube/sqlite/Sqlite.java | 9 +- .../fedilabtube/sqlite/StoredInstanceDAO.java | 67 +++--- .../webview/MastalabWebChromeClient.java | 12 +- .../worker/NotificationsWorker.java | 60 ++--- .../fedilabtube/worker/WorkHelper.java | 2 + .../main/res/layout/drawer_about_instance.xml | 17 +- 32 files changed, 537 insertions(+), 514 deletions(-) diff --git a/app/src/main/java/app/fedilab/fedilabtube/FedilabTube.java b/app/src/main/java/app/fedilab/fedilabtube/FedilabTube.java index ff2be2c..95cf7b2 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/FedilabTube.java +++ b/app/src/main/java/app/fedilab/fedilabtube/FedilabTube.java @@ -41,7 +41,7 @@ public class FedilabTube extends MultiDexApplication { .setMinimumLoggingLevel(android.util.Log.INFO) .build(); WorkManager.initialize(FedilabTube.this, myConfig); - if( interval >= 15 ) { + if (interval >= 15) { WorkHelper.fetchNotifications(this, interval); } } diff --git a/app/src/main/java/app/fedilab/fedilabtube/LoginActivity.java b/app/src/main/java/app/fedilab/fedilabtube/LoginActivity.java index 0454cfd..f95db32 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/LoginActivity.java +++ b/app/src/main/java/app/fedilab/fedilabtube/LoginActivity.java @@ -101,7 +101,6 @@ public class LoginActivity extends AppCompatActivity { } - if (!BuildConfig.full_instances) { binding.loginUid.setOnFocusChangeListener((v, hasFocus) -> { if (!hasFocus) { @@ -142,7 +141,7 @@ public class LoginActivity extends AppCompatActivity { instance = host = binding.loginInstance.getText().toString().trim().toLowerCase(); } - if( instance.startsWith("http")) { + if (instance.startsWith("http")) { try { URL url = new URL(instance); instance = url.getHost(); @@ -151,7 +150,7 @@ public class LoginActivity extends AppCompatActivity { e.printStackTrace(); } } - if (!Patterns.WEB_URL.matcher("https://"+instance).matches()) { + if (!Patterns.WEB_URL.matcher("https://" + instance).matches()) { Toasty.error(LoginActivity.this, getString(R.string.not_valide_instance)).show(); binding.loginButton.setEnabled(true); return; @@ -216,7 +215,7 @@ public class LoginActivity extends AppCompatActivity { oauthParams.setGrant_type("password"); oauthParams.setScope("user"); oauthParams.setUsername(binding.loginUid.getText().toString().trim()); - if( binding.loginPasswd.getText() != null) { + if (binding.loginPasswd.getText() != null) { oauthParams.setPassword(binding.loginPasswd.getText().toString()); } try { diff --git a/app/src/main/java/app/fedilab/fedilabtube/MainActivity.java b/app/src/main/java/app/fedilab/fedilabtube/MainActivity.java index 7e8f2e2..fe431ac 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/MainActivity.java +++ b/app/src/main/java/app/fedilab/fedilabtube/MainActivity.java @@ -83,20 +83,11 @@ public class MainActivity extends AppCompatActivity { public static int PICK_INSTANCE = 5641; public static int PICK_INSTANCE_SURF = 5642; + public static UserMe userMe; final FragmentManager fm = getSupportFragmentManager(); Fragment active; private DisplayVideosFragment recentFragment, locaFragment, trendingFragment, subscriptionFragment, mostLikedFragment; private DisplayOverviewFragment overviewFragment; - public static UserMe userMe; - - public enum TypeOfConnection{ - UNKNOWN, - NORMAL, - SURFING - } - - private TypeOfConnection typeOfConnection; - private final BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = item -> { DisplayVideosFragment displayVideosFragment = null; @@ -130,7 +121,66 @@ public class MainActivity extends AppCompatActivity { return false; } }; + private TypeOfConnection typeOfConnection; + @SuppressLint("ApplySharedPref") + public static void showRadioButtonDialogFullInstances(Activity activity, boolean storeInDb) { + final SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + AlertDialog.Builder alt_bld = new AlertDialog.Builder(activity); + alt_bld.setTitle(R.string.instance_choice); + String instance = Helper.getLiveInstance(activity); + final EditText input = new EditText(activity); + LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.MATCH_PARENT); + input.setLayoutParams(lp); + alt_bld.setView(input); + input.setText(instance); + alt_bld.setPositiveButton(R.string.validate, + (dialog, which) -> new Thread(() -> { + try { + String newInstance = input.getText().toString().trim(); + WellKnownNodeinfo.NodeInfo instanceNodeInfo = new RetrofitPeertubeAPI(activity, newInstance, null).getNodeInfo(); + if (instanceNodeInfo.getSoftware() != null && instanceNodeInfo.getSoftware().getName().trim().toLowerCase().compareTo("peertube") == 0) { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putString(Helper.PREF_INSTANCE, newInstance); + editor.commit(); + if (storeInDb) { + newInstance = newInstance.trim().toLowerCase(); + InstanceData.AboutInstance aboutInstance = new RetrofitPeertubeAPI(activity, newInstance, null).getAboutInstance(); + SQLiteDatabase db = Sqlite.getInstance(activity.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); + new StoredInstanceDAO(activity, db).insertInstance(aboutInstance, newInstance); + activity.runOnUiThread(() -> { + dialog.dismiss(); + Helper.logoutNoRemoval(activity); + }); + } else { + activity.runOnUiThread(() -> { + dialog.dismiss(); + Intent intent = new Intent(activity, MainActivity.class); + activity.startActivity(intent); + }); + } + } else { + activity.runOnUiThread(() -> Toasty.error(activity, activity.getString(R.string.not_valide_instance), Toast.LENGTH_LONG).show()); + } + } catch (Exception e) { + e.printStackTrace(); + } + + }).start()); + alt_bld.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()); + alt_bld.setNeutralButton(R.string.help, (dialog, which) -> { + Intent intent = new Intent(activity, InstancePickerActivity.class); + if (storeInDb) { + activity.startActivityForResult(intent, PICK_INSTANCE_SURF); + } else { + activity.startActivityForResult(intent, PICK_INSTANCE); + } + }); + AlertDialog alert = alt_bld.create(); + alert.show(); + } private void setTitleCustom(int titleRId) { Toolbar toolbar = findViewById(R.id.toolbar); @@ -152,7 +202,7 @@ public class MainActivity extends AppCompatActivity { navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); - if( getSupportActionBar() != null) { + if (getSupportActionBar() != null) { getSupportActionBar().setDisplayShowTitleEnabled(false); } checkIfConnectedUsers(); @@ -225,31 +275,31 @@ public class MainActivity extends AppCompatActivity { if (Helper.isLoggedIn(MainActivity.this)) { navView.inflateMenu(R.menu.bottom_nav_menu_connected); - new Thread(() -> { - final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - String tokenStr = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); - String instance = Helper.getLiveInstance(MainActivity.this); - SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - String instanceShar = sharedpreferences.getString(Helper.PREF_INSTANCE, null); - String userIdShar = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - Account account = new AccountDAO(MainActivity.this, db).getAccountByToken(tokenStr); - if( account == null) { - account = new AccountDAO(MainActivity.this, db).getAccountByIdInstance(userIdShar, instanceShar); - } - if (account != null) { - Account finalAccount = account; - OauthParams oauthParams = new OauthParams(); - oauthParams.setGrant_type("refresh_token"); - oauthParams.setClient_id(account.getClient_id()); - oauthParams.setClient_secret(account.getClient_secret()); - oauthParams.setRefresh_token(account.getRefresh_token()); - oauthParams.setAccess_token(account.getToken()); + new Thread(() -> { + final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + String tokenStr = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); + String instance = Helper.getLiveInstance(MainActivity.this); + SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); + String instanceShar = sharedpreferences.getString(Helper.PREF_INSTANCE, null); + String userIdShar = sharedpreferences.getString(Helper.PREF_KEY_ID, null); + Account account = new AccountDAO(MainActivity.this, db).getAccountByToken(tokenStr); + if (account == null) { + account = new AccountDAO(MainActivity.this, db).getAccountByIdInstance(userIdShar, instanceShar); + } + if (account != null) { + Account finalAccount = account; + OauthParams oauthParams = new OauthParams(); + oauthParams.setGrant_type("refresh_token"); + oauthParams.setClient_id(account.getClient_id()); + oauthParams.setClient_secret(account.getClient_secret()); + oauthParams.setRefresh_token(account.getRefresh_token()); + oauthParams.setAccess_token(account.getToken()); try { Token token = new RetrofitPeertubeAPI(MainActivity.this).manageToken(oauthParams); if (token == null && Helper.instanceOnline(instance)) { runOnUiThread(() -> Helper.logoutCurrentUser(MainActivity.this, finalAccount)); return; - }else if(token == null) { + } else if (token == null) { return; } runOnUiThread(() -> { @@ -290,7 +340,8 @@ public class MainActivity extends AppCompatActivity { runOnUiThread(() -> Helper.logoutCurrentUser(MainActivity.this, finalAccount)); error.printStackTrace(); } - }}).start(); + } + }).start(); } else { navView.inflateMenu(R.menu.bottom_nav_menu); @@ -332,11 +383,11 @@ public class MainActivity extends AppCompatActivity { Pattern link = Pattern.compile("(https?://[\\da-z.-]+\\.[a-z.]{2,10})/videos/watch/(\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12})$"); Matcher matcherLink = link.matcher(query.trim()); if (matcherLink.find()) { - Intent intent = new Intent(MainActivity.this, PeertubeActivity.class); - intent.setData(Uri.parse(query.trim())); - startActivity(intent); - myActionMenuItem.collapseActionView(); - return false; + Intent intent = new Intent(MainActivity.this, PeertubeActivity.class); + intent.setData(Uri.parse(query.trim())); + startActivity(intent); + myActionMenuItem.collapseActionView(); + return false; } Intent intent = new Intent(MainActivity.this, SearchActivity.class); Bundle b = new Bundle(); @@ -370,18 +421,18 @@ public class MainActivity extends AppCompatActivity { Toolbar toolbar = findViewById(R.id.toolbar); ImageButton instances = toolbar.findViewById(R.id.instances); - if(BuildConfig.full_instances && ((Helper.isLoggedIn(MainActivity.this) && typeOfConnection == NORMAL) || typeOfConnection == SURFING)) { + if (BuildConfig.full_instances && ((Helper.isLoggedIn(MainActivity.this) && typeOfConnection == NORMAL) || typeOfConnection == SURFING)) { instances.setVisibility(View.VISIBLE); instances.setOnClickListener(null); - instances.setOnClickListener(v->{ + instances.setOnClickListener(v -> { Intent intent = new Intent(MainActivity.this, ManageInstancesActivity.class); startActivity(intent); - overridePendingTransition( R.anim.slide_in_up, R.anim.slide_out_up ); + overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up); }); - }else { + } else { instances.setVisibility(View.GONE); } - switch (typeOfConnection){ + switch (typeOfConnection) { case UNKNOWN: instanceItem.setVisible(false); accountItem.setVisible(false); @@ -438,14 +489,14 @@ public class MainActivity extends AppCompatActivity { return true; } - private void checkIfConnectedUsers(){ + private void checkIfConnectedUsers() { new Thread(() -> { try { typeOfConnection = NORMAL; - if( !Helper.isLoggedIn(MainActivity.this)) { + if (!Helper.isLoggedIn(MainActivity.this)) { SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); List accounts = new AccountDAO(MainActivity.this, db).getAllAccount(); - if( accounts != null && accounts.size() > 0 ) { + if (accounts != null && accounts.size() > 0) { //The user is not authenticated and there accounts in db. That means the user is surfing some other instances typeOfConnection = TypeOfConnection.SURFING; } @@ -472,7 +523,7 @@ public class MainActivity extends AppCompatActivity { startActivity(intent); } else if (item.getItemId() == R.id.action_account) { Intent intent; - if( typeOfConnection == SURFING) { + if (typeOfConnection == SURFING) { SwitchAccountHelper.switchDialog(MainActivity.this, false); } else { if (Helper.isLoggedIn(MainActivity.this)) { @@ -590,68 +641,6 @@ public class MainActivity extends AppCompatActivity { alert.show(); } - - - @SuppressLint("ApplySharedPref") - public static void showRadioButtonDialogFullInstances(Activity activity, boolean storeInDb) { - final SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - AlertDialog.Builder alt_bld = new AlertDialog.Builder(activity); - alt_bld.setTitle(R.string.instance_choice); - String instance = Helper.getLiveInstance(activity); - final EditText input = new EditText(activity); - LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( - LinearLayout.LayoutParams.MATCH_PARENT, - LinearLayout.LayoutParams.MATCH_PARENT); - input.setLayoutParams(lp); - alt_bld.setView(input); - input.setText(instance); - alt_bld.setPositiveButton(R.string.validate, - (dialog, which) -> new Thread(() -> { - try { - String newInstance = input.getText().toString().trim(); - WellKnownNodeinfo.NodeInfo instanceNodeInfo = new RetrofitPeertubeAPI(activity, newInstance, null).getNodeInfo(); - if (instanceNodeInfo.getSoftware() != null && instanceNodeInfo.getSoftware().getName().trim().toLowerCase().compareTo("peertube") == 0) { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putString(Helper.PREF_INSTANCE, newInstance); - editor.commit(); - if( storeInDb) { - newInstance = newInstance.trim().toLowerCase(); - InstanceData.AboutInstance aboutInstance = new RetrofitPeertubeAPI(activity, newInstance, null).getAboutInstance(); - SQLiteDatabase db = Sqlite.getInstance(activity.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - new StoredInstanceDAO(activity, db).insertInstance(aboutInstance, newInstance); - activity.runOnUiThread(() -> { - dialog.dismiss(); - Helper.logoutNoRemoval(activity); - }); - }else { - activity.runOnUiThread(() -> { - dialog.dismiss(); - Intent intent = new Intent(activity, MainActivity.class); - activity.startActivity(intent); - }); - } - } else { - activity.runOnUiThread(() -> Toasty.error(activity, activity.getString(R.string.not_valide_instance), Toast.LENGTH_LONG).show()); - } - } catch (Exception e) { - e.printStackTrace(); - } - - }).start()); - alt_bld.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()); - alt_bld.setNeutralButton(R.string.help, (dialog, which) -> { - Intent intent = new Intent(activity, InstancePickerActivity.class); - if(storeInDb) { - activity.startActivityForResult(intent, PICK_INSTANCE_SURF); - }else{ - activity.startActivityForResult(intent, PICK_INSTANCE); - } - }); - AlertDialog alert = alt_bld.create(); - alert.show(); - } - - @SuppressLint("ApplySharedPref") @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { @@ -662,17 +651,15 @@ public class MainActivity extends AppCompatActivity { SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(Helper.PREF_INSTANCE, String.valueOf(data.getData())); editor.commit(); - finish(); - } - }else if (requestCode == PICK_INSTANCE_SURF && resultCode == Activity.RESULT_OK) { - if (data != null && data.getData() != null) { - final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putString(Helper.PREF_INSTANCE, String.valueOf(data.getData())); - editor.commit(); - finish(); } } } + + + public enum TypeOfConnection { + UNKNOWN, + NORMAL, + SURFING + } } \ No newline at end of file diff --git a/app/src/main/java/app/fedilab/fedilabtube/ManageInstancesActivity.java b/app/src/main/java/app/fedilab/fedilabtube/ManageInstancesActivity.java index ed99941..c5963b4 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/ManageInstancesActivity.java +++ b/app/src/main/java/app/fedilab/fedilabtube/ManageInstancesActivity.java @@ -17,20 +17,26 @@ package app.fedilab.fedilabtube; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; +import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; +import android.os.Handler; import android.view.MenuItem; import android.view.View; import androidx.appcompat.app.AppCompatActivity; import androidx.lifecycle.ViewModelProvider; +import androidx.recyclerview.widget.LinearLayoutManager; - +import java.util.ArrayList; import java.util.List; +import app.fedilab.fedilabtube.client.RetrofitPeertubeAPI; import app.fedilab.fedilabtube.client.data.InstanceData; import app.fedilab.fedilabtube.databinding.ActivityManageInstancesBinding; import app.fedilab.fedilabtube.drawer.AboutInstanceAdapter; import app.fedilab.fedilabtube.helper.Helper; +import app.fedilab.fedilabtube.sqlite.Sqlite; +import app.fedilab.fedilabtube.sqlite.StoredInstanceDAO; import app.fedilab.fedilabtube.viewmodel.InfoInstanceVM; import static app.fedilab.fedilabtube.MainActivity.PICK_INSTANCE_SURF; @@ -39,7 +45,9 @@ import static app.fedilab.fedilabtube.MainActivity.showRadioButtonDialogFullInst public class ManageInstancesActivity extends AppCompatActivity implements AboutInstanceAdapter.AllInstancesRemoved { - private ActivityManageInstancesBinding binding; + private ActivityManageInstancesBinding binding; + private List aboutInstances; + private AboutInstanceAdapter aboutInstanceAdapter; @Override protected void onCreate(Bundle savedInstanceState) { @@ -54,34 +62,43 @@ public class ManageInstancesActivity extends AppCompatActivity implements AboutI binding.loader.setVisibility(View.VISIBLE); binding.noAction.setVisibility(View.GONE); binding.lvInstances.setVisibility(View.GONE); - binding.actionButton.setOnClickListener(v-> showRadioButtonDialogFullInstances(ManageInstancesActivity.this, true)); - + binding.actionButton.setOnClickListener(v -> showRadioButtonDialogFullInstances(ManageInstancesActivity.this, true)); + aboutInstances = new ArrayList<>(); + aboutInstanceAdapter = new AboutInstanceAdapter(this.aboutInstances); + aboutInstanceAdapter.allInstancesRemoved = this; + binding.lvInstances.setAdapter(aboutInstanceAdapter); + LinearLayoutManager layoutManager + = new LinearLayoutManager(ManageInstancesActivity.this); + binding.lvInstances.setLayoutManager(layoutManager); InfoInstanceVM viewModelInfoInstance = new ViewModelProvider(ManageInstancesActivity.this).get(InfoInstanceVM.class); viewModelInfoInstance.getInstances().observe(ManageInstancesActivity.this, this::manageVIewInfoInstance); } private void manageVIewInfoInstance(List aboutInstances) { binding.loader.setVisibility(View.GONE); - if( aboutInstances == null || aboutInstances.size() == 0) { + if (aboutInstances == null || aboutInstances.size() == 0) { binding.noAction.setVisibility(View.VISIBLE); binding.lvInstances.setVisibility(View.GONE); return; } binding.noAction.setVisibility(View.GONE); binding.lvInstances.setVisibility(View.VISIBLE); + this.aboutInstances.addAll(aboutInstances); + aboutInstanceAdapter.notifyItemRangeInserted(0, aboutInstances.size()); } @Override public void onBackPressed() { super.onBackPressed(); - overridePendingTransition( R.anim.slide_out_up, R.anim.slide_in_up_down ); + overridePendingTransition(R.anim.slide_out_up, R.anim.slide_in_up_down); } + @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { finish(); - overridePendingTransition( R.anim.slide_out_up, R.anim.slide_in_up_down ); + overridePendingTransition(R.anim.slide_out_up, R.anim.slide_in_up_down); return true; } return super.onOptionsItemSelected(item); @@ -94,7 +111,13 @@ public class ManageInstancesActivity extends AppCompatActivity implements AboutI super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_INSTANCE_SURF && resultCode == Activity.RESULT_OK) { if (data != null && data.getData() != null) { - Helper.logoutNoRemoval(ManageInstancesActivity.this); + new Thread(() -> { + String newInstance = data.getData().toString().trim().toLowerCase(); + InstanceData.AboutInstance aboutInstance = new RetrofitPeertubeAPI(ManageInstancesActivity.this, newInstance, null).getAboutInstance(); + SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); + new StoredInstanceDAO(ManageInstancesActivity.this, db).insertInstance(aboutInstance, newInstance); + runOnUiThread(() -> new Handler().post(() -> Helper.logoutNoRemoval(ManageInstancesActivity.this))); + }).start(); } } } diff --git a/app/src/main/java/app/fedilab/fedilabtube/MyAccountActivity.java b/app/src/main/java/app/fedilab/fedilabtube/MyAccountActivity.java index 39f49f6..e554a8d 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/MyAccountActivity.java +++ b/app/src/main/java/app/fedilab/fedilabtube/MyAccountActivity.java @@ -13,6 +13,7 @@ package app.fedilab.fedilabtube; * * You should have received a copy of the GNU General Public License along with TubeLab; if not, * see . */ + import android.Manifest; import android.app.Activity; import android.content.Context; @@ -59,10 +60,10 @@ import static app.fedilab.fedilabtube.worker.WorkHelper.NOTIFICATION_WORKER; public class MyAccountActivity extends AppCompatActivity { - ActivityMyAccountSettingsBinding binding; private static final int PICK_IMAGE = 466; + ActivityMyAccountSettingsBinding binding; private Uri inputData; - private String fileName; + private String fileName; private NotificationSettings notificationSettings; @Override @@ -74,11 +75,11 @@ public class MyAccountActivity extends AppCompatActivity { if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); - if( MainActivity.userMe == null) { - finish(); - return; + if (MainActivity.userMe == null) { + finish(); + return; } - setTitle(String.format("@%s",MainActivity.userMe.getUsername())); + setTitle(String.format("@%s", MainActivity.userMe.getUsername())); binding.displayname.setText(MainActivity.userMe.getAccount().getDisplayName()); binding.description.setText(MainActivity.userMe.getAccount().getDescription()); @@ -93,7 +94,7 @@ public class MyAccountActivity extends AppCompatActivity { initializeValues(notificationSettings.getNewCommentOnMyVideo(), binding.notifNewCommentApp, binding.notifNewCommentMail); initializeValues(notificationSettings.getNewVideoFromSubscription(), binding.notifNewVideoApp, binding.notifNewVideoMail); - Helper.loadGiF(MyAccountActivity.this, MainActivity.userMe.getAccount().getAvatar()!=null?MainActivity.userMe.getAccount().getAvatar().getPath():null, binding.profilePicture); + Helper.loadGiF(MyAccountActivity.this, MainActivity.userMe.getAccount().getAvatar() != null ? MainActivity.userMe.getAccount().getAvatar().getPath() : null, binding.profilePicture); String[] refresh_array = getResources().getStringArray(R.array.refresh_time); ArrayAdapter refreshArray = new ArrayAdapter<>(MyAccountActivity.this, @@ -132,7 +133,7 @@ public class MyAccountActivity extends AppCompatActivity { editor.putInt(Helper.NOTIFICATION_INTERVAL, time); editor.apply(); WorkManager.getInstance(getApplicationContext()).cancelAllWorkByTag(NOTIFICATION_WORKER); - if( time > 0 ) { + if (time > 0) { WorkHelper.fetchNotifications(getApplication(), time); } @@ -169,7 +170,7 @@ public class MyAccountActivity extends AppCompatActivity { } binding.refreshTime.setSelection(position, false); - binding.selectFile.setOnClickListener(v->{ + binding.selectFile.setOnClickListener(v -> { if (ContextCompat.checkSelfPermission(MyAccountActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MyAccountActivity.this, @@ -204,13 +205,13 @@ public class MyAccountActivity extends AppCompatActivity { new Thread(() -> { UserSettings userSettings = new UserSettings(); userSettings.setNotificationSettings(notificationSettings); - if( binding.displayname.getText() != null) { + if (binding.displayname.getText() != null) { userSettings.setDisplayName(binding.displayname.getText().toString().trim()); } - if( binding.description.getText() != null) { + if (binding.description.getText() != null) { userSettings.setDescription(binding.description.getText().toString().trim()); } - if( inputData != null ) { + if (inputData != null) { userSettings.setAvatarfile(inputData); userSettings.setFileName(fileName); } @@ -219,7 +220,7 @@ public class MyAccountActivity extends AppCompatActivity { UserMe.AvatarResponse avatarResponse = api.updateUser(userSettings); MainActivity.userMe.getAccount().setDisplayName(binding.displayname.getText().toString().trim()); MainActivity.userMe.getAccount().setDescription(binding.description.getText().toString().trim()); - if( avatarResponse != null && avatarResponse.getAvatar() != null ) { + if (avatarResponse != null && avatarResponse.getAvatar() != null) { MainActivity.userMe.getAccount().setAvatar(avatarResponse.getAvatar()); } @@ -329,29 +330,29 @@ public class MyAccountActivity extends AppCompatActivity { }); } - private int getNewAppCheckedValue(boolean checked, SwitchCompat email){ + private int getNewAppCheckedValue(boolean checked, SwitchCompat email) { int newValue; - if( checked && email.isChecked()) { + if (checked && email.isChecked()) { newValue = 3; - }else if( !checked && email.isChecked()) { + } else if (!checked && email.isChecked()) { newValue = 2; - } else if( checked && !email.isChecked()) { + } else if (checked && !email.isChecked()) { newValue = 1; - }else { + } else { newValue = 0; } return newValue; } - private int getNewMailCheckedValue(boolean checked, SwitchCompat app){ + private int getNewMailCheckedValue(boolean checked, SwitchCompat app) { int newValue; - if( checked && app.isChecked()) { + if (checked && app.isChecked()) { newValue = 3; - }else if( !checked && app.isChecked()) { + } else if (!checked && app.isChecked()) { newValue = 1; - } else if( checked && !app.isChecked()) { + } else if (checked && !app.isChecked()) { newValue = 2; - }else { + } else { newValue = 0; } return newValue; diff --git a/app/src/main/java/app/fedilab/fedilabtube/PeertubeActivity.java b/app/src/main/java/app/fedilab/fedilabtube/PeertubeActivity.java index 65d1f1a..00c9f27 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/PeertubeActivity.java +++ b/app/src/main/java/app/fedilab/fedilabtube/PeertubeActivity.java @@ -152,6 +152,7 @@ import static com.google.android.exoplayer2.Player.MEDIA_ITEM_TRANSITION_REASON_ public class PeertubeActivity extends AppCompatActivity implements CommentListAdapter.AllCommentRemoved, Player.EventListener, VideoListener, TorrentListener { public static String video_id; + public static List playedVideos = new ArrayList<>(); private String peertubeInstance, videoUuid; private FullScreenMediaController.fullscreen fullscreen; private ImageView fullScreenIcon; @@ -175,16 +176,25 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd private List commentsThread; private BroadcastReceiver mPowerKeyReceiver = null; private boolean isPlayInMinimized; - public static List playedVideos = new ArrayList<>(); private VideoData.Video nextVideo; private TorrentStream torrentStream; private String show_more_content; + private videoOrientation videoOrientationType; + + public static void hideKeyboard(Activity activity) { + if (activity != null && activity.getWindow() != null) { + activity.getWindow().getDecorView(); + InputMethodManager imm = (InputMethodManager) activity.getSystemService(INPUT_METHOD_SERVICE); + assert imm != null; + imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0); + } + } @Override public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) { - if(width < height){ + if (width < height) { videoOrientationType = videoOrientation.PORTRAIT; - }else{ + } else { videoOrientationType = videoOrientation.LANDSCAPE; } } @@ -213,22 +223,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd } @Override - public void onStreamStopped() {} - - enum videoOrientation { - LANDSCAPE, - PORTRAIT - } - - private videoOrientation videoOrientationType; - - public static void hideKeyboard(Activity activity) { - if (activity != null && activity.getWindow() != null) { - activity.getWindow().getDecorView(); - InputMethodManager imm = (InputMethodManager) activity.getSystemService(INPUT_METHOD_SERVICE); - assert imm != null; - imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0); - } + public void onStreamStopped() { } @Override @@ -286,12 +281,12 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd manageIntentUrl(intent); - binding.peertubeDescriptionMore.setOnClickListener(v->{ - if( show_more_content != null && peertube != null) { - if( binding.peertubeDescriptionMore.getText().toString().compareTo(getString(R.string.show_more)) == 0) { + binding.peertubeDescriptionMore.setOnClickListener(v -> { + if (show_more_content != null && peertube != null) { + if (binding.peertubeDescriptionMore.getText().toString().compareTo(getString(R.string.show_more)) == 0) { binding.peertubeDescriptionMore.setText(getString(R.string.show_less)); binding.peertubeDescription.setText(show_more_content); - }else{ + } else { binding.peertubeDescriptionMore.setText(getString(R.string.show_more)); binding.peertubeDescription.setText(peertube.getDescription()); } @@ -327,7 +322,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd binding.peertubeInformationContainer.setVisibility(View.GONE); if (videoOrientationType == videoOrientation.LANDSCAPE) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); - }else { + } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } } else { @@ -371,11 +366,11 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd public void onAnimationEnd() { binding.mediaVideo.setVisibility(View.GONE); } - }) .playerView(binding.doubleTapPlayerView).seekSeconds(10); + }).playerView(binding.doubleTapPlayerView).seekSeconds(10); binding.doubleTapPlayerView.setPlayer(player); binding.doubleTapPlayerView.controller(binding.mediaVideo); - if( player != null) - binding.mediaVideo.player(player); + if (player != null) + binding.mediaVideo.player(player); } flag_loading = true; comments = new ArrayList<>(); @@ -411,26 +406,25 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd playVideo(); } registBroadcastReceiver(); - if( autoFullscreen && autoPlay) { + if (autoFullscreen && autoPlay) { openFullscreenDialog(); if (videoOrientationType == videoOrientation.LANDSCAPE) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); - }else { + } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } } - binding.postCommentButton.setOnClickListener(v-> openPostComment(null, 0)); + binding.postCommentButton.setOnClickListener(v -> openPostComment(null, 0)); } - private void manageVIewVideos(APIResponse apiResponse) { if (apiResponse == null || apiResponse.getPeertubes() == null || apiResponse.getPeertubes().size() == 0) { playVideo(); return; } peertube = apiResponse.getPeertubes().get(0); - if( peertube.getUserHistory() != null) { - player.seekTo(peertube.getUserHistory().getCurrentTime()*1000); + if (peertube.getUserHistory() != null) { + player.seekTo(peertube.getUserHistory().getCurrentTime() * 1000); } sepiaSearch = false; playVideo(); @@ -459,7 +453,6 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd } } - public void manageVIewCommentReply(Comment comment, APIResponse apiResponse) { if (apiResponse == null || apiResponse.getError() != null || apiResponse.getCommentThreadData() == null) { if (apiResponse == null || apiResponse.getError() == null) @@ -504,7 +497,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd if (b != null) { peertubeInstance = b.getString("peertube_instance", Helper.getLiveInstance(PeertubeActivity.this)); videoUuid = b.getString("video_uuid", null); - if( comments != null && comments.size() > 0) { + if (comments != null && comments.size() > 0) { int number = comments.size(); comments.clear(); commentListAdapter.notifyItemRangeRemoved(0, number); @@ -515,14 +508,14 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd } private void manageIntentUrl(Intent intent) { - if(intent.getData() != null) { //Comes from a link + if (intent.getData() != null) { //Comes from a link String url = intent.getData().toString(); Pattern link = Pattern.compile("(https?://[\\da-z.-]+\\.[a-z.]{2,10})/videos/watch/(\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12})$"); Matcher matcherLink = link.matcher(url); if (matcherLink.find()) { String instance = matcherLink.group(1); String uuid = matcherLink.group(2); - if(instance != null && uuid != null) { + if (instance != null && uuid != null) { peertubeInstance = instance.replace("https://", "").replace("http://", ""); sepiaSearch = true; // Sepia search flag is used because, at this time we don't know if the video is federated. videoUuid = uuid; @@ -531,11 +524,11 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd peertube.setEmbedUrl(url); SearchVM viewModelSearch = new ViewModelProvider(PeertubeActivity.this).get(SearchVM.class); viewModelSearch.getVideos("0", peertube.getEmbedUrl()).observe(PeertubeActivity.this, this::manageVIewVideos); - }else { + } else { Helper.forwardToAnotherApp(PeertubeActivity.this, intent); finish(); } - }else{ + } else { Helper.forwardToAnotherApp(PeertubeActivity.this, intent); finish(); } @@ -554,14 +547,14 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd } show_more_content = null; binding.peertubeDescriptionMore.setVisibility(View.GONE); - if( autoFullscreen && autoPlay) { + if (autoFullscreen && autoPlay) { fullscreen = FullScreenMediaController.fullscreen.ON; setFullscreen(FullScreenMediaController.fullscreen.ON); fullScreenMode = true; openFullscreenDialog(); if (videoOrientationType == videoOrientation.LANDSCAPE) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); - }else { + } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } } else { @@ -581,11 +574,11 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd VideoData.Description description = api.getVideoDescription(videoUuid); Handler mainHandler = new Handler(Looper.getMainLooper()); Runnable myRunnable = () -> { - if( description == null) { + if (description == null) { binding.peertubeDescriptionMore.setVisibility(View.GONE); show_more_content = null; - }else{ - if( !PeertubeActivity.this.isFinishing()) { + } else { + if (!PeertubeActivity.this.isFinishing()) { if (peertube != null && peertube.getDescription() != null && description.getDescription().compareTo(peertube.getDescription()) > 0) { binding.peertubeDescriptionMore.setVisibility(View.VISIBLE); show_more_content = description.getDescription(); @@ -618,7 +611,6 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd } } - @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { @@ -676,7 +668,6 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd this.fullscreen = fullscreen; } - public void manageCaptions(APIResponse apiResponse) { if (apiResponse == null || (apiResponse.getError() != null) || apiResponse.getCaptions() == null || apiResponse.getCaptions().size() == 0) { return; @@ -684,14 +675,13 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd captions = apiResponse.getCaptions(); } - public void manageNextVideos(APIResponse apiResponse) { if (apiResponse == null || apiResponse.getError() != null || apiResponse.getPeertubes() == null || apiResponse.getPeertubes().size() == 0) { return; } List suggestedVideos = apiResponse.getPeertubes(); - for(VideoData.Video video: suggestedVideos) { - if(!playedVideos.contains(video.getId())){ + for (VideoData.Video video : suggestedVideos) { + if (!playedVideos.contains(video.getId())) { TimelineVM feedsViewModel = new ViewModelProvider(PeertubeActivity.this).get(TimelineVM.class); feedsViewModel.getVideo(null, suggestedVideos.get(0).getUuid(), false).observe(PeertubeActivity.this, this::nextVideoDetails); return; @@ -705,7 +695,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd return; } int i = 0; - while (i < (apiResponse.getPeertubes().size()-1) && playedVideos.contains(apiResponse.getPeertubes().get(i).getId())) { + while (i < (apiResponse.getPeertubes().size() - 1) && playedVideos.contains(apiResponse.getPeertubes().get(i).getId())) { i++; } nextVideo = apiResponse.getPeertubes().get(i); @@ -713,7 +703,6 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd player.addMediaItem(mediaItem); } - @SuppressLint("ClickableViewAccessibility") public void manageVIewVideo(APIResponse apiResponse) { if (apiResponse == null || (apiResponse.getError() != null) || apiResponse.getPeertubes() == null || apiResponse.getPeertubes().size() == 0) { @@ -727,12 +716,12 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd return; } long position = -1; - if( peertube.getUserHistory() != null) { + if (peertube.getUserHistory() != null) { position = peertube.getUserHistory().getCurrentTime() * 1000; } peertube = apiResponse.getPeertubes().get(0); - if( peertube.getTags() != null && peertube.getTags().size() > 0) { + if (peertube.getTags() != null && peertube.getTags().size() > 0) { SearchVM searchViewModel = new ViewModelProvider(PeertubeActivity.this).get(SearchVM.class); searchViewModel.searchNextVideos(peertube.getTags()).observe(PeertubeActivity.this, this::manageNextVideos); } @@ -777,8 +766,8 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd binding.peertubeDislikeCount.setText(Helper.withSuffix(peertube.getDislikes())); binding.peertubeLikeCount.setText(Helper.withSuffix(peertube.getLikes())); binding.peertubeViewCount.setText(Helper.withSuffix(peertube.getViews())); - loadGiF(PeertubeActivity.this,peertube.getChannel().getAvatar()!=null?peertube.getChannel().getAvatar().getPath():null, binding.ppChannel); - binding.ppChannel.setOnClickListener(v->{ + loadGiF(PeertubeActivity.this, peertube.getChannel().getAvatar() != null ? peertube.getChannel().getAvatar().getPath() : null, binding.ppChannel); + binding.ppChannel.setOnClickListener(v -> { Intent intent = new Intent(PeertubeActivity.this, ShowChannelActivity.class); Bundle b = new Bundle(); b.putParcelable("channel", peertube.getChannel()); @@ -857,8 +846,8 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd binding.loader.setVisibility(View.GONE); startStream( apiResponse.getPeertubes().get(0).getFileUrl(null, PeertubeActivity.this), - apiResponse.getPeertubes().get(0).getStreamingPlaylists().size()>0?apiResponse.getPeertubes().get(0).getStreamingPlaylists().get(0).getPlaylistUrl():null, - autoPlay,position, null, null); + apiResponse.getPeertubes().get(0).getStreamingPlaylists().size() > 0 ? apiResponse.getPeertubes().get(0).getStreamingPlaylists().get(0).getPlaylistUrl() : null, + autoPlay, position, null, null); player.prepare(); player.setPlayWhenReady(autoPlay); } @@ -1005,11 +994,11 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd private void startStream(String videoURL, String streamingPlaylistsURLS, boolean autoPlay, long position, Uri subtitles, String lang) { if (videoURL != null) { - if( videoURL.endsWith(".torrent")) { + if (videoURL.endsWith(".torrent")) { torrentStream.startStream(videoURL); return; - }else { + } else { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int video_cache = sharedpreferences.getInt(Helper.SET_VIDEO_CACHE, Helper.DEFAULT_VIDEO_CACHE_MB); ProgressiveMediaSource videoSource; @@ -1019,7 +1008,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd Util.getUserAgent(PeertubeActivity.this, null), null); if (subtitles != null) { - MediaItem.Subtitle mediaSubtitle = new MediaItem.Subtitle(subtitles, MimeTypes.TEXT_VTT, lang); + MediaItem.Subtitle mediaSubtitle = new MediaItem.Subtitle(subtitles, MimeTypes.TEXT_VTT, lang); subtitleSource = new SingleSampleMediaSource.Factory(dataSourceFactory).createMediaSource(mediaSubtitle, C.TIME_UNSET); } MediaItem mediaItem = new MediaItem.Builder().setUri(videoURL).build(); @@ -1030,7 +1019,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd videoSource = new ProgressiveMediaSource.Factory(cacheDataSourceFactory) .createMediaSource(mediaItem); if (subtitles != null) { - MediaItem.Subtitle mediaSubtitle = new MediaItem.Subtitle(subtitles, MimeTypes.TEXT_VTT, lang, Format.NO_VALUE); + MediaItem.Subtitle mediaSubtitle = new MediaItem.Subtitle(subtitles, MimeTypes.TEXT_VTT, lang, Format.NO_VALUE); subtitleSource = new SingleSampleMediaSource.Factory(cacheDataSourceFactory).createMediaSource(mediaSubtitle, C.TIME_UNSET); } } @@ -1038,7 +1027,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd MergingMediaSource mergedSource = new MergingMediaSource(videoSource, subtitleSource); player.setMediaSource(mergedSource); - }else { + } else { player.setMediaSource(videoSource); } } @@ -1049,7 +1038,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd player.setMediaSource(hlsMediaSource); } player.prepare(); - if( position > 0) { + if (position > 0) { player.seekTo(0, position); } player.setPlayWhenReady(autoPlay); @@ -1072,7 +1061,6 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd change(); } - @Override public void onDestroy() { super.onDestroy(); @@ -1080,7 +1068,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd if (player != null) { player.release(); } - if( torrentStream != null && torrentStream.isStreaming()) { + if (torrentStream != null && torrentStream.isStreaming()) { torrentStream.stopStream(); } unregisterReceiver(); @@ -1107,12 +1095,12 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd @Override protected void onPause() { super.onPause(); - if( player != null) { - updateHistory(player.getCurrentPosition()/1000); + if (player != null) { + updateHistory(player.getCurrentPosition() / 1000); } if (player != null && (!isPlayInMinimized || !playInMinimized)) { player.setPlayWhenReady(false); - }else if (playInMinimized) { + } else if (playInMinimized) { enterVideoMode(); } } @@ -1128,7 +1116,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd String strAction = intent.getAction(); if (strAction.equals(Intent.ACTION_SCREEN_OFF)) { if (player != null && isPlayInMinimized) { - if( !sharedpreferences.getBoolean(getString(R.string.set_play_screen_lock_choice), false)) { + if (!sharedpreferences.getBoolean(getString(R.string.set_play_screen_lock_choice), false)) { player.setPlayWhenReady(false); } } @@ -1153,7 +1141,6 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd } } - @RequiresApi(api = Build.VERSION_CODES.N) @Override public void onUserLeaveHint() { @@ -1175,14 +1162,13 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd } } - @Override public void onBackPressed() { - if(binding.postComment.getVisibility() == View.VISIBLE){ + if (binding.postComment.getVisibility() == View.VISIBLE) { closePostComment(); } else if (binding.replyThread.getVisibility() == View.VISIBLE) { closeCommentThread(); - } else { + } else { if (playInMinimized && player != null) { enterVideoMode(); } else { @@ -1191,7 +1177,6 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd } } - @Override public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode, Configuration newConfig) { if (isInPictureInPictureMode) { @@ -1205,7 +1190,6 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd } } - public void displayResolution() { AlertDialog.Builder builderSingle = new AlertDialog.Builder(PeertubeActivity.this); builderSingle.setTitle(R.string.pickup_resolution); @@ -1235,7 +1219,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd binding.loader.setVisibility(View.GONE); startStream( peertube.getFileUrl(res, PeertubeActivity.this), - peertube.getStreamingPlaylists().size()>0?peertube.getStreamingPlaylists().get(0).getPlaylistUrl():null, + peertube.getStreamingPlaylists().size() > 0 ? peertube.getStreamingPlaylists().get(0).getPlaylistUrl() : null, true, position, null, null); } @@ -1243,15 +1227,14 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd builderSingle.show(); } - private void initFullscreenDialog() { fullScreenDialog = new Dialog(this, android.R.style.Theme_Black_NoTitleBar_Fullscreen) { public void onBackPressed() { - if( player != null && player.isPlaying() && fullScreenMode) { + if (player != null && player.isPlaying() && fullScreenMode) { player.setPlayWhenReady(false); } - if( fullScreenMode) { + if (fullScreenMode) { closeFullscreenDialog(); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); Handler handler = new Handler(); @@ -1272,16 +1255,12 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd fullScreenDialog.show(); } - - - - public void openCommentThread(Comment comment) { CommentVM commentViewModel = new ViewModelProvider(PeertubeActivity.this).get(CommentVM.class); binding.peertubeReply.setVisibility(View.GONE); - commentViewModel.getRepliesComment(videoUuid, comment.getId()).observe(PeertubeActivity.this, apiResponse->manageVIewCommentReply(comment, apiResponse)); + commentViewModel.getRepliesComment(videoUuid, comment.getId()).observe(PeertubeActivity.this, apiResponse -> manageVIewCommentReply(comment, apiResponse)); binding.replyThread.setVisibility(View.VISIBLE); @@ -1310,14 +1289,14 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd private void sendComment(Comment comment, int position) { if (isLoggedIn(PeertubeActivity.this) && !sepiaSearch) { - if( comment == null) { + if (comment == null) { String commentStr = binding.addCommentWrite.getText().toString(); if (commentStr.trim().length() > 0) { PostActionsVM viewModelComment = new ViewModelProvider(PeertubeActivity.this).get(PostActionsVM.class); viewModelComment.comment(ADD_COMMENT, peertube.getId(), null, commentStr).observe(PeertubeActivity.this, apiResponse1 -> manageVIewPostActions(ADD_COMMENT, 0, apiResponse1)); binding.addCommentWrite.setText(""); } - }else{ + } else { String commentView = binding.addCommentWrite.getText().toString(); if (commentView.trim().length() > 0) { PostActionsVM viewModelComment = new ViewModelProvider(PeertubeActivity.this).get(PostActionsVM.class); @@ -1359,9 +1338,8 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd binding.replyThread.startAnimation(animate); } - public void openPostComment(Comment comment, int position) { - if( comment != null) { + if (comment != null) { binding.replyContent.setVisibility(View.VISIBLE); Account account = comment.getAccount(); Helper.loadGiF(PeertubeActivity.this, account.getAvatar() != null ? account.getAvatar().getPath() : null, binding.commentAccountProfile); @@ -1374,7 +1352,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd commentSpan = Html.fromHtml(comment.getText()); binding.commentContent.setText(commentSpan); binding.commentDate.setText(Helper.dateDiff(PeertubeActivity.this, comment.getCreatedAt())); - }else{ + } else { binding.replyContent.setVisibility(View.GONE); } binding.postComment.setVisibility(View.VISIBLE); @@ -1402,13 +1380,13 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd }); animateComment.setDuration(500); binding.postComment.startAnimation(animateComment); - if( comment != null) { + if (comment != null) { binding.addCommentWrite.setText(String.format("@%s ", comment.getAccount().getAcct())); binding.addCommentWrite.setSelection(binding.addCommentWrite.getText().length()); } binding.send.setOnClickListener(null); - binding.send.setOnClickListener(v-> sendComment(comment, position)); + binding.send.setOnClickListener(v -> sendComment(comment, position)); } private void closePostComment() { @@ -1478,7 +1456,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd openFullscreenDialog(); if (videoOrientationType == videoOrientation.LANDSCAPE) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); - }else { + } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } } else { @@ -1490,12 +1468,12 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd } }); ImageButton playButton = controlView.findViewById(R.id.exo_play); - playButton.setOnClickListener(v->{ - if(autoFullscreen && !fullScreenMode) { + playButton.setOnClickListener(v -> { + if (autoFullscreen && !fullScreenMode) { openFullscreenDialog(); if (videoOrientationType == videoOrientation.LANDSCAPE) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); - }else { + } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } } @@ -1610,7 +1588,6 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd } - public void addElement(String playlistId, String videoId, APIResponse apiResponse) { if (apiResponse != null && apiResponse.getActionReturn() != null) { @@ -1626,12 +1603,10 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd } } - - private void updateHistory(long position) { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); boolean storeInHistory = sharedpreferences.getBoolean(getString(R.string.set_store_in_history), true); - if( Helper.isLoggedIn(PeertubeActivity.this) && peertube != null && storeInHistory) { + if (Helper.isLoggedIn(PeertubeActivity.this) && peertube != null && storeInHistory) { new Thread(() -> { try { RetrofitPeertubeAPI api = new RetrofitPeertubeAPI(PeertubeActivity.this); @@ -1648,13 +1623,11 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd binding.noActionText.setVisibility(View.VISIBLE); } - - private void playNextVideo() { - if( nextVideo != null) { + if (nextVideo != null) { Intent intent = new Intent(PeertubeActivity.this, PeertubeActivity.class); Bundle b = new Bundle(); - b.putParcelable("video",nextVideo); + b.putParcelable("video", nextVideo); b.putString("video_id", nextVideo.getId()); b.putString("video_uuid", nextVideo.getUuid()); playedVideos.add(nextVideo.getId()); @@ -1664,22 +1637,24 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd } } - - @Override public void onMediaItemTransition(MediaItem mediaItem, int reason) { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); boolean autoplayNextVideo = sharedpreferences.getBoolean(getString(R.string.set_autoplay_next_video_choice), true); - if (reason == MEDIA_ITEM_TRANSITION_REASON_AUTO && autoplayNextVideo){ + if (reason == MEDIA_ITEM_TRANSITION_REASON_AUTO && autoplayNextVideo) { player.removeMediaItems(0, player.getMediaItemCount()); playNextVideo(); } } - - @Override public void onPlayerError(ExoPlaybackException error) { } + + + enum videoOrientation { + LANDSCAPE, + PORTRAIT + } } diff --git a/app/src/main/java/app/fedilab/fedilabtube/PeertubeRegisterActivity.java b/app/src/main/java/app/fedilab/fedilabtube/PeertubeRegisterActivity.java index a9e5af6..9c29462 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/PeertubeRegisterActivity.java +++ b/app/src/main/java/app/fedilab/fedilabtube/PeertubeRegisterActivity.java @@ -61,7 +61,6 @@ public class PeertubeRegisterActivity extends AppCompatActivity { getSupportActionBar().setDisplayHomeAsUpEnabled(true); - if (BuildConfig.full_instances) { binding.loginInstanceContainer.setVisibility(View.VISIBLE); binding.titleLoginInstance.setVisibility(View.VISIBLE); @@ -114,21 +113,21 @@ public class PeertubeRegisterActivity extends AppCompatActivity { setTextAgreement(); binding.signup.setOnClickListener(view -> { binding.errorMessage.setVisibility(View.GONE); - if ( binding.username.getText() == null || binding.email.getText() == null || binding.password.getText() == null || binding.passwordConfirm.getText() == null || binding.username.getText().toString().trim().length() == 0 || binding.email.getText().toString().trim().length() == 0 || - binding.password.getText().toString().trim().length() == 0 || binding.passwordConfirm.getText().toString().trim().length() == 0 || ! binding.agreement.isChecked()) { + if (binding.username.getText() == null || binding.email.getText() == null || binding.password.getText() == null || binding.passwordConfirm.getText() == null || binding.username.getText().toString().trim().length() == 0 || binding.email.getText().toString().trim().length() == 0 || + binding.password.getText().toString().trim().length() == 0 || binding.passwordConfirm.getText().toString().trim().length() == 0 || !binding.agreement.isChecked()) { Toasty.error(PeertubeRegisterActivity.this, getString(R.string.all_field_filled)).show(); return; } - if (! binding.password.getText().toString().trim().equals( binding.passwordConfirm.getText().toString().trim())) { + if (!binding.password.getText().toString().trim().equals(binding.passwordConfirm.getText().toString().trim())) { Toasty.error(PeertubeRegisterActivity.this, getString(R.string.password_error)).show(); return; } - if (!android.util.Patterns.EMAIL_ADDRESS.matcher( binding.email.getText().toString().trim()).matches()) { + if (!android.util.Patterns.EMAIL_ADDRESS.matcher(binding.email.getText().toString().trim()).matches()) { Toasty.error(PeertubeRegisterActivity.this, getString(R.string.email_error)).show(); return; } - String[] emailArray = binding.email.getText().toString().split("@"); + String[] emailArray = binding.email.getText().toString().split("@"); if (!BuildConfig.full_instances) { if (emailArray.length > 1 && !Arrays.asList(Helper.valideEmails).contains(emailArray[1])) { Toasty.error(PeertubeRegisterActivity.this, getString(R.string.email_error_domain, emailArray[1])).show(); @@ -136,19 +135,19 @@ public class PeertubeRegisterActivity extends AppCompatActivity { } } - if ( binding.password.getText().toString().trim().length() < 8) { + if (binding.password.getText().toString().trim().length() < 8) { Toasty.error(PeertubeRegisterActivity.this, getString(R.string.password_too_short)).show(); return; } - if ( binding.username.getText().toString().matches("[a-z0-9_]")) { + if (binding.username.getText().toString().matches("[a-z0-9_]")) { Toasty.error(PeertubeRegisterActivity.this, getString(R.string.username_error)).show(); return; } binding.signup.setEnabled(false); if (BuildConfig.full_instances) { - if ( binding.loginInstance.getText() != null) { - instance = binding.loginInstance.getText().toString(); + if (binding.loginInstance.getText() != null) { + instance = binding.loginInstance.getText().toString(); } else { instance = ""; } @@ -166,10 +165,10 @@ public class PeertubeRegisterActivity extends AppCompatActivity { } AccountCreation accountCreation = new AccountCreation(); - accountCreation.setEmail( binding.email.getText().toString().trim()); - accountCreation.setPassword( binding.password.getText().toString().trim()); - accountCreation.setPasswordConfirm( binding.passwordConfirm.getText().toString().trim()); - accountCreation.setUsername( binding.username.getText().toString().trim()); + accountCreation.setEmail(binding.email.getText().toString().trim()); + accountCreation.setPassword(binding.password.getText().toString().trim()); + accountCreation.setPasswordConfirm(binding.passwordConfirm.getText().toString().trim()); + accountCreation.setUsername(binding.username.getText().toString().trim()); accountCreation.setInstance(instance); new Thread(() -> { @@ -259,7 +258,7 @@ public class PeertubeRegisterActivity extends AppCompatActivity { agreement_text.setMovementMethod(null); agreement_text.setText(null); if (BuildConfig.full_instances) { - if ( binding.loginInstance.getText() != null) { + if (binding.loginInstance.getText() != null) { content_agreement = getString(R.string.agreement_check_peertube, "" + tos + "" ); diff --git a/app/src/main/java/app/fedilab/fedilabtube/PeertubeUploadActivity.java b/app/src/main/java/app/fedilab/fedilabtube/PeertubeUploadActivity.java index 5b98d33..3bb3f3b 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/PeertubeUploadActivity.java +++ b/app/src/main/java/app/fedilab/fedilabtube/PeertubeUploadActivity.java @@ -66,8 +66,8 @@ import static app.fedilab.fedilabtube.client.RetrofitPeertubeAPI.DataType.MY_CHA public class PeertubeUploadActivity extends AppCompatActivity { - private final int PICK_IVDEO = 52378; public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 724; + private final int PICK_IVDEO = 52378; private Button set_upload_file, set_upload_submit; private Spinner set_upload_privacy, set_upload_channel; private TextView set_upload_file_name; diff --git a/app/src/main/java/app/fedilab/fedilabtube/ShowAccountActivity.java b/app/src/main/java/app/fedilab/fedilabtube/ShowAccountActivity.java index df19899..e6450d1 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/ShowAccountActivity.java +++ b/app/src/main/java/app/fedilab/fedilabtube/ShowAccountActivity.java @@ -134,7 +134,7 @@ public class ShowAccountActivity extends AppCompatActivity { }); AlertDialog alertDialog = dialogBuilder.create(); alertDialog.show(); - }else if( item.getItemId() == R.id.action_share && account != null) { + } else if (item.getItemId() == R.id.action_share && account != null) { Intent sendIntent = new Intent(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.shared_via)); String extra_text = account.getUrl(); diff --git a/app/src/main/java/app/fedilab/fedilabtube/ShowChannelActivity.java b/app/src/main/java/app/fedilab/fedilabtube/ShowChannelActivity.java index 74c765e..ea47f17 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/ShowChannelActivity.java +++ b/app/src/main/java/app/fedilab/fedilabtube/ShowChannelActivity.java @@ -159,7 +159,7 @@ public class ShowChannelActivity extends AppCompatActivity { }); androidx.appcompat.app.AlertDialog alertDialog = dialogBuilder.create(); alertDialog.show(); - } else if( item.getItemId() == R.id.action_share && channel != null) { + } else if (item.getItemId() == R.id.action_share && channel != null) { Intent sendIntent = new Intent(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.shared_via)); String extra_text = channel.getUrl(); diff --git a/app/src/main/java/app/fedilab/fedilabtube/client/PeertubeService.java b/app/src/main/java/app/fedilab/fedilabtube/client/PeertubeService.java index ed9d723..9bb94d0 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/client/PeertubeService.java +++ b/app/src/main/java/app/fedilab/fedilabtube/client/PeertubeService.java @@ -68,7 +68,7 @@ public interface PeertubeService { //Instance info @GET("config/about") - Call configAbout(); + Call configAbout(); @GET("{nodeInfoPath}") Call getNodeinfo(@Path(value = "nodeInfoPath", encoded = true) String nodeInfoPath); @@ -140,7 +140,7 @@ public interface PeertubeService { @Field("description") String description, @Field("displayName") String displayName, @Field("nsfwPolicy") String nsfwPolicy - ); + ); @Multipart @POST("users/me/avatar/pick") diff --git a/app/src/main/java/app/fedilab/fedilabtube/client/RetrofitPeertubeAPI.java b/app/src/main/java/app/fedilab/fedilabtube/client/RetrofitPeertubeAPI.java index 522e876..ebc97c9 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/client/RetrofitPeertubeAPI.java +++ b/app/src/main/java/app/fedilab/fedilabtube/client/RetrofitPeertubeAPI.java @@ -166,9 +166,9 @@ public class RetrofitPeertubeAPI { } private String getToken() { - if( token != null) { + if (token != null) { return "Bearer " + token; - }else{ + } else { return null; } } @@ -454,7 +454,7 @@ public class RetrofitPeertubeAPI { /** * Update history * - * @param videoId String + * @param videoId String * @param currentTime int */ public void updateHistory(String videoId, long currentTime) { @@ -525,10 +525,10 @@ public class RetrofitPeertubeAPI { } byte[] imageBytes = byteBuffer.toByteArray(); String mime = MimeTypeMap.getFileExtensionFromUrl(userSettings.getAvatarfile().toString()); - if( mime == null || mime.trim().length() == 0) { + if (mime == null || mime.trim().length() == 0) { mime = "png"; } - RequestBody requestFile = RequestBody.create(MediaType.parse("image/"+mime), imageBytes); + RequestBody requestFile = RequestBody.create(MediaType.parse("image/" + mime), imageBytes); MultipartBody.Part bodyThumbnail = MultipartBody.Part.createFormData("avatarfile", userSettings.getFileName(), requestFile); Call updateProfilePicture = peertubeService.updateProfilePicture(getToken(), bodyThumbnail); Response responseAvatar = updateProfilePicture.execute(); @@ -599,16 +599,17 @@ public class RetrofitPeertubeAPI { /** * About the instance + * * @return AboutInstance */ public InstanceData.AboutInstance getAboutInstance() { PeertubeService peertubeService = init(); - Call about = peertubeService.configAbout(); + Call about = peertubeService.configAbout(); try { - Response response = about.execute(); + Response response = about.execute(); if (response.isSuccessful() && response.body() != null) { - return response.body(); + return response.body().getInstance(); } } catch (IOException e) { e.printStackTrace(); @@ -800,7 +801,7 @@ public class RetrofitPeertubeAPI { */ public APIResponse searchNextVideos(List tags) { PeertubeService peertubeService = init(); - Call searchVideosCall = peertubeService.searchNextVideo(getToken(), tags, "0" , "20"); + Call searchVideosCall = peertubeService.searchNextVideo(getToken(), tags, "0", "20"); APIResponse apiResponse = new APIResponse(); try { Response response = searchVideosCall.execute(); @@ -1058,7 +1059,6 @@ public class RetrofitPeertubeAPI { } - /** * Get video description * @@ -1071,9 +1071,10 @@ public class RetrofitPeertubeAPI { try { Response response = videoDescription.execute(); if (response.isSuccessful() && response.body() != null) { - return response.body(); + return response.body(); } - } catch (IOException ignored) {} + } catch (IOException ignored) { + } return null; } 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 index 8a77425..59eff4c 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/client/data/InstanceData.java +++ b/app/src/main/java/app/fedilab/fedilabtube/client/data/InstanceData.java @@ -242,29 +242,21 @@ public class InstanceData { } } - public static class AboutInstance implements Parcelable, Serializable { + public static class InstanceInfo { + @SerializedName("instance") + private AboutInstance instance; - @SerializedName("name") - private String name; - @SerializedName("shortDescription") - private String shortDescription; - @SerializedName("description") - private String description; - @SerializedName("terms") - private String terms; - private String host; - - - public AboutInstance(){} - - protected AboutInstance(Parcel in) { - name = in.readString(); - shortDescription = in.readString(); - description = in.readString(); - terms = in.readString(); - host = in.readString(); + public AboutInstance getInstance() { + return instance; } + public void setInstance(AboutInstance instance) { + this.instance = instance; + } + } + + public static class AboutInstance implements Parcelable, Serializable { + public static final Creator CREATOR = new Creator() { @Override public AboutInstance createFromParcel(Parcel in) { @@ -276,6 +268,26 @@ public class InstanceData { return new AboutInstance[size]; } }; + @SerializedName("name") + private String name; + @SerializedName("shortDescription") + private String shortDescription; + @SerializedName("description") + private String description; + @SerializedName("terms") + private String terms; + private String host; + + public AboutInstance() { + } + + protected AboutInstance(Parcel in) { + name = in.readString(); + shortDescription = in.readString(); + description = in.readString(); + terms = in.readString(); + host = in.readString(); + } public String getName() { return name; 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 index 782522f..3dd0859 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/client/data/VideoData.java +++ b/app/src/main/java/app/fedilab/fedilabtube/client/data/VideoData.java @@ -180,7 +180,7 @@ public class VideoData { this.trackerUrls = in.createStringArrayList(); long tmpUpdatedAt = in.readLong(); this.updatedAt = tmpUpdatedAt == -1 ? null : new Date(tmpUpdatedAt); - this.userHistory = in.readParcelable(UserHistory.class.getClassLoader()); + this.userHistory = in.readParcelable(UserHistory.class.getClassLoader()); this.uuid = in.readString(); this.views = in.readInt(); this.waitTranscoding = in.readByte() != 0; @@ -198,7 +198,7 @@ public class VideoData { return file.getMagnetUri(); } else if (mode == Helper.VIDEO_MODE_TORRENT) { return file.getTorrentUrl(); - }else { + } else { return file.getFileUrl(); } } @@ -698,7 +698,7 @@ public class VideoData { } - public static class UserHistory implements Parcelable{ + public static class UserHistory implements Parcelable { public static final Creator CREATOR = new Creator() { @Override @@ -743,7 +743,7 @@ public class VideoData { } - public static class Description{ + public static class Description { @SerializedName("description") private String description; diff --git a/app/src/main/java/app/fedilab/fedilabtube/client/entities/File.java b/app/src/main/java/app/fedilab/fedilabtube/client/entities/File.java index 1120da2..05582ad 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/client/entities/File.java +++ b/app/src/main/java/app/fedilab/fedilabtube/client/entities/File.java @@ -9,6 +9,17 @@ import com.google.gson.annotations.SerializedName; @SuppressWarnings({"unused", "RedundantSuppression"}) public class File implements Parcelable { + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + @Override + public File createFromParcel(Parcel source) { + return new File(source); + } + + @Override + public File[] newArray(int size) { + return new File[size]; + } + }; @SerializedName("fileDownloadUrl") private String fileDownloadUrl; @SerializedName("fileUrl") @@ -28,6 +39,21 @@ public class File implements Parcelable { @SerializedName("torrentUrl") private String torrentUrl; + public File() { + } + + protected File(Parcel in) { + this.fileDownloadUrl = in.readString(); + this.fileUrl = in.readString(); + this.fps = in.readInt(); + this.magnetUri = in.readString(); + this.metadataUrl = in.readString(); + this.resolutions = in.readParcelable(Item.class.getClassLoader()); + this.size = in.readLong(); + this.torrentDownloadUrl = in.readString(); + this.torrentUrl = in.readString(); + } + public String getFileDownloadUrl() { return fileDownloadUrl; } @@ -100,7 +126,6 @@ public class File implements Parcelable { this.torrentUrl = torrentUrl; } - @Override public int describeContents() { return 0; @@ -118,31 +143,4 @@ public class File implements Parcelable { dest.writeString(this.torrentDownloadUrl); dest.writeString(this.torrentUrl); } - - public File() { - } - - protected File(Parcel in) { - this.fileDownloadUrl = in.readString(); - this.fileUrl = in.readString(); - this.fps = in.readInt(); - this.magnetUri = in.readString(); - this.metadataUrl = in.readString(); - this.resolutions = in.readParcelable(Item.class.getClassLoader()); - this.size = in.readLong(); - this.torrentDownloadUrl = in.readString(); - this.torrentUrl = in.readString(); - } - - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - @Override - public File createFromParcel(Parcel source) { - return new File(source); - } - - @Override - public File[] newArray(int size) { - return new File[size]; - } - }; } diff --git a/app/src/main/java/app/fedilab/fedilabtube/client/entities/UserSettings.java b/app/src/main/java/app/fedilab/fedilabtube/client/entities/UserSettings.java index a6f8272..5da4280 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/client/entities/UserSettings.java +++ b/app/src/main/java/app/fedilab/fedilabtube/client/entities/UserSettings.java @@ -37,26 +37,14 @@ public class UserSettings { return videosHistoryEnabled; } - public void setVideosHistoryEnabled(Boolean videosHistoryEnabled) { - this.videosHistoryEnabled = videosHistoryEnabled; - } - public Boolean isAutoPlayVideo() { return autoPlayVideo; } - public void setAutoPlayVideo(Boolean autoPlayVideo) { - this.autoPlayVideo = autoPlayVideo; - } - public Boolean isWebTorrentEnabled() { return webTorrentEnabled; } - public void setWebTorrentEnabled(Boolean webTorrentEnabled) { - this.webTorrentEnabled = webTorrentEnabled; - } - public List getVideoLanguages() { return videoLanguages; } @@ -93,32 +81,44 @@ public class UserSettings { return videosHistoryEnabled; } + public void setVideosHistoryEnabled(Boolean videosHistoryEnabled) { + this.videosHistoryEnabled = videosHistoryEnabled; + } + public Boolean getAutoPlayVideo() { return autoPlayVideo; } + public void setAutoPlayVideo(Boolean autoPlayVideo) { + this.autoPlayVideo = autoPlayVideo; + } + public Boolean getWebTorrentEnabled() { return webTorrentEnabled; } + public void setWebTorrentEnabled(Boolean webTorrentEnabled) { + this.webTorrentEnabled = webTorrentEnabled; + } + public Boolean isAutoPlayNextVideo() { return autoPlayNextVideo; } + public Boolean getAutoPlayNextVideo() { + return autoPlayNextVideo; + } + public void setAutoPlayNextVideo(Boolean autoPlayNextVideo) { this.autoPlayNextVideo = autoPlayNextVideo; } - public Boolean getAutoPlayNextVideo() { - return autoPlayNextVideo; - } - public String getFileName() { return fileName; } public void setFileName(String fileName) { - if( fileName == null) { + if (fileName == null) { this.fileName = "avatar.png"; } else { this.fileName = fileName; diff --git a/app/src/main/java/app/fedilab/fedilabtube/drawer/AboutInstanceAdapter.java b/app/src/main/java/app/fedilab/fedilabtube/drawer/AboutInstanceAdapter.java index 18ff0c4..f0f8cb6 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/drawer/AboutInstanceAdapter.java +++ b/app/src/main/java/app/fedilab/fedilabtube/drawer/AboutInstanceAdapter.java @@ -22,10 +22,14 @@ import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; +import android.os.Build; import android.os.Handler; import android.os.Looper; +import android.text.Html; +import android.text.SpannableString; import android.view.LayoutInflater; import android.view.ViewGroup; +import android.widget.TextView; import androidx.annotation.NonNull; import androidx.appcompat.widget.PopupMenu; @@ -35,24 +39,23 @@ import java.util.List; import app.fedilab.fedilabtube.MainActivity; import app.fedilab.fedilabtube.R; -import app.fedilab.fedilabtube.client.RetrofitPeertubeAPI; import app.fedilab.fedilabtube.client.data.InstanceData; import app.fedilab.fedilabtube.databinding.DrawerAboutInstanceBinding; import app.fedilab.fedilabtube.helper.Helper; import app.fedilab.fedilabtube.sqlite.Sqlite; import app.fedilab.fedilabtube.sqlite.StoredInstanceDAO; +import static androidx.core.text.HtmlCompat.FROM_HTML_MODE_LEGACY; + public class AboutInstanceAdapter extends RecyclerView.Adapter { private final List aboutInstances; - private final AboutInstanceAdapter aboutInstanceAdapter; public AllInstancesRemoved allInstancesRemoved; private Context context; public AboutInstanceAdapter(List aboutInstances) { - aboutInstanceAdapter = this; this.aboutInstances = aboutInstances; } @@ -71,7 +74,7 @@ public class AboutInstanceAdapter extends RecyclerView.Adapter= Build.VERSION_CODES.N) + spannableString = new SpannableString(Html.fromHtml(aboutInstance.getShortDescription(), FROM_HTML_MODE_LEGACY)); + else + spannableString = new SpannableString(Html.fromHtml(aboutInstance.getShortDescription())); + holder.binding.aboutInstanceDescription.setText(spannableString, TextView.BufferType.SPANNABLE); + } + holder.binding.aboutInstanceName.setText(aboutInstance.getName()); - holder.binding.playlistContainer.setOnClickListener(v->{ + holder.binding.playlistContainer.setOnClickListener(v -> { final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(Helper.PREF_INSTANCE, aboutInstance.getHost()); editor.commit(); - ((Activity)context).runOnUiThread(() -> { + ((Activity) context).runOnUiThread(() -> { Intent intent = new Intent(context, MainActivity.class); context.startActivity(intent); }); }); - holder.binding.instanceMore.setOnClickListener(v->{ + holder.binding.instanceMore.setOnClickListener(v -> { PopupMenu popup = new PopupMenu(context, holder.binding.instanceMore); popup.getMenuInflater() .inflate(R.menu.instance_menu, popup.getMenu()); @@ -112,8 +125,10 @@ public class AboutInstanceAdapter extends RecyclerView.Adapter { SQLiteDatabase db = Sqlite.getInstance(context.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); new StoredInstanceDAO(context, db).removeInstance(aboutInstance.getHost()); + aboutInstances.remove(aboutInstance); Handler mainHandler = new Handler(Looper.getMainLooper()); Runnable myRunnable = () -> { + notifyItemRemoved(i); if (aboutInstances.size() == 0) { allInstancesRemoved.onAllInstancesRemoved(); } @@ -128,6 +143,7 @@ public class AboutInstanceAdapter extends RecyclerView.Adapter comments; private final CommentListAdapter commentListAdapter; + private final boolean isThread; public AllCommentRemoved allCommentRemoved; boolean isVideoOwner; private Context context; - private final boolean isThread; public CommentListAdapter(List comments, boolean isVideoOwner, boolean isThread) { this.comments = comments; @@ -125,11 +125,11 @@ public class CommentListAdapter extends RecyclerView.Adapter ((PeertubeActivity) context).openPostComment(comment, i)); @@ -375,8 +375,8 @@ public class CommentListAdapter extends RecyclerView.Adapter. */ - import com.bumptech.glide.Glide; import com.bumptech.glide.request.target.CustomTarget; import com.bumptech.glide.request.transition.Transition; @@ -60,6 +45,21 @@ import es.dmoral.toasty.Toasty; import static app.fedilab.fedilabtube.MainActivity.peertubeInformation; import static app.fedilab.fedilabtube.MainActivity.userMe; +/* 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 . */ + public class SettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener { @Override @@ -135,7 +135,7 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared if (set_video_sensitive_choice != null) { editor.putString(getString(R.string.set_video_sensitive_choice), set_video_sensitive_choice.getValue()); editor.apply(); - if(Helper.isLoggedIn(getActivity())) { + if (Helper.isLoggedIn(getActivity())) { new Thread(() -> { UserSettings userSettings = new UserSettings(); userSettings.setNsfwPolicy(set_video_sensitive_choice.getValue()); @@ -182,7 +182,7 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared SwitchPreference set_autoplay_choice = findPreference(getString(R.string.set_autoplay_choice)); assert set_autoplay_choice != null; editor.putBoolean(getString(R.string.set_autoplay_choice), set_autoplay_choice.isChecked()); - if(Helper.isLoggedIn(getActivity())) { + if (Helper.isLoggedIn(getActivity())) { new Thread(() -> { UserSettings userSettings = new UserSettings(); userSettings.setAutoPlayVideo(set_autoplay_choice.isChecked()); @@ -204,7 +204,7 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared SwitchPreference set_autoplay_next_video_choice = findPreference(getString(R.string.set_autoplay_next_video_choice)); assert set_autoplay_next_video_choice != null; editor.putBoolean(getString(R.string.set_autoplay_next_video_choice), set_autoplay_next_video_choice.isChecked()); - if(Helper.isLoggedIn(getActivity())) { + if (Helper.isLoggedIn(getActivity())) { new Thread(() -> { UserSettings userSettings = new UserSettings(); userSettings.setAutoPlayNextVideo(set_autoplay_next_video_choice.isChecked()); @@ -233,7 +233,7 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared MultiSelectListPreference set_video_language_choice = findPreference(getString(R.string.set_video_language_choice)); assert set_video_language_choice != null; editor.putStringSet(getString(R.string.set_video_language_choice), set_video_language_choice.getValues()); - if(Helper.isLoggedIn(getActivity())) { + if (Helper.isLoggedIn(getActivity())) { new Thread(() -> { UserSettings userSettings = new UserSettings(); Set language_choiceValues = set_video_language_choice.getValues(); @@ -266,7 +266,7 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared Preference my_account = findPreference("my_account"); assert my_account != null; - if(!Helper.isLoggedIn(getActivity()) || userMe == null) { + if (!Helper.isLoggedIn(getActivity()) || userMe == null) { my_account.setVisible(false); } else { my_account.setTitle(userMe.getUsername()); @@ -275,18 +275,19 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared Drawable defaultAvatar = ResourcesCompat.getDrawable(resources, R.drawable.missing_peertube, null); my_account.setIcon(defaultAvatar); Glide.with(getActivity()) - .asDrawable() - .load("https://" + Helper.getLiveInstance(context) + userMe.getAccount().getAvatar().getPath()) - .into(new CustomTarget() { - @Override - public void onResourceReady(@NonNull Drawable resource, @Nullable Transition transition) { - my_account.setIcon(resource); - } - @Override - public void onLoadCleared(@Nullable Drawable placeholder) { + .asDrawable() + .load("https://" + Helper.getLiveInstance(context) + userMe.getAccount().getAvatar().getPath()) + .into(new CustomTarget() { + @Override + public void onResourceReady(@NonNull Drawable resource, @Nullable Transition transition) { + my_account.setIcon(resource); + } - } - }); + @Override + public void onLoadCleared(@Nullable Drawable placeholder) { + + } + }); } @@ -307,7 +308,6 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared } - //****** Video mode ******* ListPreference set_video_mode_choice = findPreference(getString(R.string.set_video_mode_choice)); List array = Arrays.asList(getResources().getStringArray(R.array.settings_video_mode)); @@ -349,7 +349,7 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared SwitchPreference set_video_minimize_choice = findPreference(getString(R.string.set_video_minimize_choice)); assert set_video_minimize_choice != null; set_video_minimize_choice.setChecked(minimized); - if ( Build.VERSION.SDK_INT < Build.VERSION_CODES.O + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O || !getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) { set_video_minimize_choice.setVisible(false); } @@ -422,8 +422,8 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared entryValuesSensitive[1] = Helper.BLUR.toLowerCase(); entryValuesSensitive[2] = Helper.DISPLAY.toLowerCase(); int currentSensitivePosition = 0; - for(CharSequence val : entryValuesSensitive) { - if(val.equals(currentSensitive)) { + for (CharSequence val : entryValuesSensitive) { + if (val.equals(currentSensitive)) { break; } currentSensitivePosition++; diff --git a/app/src/main/java/app/fedilab/fedilabtube/helper/CommentDecorationHelper.java b/app/src/main/java/app/fedilab/fedilabtube/helper/CommentDecorationHelper.java index 9122b61..f308f7c 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/helper/CommentDecorationHelper.java +++ b/app/src/main/java/app/fedilab/fedilabtube/helper/CommentDecorationHelper.java @@ -13,29 +13,30 @@ package app.fedilab.fedilabtube.helper; * * You should have received a copy of the GNU General Public License along with TubeLab; if not, * see . */ + import java.util.List; import app.fedilab.fedilabtube.client.data.CommentData; public class CommentDecorationHelper { - public static int getIndentation(String replyToCommentId, List comments){ + public static int getIndentation(String replyToCommentId, List comments) { return numberOfIndentation(0, replyToCommentId, comments); } private static int numberOfIndentation(int currentIdentation, String replyToCommentId, List comments) { String targetedComment = null; - for(CommentData.Comment comment: comments) { - if( replyToCommentId.compareTo(comment.getId()) == 0) { + for (CommentData.Comment comment : comments) { + if (replyToCommentId.compareTo(comment.getId()) == 0) { targetedComment = comment.getInReplyToCommentId(); break; } } - if ( targetedComment != null) { + if (targetedComment != null) { currentIdentation++; return numberOfIndentation(currentIdentation, targetedComment, comments); - }else{ + } else { return Math.min(currentIdentation, 5); } } diff --git a/app/src/main/java/app/fedilab/fedilabtube/helper/Helper.java b/app/src/main/java/app/fedilab/fedilabtube/helper/Helper.java index 4373ec1..650e4e8 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/helper/Helper.java +++ b/app/src/main/java/app/fedilab/fedilabtube/helper/Helper.java @@ -479,12 +479,12 @@ public class Helper { RequestBuilder requestBuilder = Glide.with(imageView.getContext()) .load(url) .thumbnail(0.1f); - if( blur ) { - requestBuilder.apply(new RequestOptions().transform(new BlurTransformation(50, 3), new CenterCrop(), new RoundedCorners(10))); - }else { - requestBuilder.apply(new RequestOptions().transform(new CenterCrop(), new RoundedCorners(round))); - } - requestBuilder.into(imageView); + if (blur) { + requestBuilder.apply(new RequestOptions().transform(new BlurTransformation(50, 3), new CenterCrop(), new RoundedCorners(10))); + } else { + requestBuilder.apply(new RequestOptions().transform(new CenterCrop(), new RoundedCorners(round))); + } + requestBuilder.into(imageView); } catch (Exception e) { try { Glide.with(imageView.getContext()) @@ -706,7 +706,7 @@ public class Helper { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userName = sharedpreferences.getString(Helper.PREF_KEY_NAME, ""); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, ""); - if( video == null) { + if (video == null) { return false; } Account account = video.getAccount(); @@ -748,8 +748,9 @@ public class Helper { /** * Forward the intent (open an URL) to another app + * * @param activity Activity - * @param i Intent + * @param i Intent */ public static void forwardToAnotherApp(Activity activity, Intent i) { Intent intent = new Intent(); diff --git a/app/src/main/java/app/fedilab/fedilabtube/helper/NotificationHelper.java b/app/src/main/java/app/fedilab/fedilabtube/helper/NotificationHelper.java index 8c46d68..2b0d2e0 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/helper/NotificationHelper.java +++ b/app/src/main/java/app/fedilab/fedilabtube/helper/NotificationHelper.java @@ -14,6 +14,7 @@ package app.fedilab.fedilabtube.helper; * * You should have received a copy of the GNU General Public License along with TubeLab; if not, * see . */ + import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; diff --git a/app/src/main/java/app/fedilab/fedilabtube/helper/SwitchAccountHelper.java b/app/src/main/java/app/fedilab/fedilabtube/helper/SwitchAccountHelper.java index e233377..111be3b 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/helper/SwitchAccountHelper.java +++ b/app/src/main/java/app/fedilab/fedilabtube/helper/SwitchAccountHelper.java @@ -23,7 +23,6 @@ import androidx.appcompat.app.AlertDialog; import java.util.List; - import app.fedilab.fedilabtube.LoginActivity; import app.fedilab.fedilabtube.MainActivity; import app.fedilab.fedilabtube.R; @@ -35,9 +34,9 @@ import app.fedilab.fedilabtube.sqlite.Sqlite; import static android.content.Context.MODE_PRIVATE; public class SwitchAccountHelper { - - - public static void switchDialog(Activity activity, boolean withAddAccount){ + + + public static void switchDialog(Activity activity, boolean withAddAccount) { SQLiteDatabase db = Sqlite.getInstance(activity.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); List accounts = new AccountDAO(activity, db).getAllAccount(); @@ -67,7 +66,7 @@ public class SwitchAccountHelper { }); } builderSingle.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()); - if( withAddAccount) { + if (withAddAccount) { builderSingle.setPositiveButton(R.string.add_account, (dialog, which) -> { Intent intent = new Intent(activity, LoginActivity.class); activity.startActivity(intent); diff --git a/app/src/main/java/app/fedilab/fedilabtube/services/RetrieveInfoService.java b/app/src/main/java/app/fedilab/fedilabtube/services/RetrieveInfoService.java index 00561c4..5d1f471 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/services/RetrieveInfoService.java +++ b/app/src/main/java/app/fedilab/fedilabtube/services/RetrieveInfoService.java @@ -127,7 +127,7 @@ public class RetrieveInfoService extends Service implements NetworkStateReceiver @Override public void run() { EmojiHelper.fillMapEmoji(getApplicationContext()); - if( peertubeInformation == null || peertubeInformation.getCategories().size() == 0) { + if (peertubeInformation == null || peertubeInformation.getCategories().size() == 0) { peertubeInformation = new PeertubeInformation(); peertubeInformation.setCategories(new LinkedHashMap<>()); peertubeInformation.setLanguages(new LinkedHashMap<>()); diff --git a/app/src/main/java/app/fedilab/fedilabtube/sqlite/AccountDAO.java b/app/src/main/java/app/fedilab/fedilabtube/sqlite/AccountDAO.java index 5ed353f..7c1a3c7 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/sqlite/AccountDAO.java +++ b/app/src/main/java/app/fedilab/fedilabtube/sqlite/AccountDAO.java @@ -252,7 +252,7 @@ public class AccountDAO { /** * Returns an Account by id and instance * - * @param id String + * @param id String * @param instance String * @return Account */ @@ -266,6 +266,7 @@ public class AccountDAO { return null; } } + /** * Test if the current user is already stored in data base * diff --git a/app/src/main/java/app/fedilab/fedilabtube/sqlite/Sqlite.java b/app/src/main/java/app/fedilab/fedilabtube/sqlite/Sqlite.java index e9c2fb0..6f41ca6 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/sqlite/Sqlite.java +++ b/app/src/main/java/app/fedilab/fedilabtube/sqlite/Sqlite.java @@ -59,6 +59,9 @@ public class Sqlite extends SQLiteOpenHelper { static final String COL_UUID = "UUID"; static final String COL_CACHE = "CACHE"; static final String COL_DATE = "DATE"; + static final String COL_USER_INSTANCE = "USER_INSTANCE"; + static final String TABLE_BOOKMARKED_INSTANCES = "BOOKMARKED_INSTANCES"; + static final String COL_ABOUT = "ABOUT"; private static final String CREATE_TABLE_USER_ACCOUNT = "CREATE TABLE " + TABLE_USER_ACCOUNT + " (" + COL_USER_ID + " TEXT, " + COL_USERNAME + " TEXT NOT NULL, " + COL_ACCT + " TEXT NOT NULL, " + COL_DISPLAYED_NAME + " TEXT NOT NULL, " + COL_LOCKED + " INTEGER NOT NULL, " @@ -82,10 +85,6 @@ public class Sqlite extends SQLiteOpenHelper { + COL_INSTANCE + " TEXT NOT NULL, " + COL_CACHE + " TEXT NOT NULL, " + COL_DATE + " TEXT NOT NULL)"; - - static final String COL_USER_INSTANCE = "USER_INSTANCE"; - static final String TABLE_BOOKMARKED_INSTANCES = "BOOKMARKED_INSTANCES"; - static final String COL_ABOUT = "ABOUT"; private final String CREATE_TABLE_STORED_INSTANCES = "CREATE TABLE " + TABLE_BOOKMARKED_INSTANCES + "(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " @@ -118,7 +117,7 @@ public class Sqlite extends SQLiteOpenHelper { public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { switch (oldVersion) { case 2: - db.execSQL("DROP TABLE IF EXISTS " +TABLE_BOOKMARKED_INSTANCES); + db.execSQL("DROP TABLE IF EXISTS " + TABLE_BOOKMARKED_INSTANCES); } } diff --git a/app/src/main/java/app/fedilab/fedilabtube/sqlite/StoredInstanceDAO.java b/app/src/main/java/app/fedilab/fedilabtube/sqlite/StoredInstanceDAO.java index 55bb3ae..eda559c 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/sqlite/StoredInstanceDAO.java +++ b/app/src/main/java/app/fedilab/fedilabtube/sqlite/StoredInstanceDAO.java @@ -42,36 +42,6 @@ public class StoredInstanceDAO { this.db = db; } - - /** - * Insert instance info in database - * - * @param aboutInstance AboutInstance - * @param targetedInstance String - * @return boolean - */ - public boolean insertInstance(InstanceData.AboutInstance aboutInstance, String targetedInstance) { - ContentValues values = new ContentValues(); - - SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - String instance = Helper.getLiveInstance(context); - - values.put(Sqlite.COL_USER_ID, userId); - values.put(Sqlite.COL_USER_INSTANCE, instance); - values.put(Sqlite.COL_ABOUT, aboutInstanceToStringStorage(aboutInstance)); - values.put(Sqlite.COL_INSTANCE, targetedInstance); - //Inserts account - try { - db.insertOrThrow(Sqlite.TABLE_BOOKMARKED_INSTANCES, null, values); - - } catch (Exception e) { - e.printStackTrace(); - return false; - } - return true; - } - /** * Unserialized AboutInstance * @@ -105,7 +75,36 @@ public class StoredInstanceDAO { /** * Insert instance info in database * - * @param aboutInstance AboutInstance + * @param aboutInstance AboutInstance + * @param targetedInstance String + * @return boolean + */ + public boolean insertInstance(InstanceData.AboutInstance aboutInstance, String targetedInstance) { + ContentValues values = new ContentValues(); + + SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); + String instance = Helper.getLiveInstance(context); + + values.put(Sqlite.COL_USER_ID, userId != null ? userId : "_ALL_"); + values.put(Sqlite.COL_USER_INSTANCE, instance != null ? instance : "_ALL_"); + values.put(Sqlite.COL_ABOUT, aboutInstanceToStringStorage(aboutInstance)); + values.put(Sqlite.COL_INSTANCE, targetedInstance); + //Inserts account + try { + db.insertOrThrow(Sqlite.TABLE_BOOKMARKED_INSTANCES, null, values); + + } catch (Exception e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * Insert instance info in database + * + * @param aboutInstance AboutInstance * @param targetedInstance String * @return int */ @@ -125,11 +124,10 @@ public class StoredInstanceDAO { public int removeInstance(String instance) { - return db.delete(Sqlite.TABLE_BOOKMARKED_INSTANCES, Sqlite.COL_INSTANCE + " = '" +instance + "'", null); + return db.delete(Sqlite.TABLE_BOOKMARKED_INSTANCES, Sqlite.COL_INSTANCE + " = '" + instance + "'", null); } - /** * Returns all Instance in db * @@ -147,7 +145,6 @@ public class StoredInstanceDAO { } - /*** * Method to hydrate an Account from database * @param c Cursor @@ -184,7 +181,9 @@ public class StoredInstanceDAO { List aboutInstances = new ArrayList<>(); while (c.moveToNext()) { String aboutInstanceStr = c.getString(c.getColumnIndex(Sqlite.COL_ABOUT)); + String instance = c.getString(c.getColumnIndex(Sqlite.COL_INSTANCE)); InstanceData.AboutInstance aboutInstance = restoreAboutInstanceFromString(aboutInstanceStr); + aboutInstance.setHost(instance); aboutInstances.add(aboutInstance); } //Close the cursor diff --git a/app/src/main/java/app/fedilab/fedilabtube/webview/MastalabWebChromeClient.java b/app/src/main/java/app/fedilab/fedilabtube/webview/MastalabWebChromeClient.java index a22fd25..35a37b6 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/webview/MastalabWebChromeClient.java +++ b/app/src/main/java/app/fedilab/fedilabtube/webview/MastalabWebChromeClient.java @@ -37,17 +37,15 @@ import app.fedilab.fedilabtube.R; public class MastalabWebChromeClient extends WebChromeClient implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener { - private FrameLayout videoViewContainer; - private CustomViewCallback videoViewCallback; - - private ToggledFullscreenCallback toggledFullscreenCallback; - private final CustomWebview webView; private final View activityNonVideoView; private final ViewGroup activityVideoView; private final ProgressBar pbar; - private boolean isVideoFullscreen; private final Activity activity; + private FrameLayout videoViewContainer; + private CustomViewCallback videoViewCallback; + private ToggledFullscreenCallback toggledFullscreenCallback; + private boolean isVideoFullscreen; public MastalabWebChromeClient(Activity activity, CustomWebview webView, FrameLayout activityNonVideoView, ViewGroup activityVideoView) { @@ -113,7 +111,6 @@ public class MastalabWebChromeClient extends WebChromeClient implements MediaPla public void onShowCustomView(View view, CustomViewCallback callback) { if (view instanceof FrameLayout) { if (((AppCompatActivity) activity).getSupportActionBar() != null) - //noinspection ConstantConditions ((AppCompatActivity) activity).getSupportActionBar().hide(); // A video wants to be shown FrameLayout frameLayout = (FrameLayout) view; @@ -178,7 +175,6 @@ public class MastalabWebChromeClient extends WebChromeClient implements MediaPla @Override public void onHideCustomView() { if (((AppCompatActivity) activity).getSupportActionBar() != null) - //noinspection ConstantConditions ((AppCompatActivity) activity).getSupportActionBar().show(); // This method should be manually called on video end in all cases because it's not always called automatically. // This method must be manually called on back key press (from this class' onBackPressed() method). diff --git a/app/src/main/java/app/fedilab/fedilabtube/worker/NotificationsWorker.java b/app/src/main/java/app/fedilab/fedilabtube/worker/NotificationsWorker.java index b0c0095..96a1841 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/worker/NotificationsWorker.java +++ b/app/src/main/java/app/fedilab/fedilabtube/worker/NotificationsWorker.java @@ -61,9 +61,9 @@ import static android.content.Context.NOTIFICATION_SERVICE; public class NotificationsWorker extends Worker { - private final NotificationManager notificationManager; public static String FETCH_NOTIFICATION_CHANNEL_ID = "fetch_notification_peertube"; public static int pendingNotificationID = 1; + private final NotificationManager notificationManager; public NotificationsWorker( @NonNull Context context, @@ -80,7 +80,7 @@ public class NotificationsWorker extends Worker { Context applicationContext = getApplicationContext(); SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); List accounts = new AccountDAO(applicationContext, db).getAllAccount(); - if( accounts == null || accounts.size() == 0) { + if (accounts == null || accounts.size() == 0) { return Result.success(); } setForegroundAsync(createForegroundInfo()); @@ -95,28 +95,28 @@ public class NotificationsWorker extends Worker { List accounts = new AccountDAO(getApplicationContext(), db).getAllAccount(); SharedPreferences sharedpreferences = getApplicationContext().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedpreferences.edit(); - for(AccountData.Account account: accounts) { + for (AccountData.Account account : accounts) { RetrofitPeertubeAPI retrofitPeertubeAPI = new RetrofitPeertubeAPI(getApplicationContext(), account.getHost(), account.getToken()); APIResponse apiResponse = retrofitPeertubeAPI.getNotifications(); - if( apiResponse == null) { + if (apiResponse == null) { return; } try { UserMe userMe = retrofitPeertubeAPI.verifyCredentials(); - if( userMe != null) { + if (userMe != null) { List notifications = apiResponse.getPeertubeNotifications(); NotificationSettings notificationSettings = userMe.getNotificationSettings(); - if( apiResponse.getPeertubeNotifications() != null && apiResponse.getPeertubeNotifications().size() > 0 ) { + if (apiResponse.getPeertubeNotifications() != null && apiResponse.getPeertubeNotifications().size() > 0) { String last_read = sharedpreferences.getString(Helper.LAST_NOTIFICATION_READ + account.getId() + account.getHost(), null); editor.putString(Helper.LAST_NOTIFICATION_READ + account.getId() + account.getHost(), apiResponse.getPeertubeNotifications().get(0).getId()); editor.apply(); - if( last_read != null) { - for(NotificationData.Notification notification: notifications) { + if (last_read != null) { + for (NotificationData.Notification notification : notifications) { String title = ""; String message = ""; FutureTarget futureBitmap = Glide.with(getApplicationContext()) .asBitmap() - .load("https://"+account.getHost()+account.getAvatar()).submit(); + .load("https://" + account.getHost() + account.getAvatar()).submit(); Bitmap icon; try { icon = futureBitmap.get(); @@ -126,14 +126,14 @@ public class NotificationsWorker extends Worker { } Intent intent = null; - if(notification.getId().compareTo(last_read) > 0) { + if (notification.getId().compareTo(last_read) > 0) { switch (notification.getType()) { case DisplayNotificationsFragment.NEW_VIDEO_FROM_SUBSCRIPTION: - if(notificationSettings.getNewVideoFromSubscription() == 1 || notificationSettings.getNewVideoFromSubscription() == 3) { - if( notification.getVideo().getChannel().getAvatar() != null ) { + if (notificationSettings.getNewVideoFromSubscription() == 1 || notificationSettings.getNewVideoFromSubscription() == 3) { + if (notification.getVideo().getChannel().getAvatar() != null) { FutureTarget futureBitmapChannel = Glide.with(getApplicationContext()) .asBitmap() - .load("https://"+account.getHost()+notification.getVideo().getChannel().getAvatar().getPath()).submit(); + .load("https://" + account.getHost() + notification.getVideo().getChannel().getAvatar().getPath()).submit(); try { icon = futureBitmapChannel.get(); } catch (Exception e) { @@ -141,7 +141,7 @@ public class NotificationsWorker extends Worker { R.drawable.missing_peertube); } - }else{ + } else { icon = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.missing_peertube); } @@ -158,11 +158,11 @@ public class NotificationsWorker extends Worker { } break; case DisplayNotificationsFragment.NEW_COMMENT_ON_MY_VIDEO: - if(notificationSettings.getNewCommentOnMyVideo() == 1 || notificationSettings.getNewCommentOnMyVideo() == 3) { - if( notification.getComment().getAccount().getAvatar() != null ) { + if (notificationSettings.getNewCommentOnMyVideo() == 1 || notificationSettings.getNewCommentOnMyVideo() == 3) { + if (notification.getComment().getAccount().getAvatar() != null) { FutureTarget futureBitmapChannel = Glide.with(getApplicationContext()) .asBitmap() - .load("https://"+account.getHost()+ notification.getComment().getAccount().getAvatar().getPath()).submit(); + .load("https://" + account.getHost() + notification.getComment().getAccount().getAvatar().getPath()).submit(); try { icon = futureBitmapChannel.get(); } catch (Exception e) { @@ -170,7 +170,7 @@ public class NotificationsWorker extends Worker { R.drawable.missing_peertube); } - }else{ + } else { icon = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.missing_peertube); } @@ -191,31 +191,31 @@ public class NotificationsWorker extends Worker { break; case DisplayNotificationsFragment.BLACKLIST_ON_MY_VIDEO: - if(notificationSettings.getBlacklistOnMyVideo() == 1 || notificationSettings.getBlacklistOnMyVideo() == 3) { + if (notificationSettings.getBlacklistOnMyVideo() == 1 || notificationSettings.getBlacklistOnMyVideo() == 3) { title = getApplicationContext().getString(R.string.new_blacklist); message = getApplicationContext().getString(R.string.peertube_video_blacklist, notification.getVideo().getName()); } break; case DisplayNotificationsFragment.UNBLACKLIST_ON_MY_VIDEO: - if(notificationSettings.getBlacklistOnMyVideo() == 1 || notificationSettings.getBlacklistOnMyVideo() == 3) { + if (notificationSettings.getBlacklistOnMyVideo() == 1 || notificationSettings.getBlacklistOnMyVideo() == 3) { title = getApplicationContext().getString(R.string.new_blacklist); message = getApplicationContext().getString(R.string.peertube_video_unblacklist, notification.getVideo().getName()); } break; case DisplayNotificationsFragment.MY_VIDEO_PUBLISHED: - if(notificationSettings.getMyVideoPublished() == 1 || notificationSettings.getMyVideoPublished() == 3) { + if (notificationSettings.getMyVideoPublished() == 1 || notificationSettings.getMyVideoPublished() == 3) { title = getApplicationContext().getString(R.string.new_my_video_published); message = getApplicationContext().getString(R.string.peertube_video_published, notification.getVideo().getName()); } break; case DisplayNotificationsFragment.MY_VIDEO_IMPORT_SUCCESS: - if(notificationSettings.getMyVideoPublished() == 1 || notificationSettings.getMyVideoPublished() == 3) { + if (notificationSettings.getMyVideoPublished() == 1 || notificationSettings.getMyVideoPublished() == 3) { message = getApplicationContext().getString(R.string.peertube_video_import_success, notification.getVideo().getName()); title = getApplicationContext().getString(R.string.new_my_video_error); } break; case DisplayNotificationsFragment.MY_VIDEO_IMPORT_ERROR: - if(notificationSettings.getMyVideoPublished() == 1 || notificationSettings.getMyVideoPublished() == 3) { + if (notificationSettings.getMyVideoPublished() == 1 || notificationSettings.getMyVideoPublished() == 3) { message = getApplicationContext().getString(R.string.peertube_video_import_error, notification.getVideo().getName()); title = getApplicationContext().getString(R.string.new_my_video_error); } @@ -224,14 +224,14 @@ public class NotificationsWorker extends Worker { break; case DisplayNotificationsFragment.NEW_FOLLOW: - if(notificationSettings.getNewFollow() == 1 || notificationSettings.getNewFollow() == 3) { - if( notification.getVideo().getChannel().getAvatar() != null ) { + if (notificationSettings.getNewFollow() == 1 || notificationSettings.getNewFollow() == 3) { + if (notification.getVideo().getChannel().getAvatar() != null) { FutureTarget futureBitmapChannel = Glide.with(getApplicationContext()) .asBitmap() - .load("https://"+account.getHost()+notification.getVideo().getChannel().getAvatar().getPath()).submit(); + .load("https://" + account.getHost() + notification.getVideo().getChannel().getAvatar().getPath()).submit(); icon = futureBitmapChannel.get(); - }else{ + } else { icon = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.missing_peertube); } @@ -250,7 +250,7 @@ public class NotificationsWorker extends Worker { accountAction.setHost(actor.getHost()); accountAction.setUsername(actor.getName()); intent = new Intent(getApplicationContext(), ShowAccountActivity.class); - b.putParcelable("account", accountAction); + b.putParcelable("account", accountAction); b.putString("accountAcct", accountAction.getUsername() + "@" + accountAction.getHost()); intent.putExtras(b); } @@ -274,14 +274,14 @@ public class NotificationsWorker extends Worker { break; } - if( message != null && icon != null && title != null) { + if (message != null && icon != null && title != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) message = Html.fromHtml(message, Html.FROM_HTML_MODE_LEGACY).toString(); else message = Html.fromHtml(message).toString(); NotificationHelper.notify_user(getApplicationContext(), account, intent, icon, title, message); } - }else { + } else { break; } } diff --git a/app/src/main/java/app/fedilab/fedilabtube/worker/WorkHelper.java b/app/src/main/java/app/fedilab/fedilabtube/worker/WorkHelper.java index 1d5b2f9..93b3d8a 100644 --- a/app/src/main/java/app/fedilab/fedilabtube/worker/WorkHelper.java +++ b/app/src/main/java/app/fedilab/fedilabtube/worker/WorkHelper.java @@ -13,7 +13,9 @@ package app.fedilab.fedilabtube.worker; * * You should have received a copy of the GNU General Public License along with TubeLab; if not, * see . */ + import android.app.Application; + import androidx.work.BackoffPolicy; import androidx.work.Constraints; import androidx.work.ExistingPeriodicWorkPolicy; diff --git a/app/src/main/res/layout/drawer_about_instance.xml b/app/src/main/res/layout/drawer_about_instance.xml index 116d4fb..d89cd6f 100644 --- a/app/src/main/res/layout/drawer_about_instance.xml +++ b/app/src/main/res/layout/drawer_about_instance.xml @@ -32,21 +32,34 @@ android:layout_marginBottom="5dp"> + +