1
0
mirror of https://framagit.org/tom79/fedilab-tube synced 2025-06-05 21:09:11 +02:00

Last fixes

This commit is contained in:
Thomas
2020-11-11 10:34:28 +01:00
parent 17c84f6c37
commit 431c21e066
32 changed files with 537 additions and 514 deletions

View File

@ -41,7 +41,7 @@ public class FedilabTube extends MultiDexApplication {
.setMinimumLoggingLevel(android.util.Log.INFO) .setMinimumLoggingLevel(android.util.Log.INFO)
.build(); .build();
WorkManager.initialize(FedilabTube.this, myConfig); WorkManager.initialize(FedilabTube.this, myConfig);
if( interval >= 15 ) { if (interval >= 15) {
WorkHelper.fetchNotifications(this, interval); WorkHelper.fetchNotifications(this, interval);
} }
} }

View File

@ -101,7 +101,6 @@ public class LoginActivity extends AppCompatActivity {
} }
if (!BuildConfig.full_instances) { if (!BuildConfig.full_instances) {
binding.loginUid.setOnFocusChangeListener((v, hasFocus) -> { binding.loginUid.setOnFocusChangeListener((v, hasFocus) -> {
if (!hasFocus) { if (!hasFocus) {
@ -142,7 +141,7 @@ public class LoginActivity extends AppCompatActivity {
instance = host = binding.loginInstance.getText().toString().trim().toLowerCase(); instance = host = binding.loginInstance.getText().toString().trim().toLowerCase();
} }
if( instance.startsWith("http")) { if (instance.startsWith("http")) {
try { try {
URL url = new URL(instance); URL url = new URL(instance);
instance = url.getHost(); instance = url.getHost();
@ -151,7 +150,7 @@ public class LoginActivity extends AppCompatActivity {
e.printStackTrace(); 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(); Toasty.error(LoginActivity.this, getString(R.string.not_valide_instance)).show();
binding.loginButton.setEnabled(true); binding.loginButton.setEnabled(true);
return; return;
@ -216,7 +215,7 @@ public class LoginActivity extends AppCompatActivity {
oauthParams.setGrant_type("password"); oauthParams.setGrant_type("password");
oauthParams.setScope("user"); oauthParams.setScope("user");
oauthParams.setUsername(binding.loginUid.getText().toString().trim()); oauthParams.setUsername(binding.loginUid.getText().toString().trim());
if( binding.loginPasswd.getText() != null) { if (binding.loginPasswd.getText() != null) {
oauthParams.setPassword(binding.loginPasswd.getText().toString()); oauthParams.setPassword(binding.loginPasswd.getText().toString());
} }
try { try {

View File

@ -83,20 +83,11 @@ public class MainActivity extends AppCompatActivity {
public static int PICK_INSTANCE = 5641; public static int PICK_INSTANCE = 5641;
public static int PICK_INSTANCE_SURF = 5642; public static int PICK_INSTANCE_SURF = 5642;
public static UserMe userMe;
final FragmentManager fm = getSupportFragmentManager(); final FragmentManager fm = getSupportFragmentManager();
Fragment active; Fragment active;
private DisplayVideosFragment recentFragment, locaFragment, trendingFragment, subscriptionFragment, mostLikedFragment; private DisplayVideosFragment recentFragment, locaFragment, trendingFragment, subscriptionFragment, mostLikedFragment;
private DisplayOverviewFragment overviewFragment; private DisplayOverviewFragment overviewFragment;
public static UserMe userMe;
public enum TypeOfConnection{
UNKNOWN,
NORMAL,
SURFING
}
private TypeOfConnection typeOfConnection;
private final BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener private final BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= item -> { = item -> {
DisplayVideosFragment displayVideosFragment = null; DisplayVideosFragment displayVideosFragment = null;
@ -130,7 +121,66 @@ public class MainActivity extends AppCompatActivity {
return false; 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) { private void setTitleCustom(int titleRId) {
Toolbar toolbar = findViewById(R.id.toolbar); Toolbar toolbar = findViewById(R.id.toolbar);
@ -152,7 +202,7 @@ public class MainActivity extends AppCompatActivity {
navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
if( getSupportActionBar() != null) { if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowTitleEnabled(false); getSupportActionBar().setDisplayShowTitleEnabled(false);
} }
checkIfConnectedUsers(); checkIfConnectedUsers();
@ -225,31 +275,31 @@ public class MainActivity extends AppCompatActivity {
if (Helper.isLoggedIn(MainActivity.this)) { if (Helper.isLoggedIn(MainActivity.this)) {
navView.inflateMenu(R.menu.bottom_nav_menu_connected); navView.inflateMenu(R.menu.bottom_nav_menu_connected);
new Thread(() -> { new Thread(() -> {
final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String tokenStr = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); String tokenStr = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);
String instance = Helper.getLiveInstance(MainActivity.this); String instance = Helper.getLiveInstance(MainActivity.this);
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
String instanceShar = sharedpreferences.getString(Helper.PREF_INSTANCE, null); String instanceShar = sharedpreferences.getString(Helper.PREF_INSTANCE, null);
String userIdShar = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String userIdShar = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
Account account = new AccountDAO(MainActivity.this, db).getAccountByToken(tokenStr); Account account = new AccountDAO(MainActivity.this, db).getAccountByToken(tokenStr);
if( account == null) { if (account == null) {
account = new AccountDAO(MainActivity.this, db).getAccountByIdInstance(userIdShar, instanceShar); account = new AccountDAO(MainActivity.this, db).getAccountByIdInstance(userIdShar, instanceShar);
} }
if (account != null) { if (account != null) {
Account finalAccount = account; Account finalAccount = account;
OauthParams oauthParams = new OauthParams(); OauthParams oauthParams = new OauthParams();
oauthParams.setGrant_type("refresh_token"); oauthParams.setGrant_type("refresh_token");
oauthParams.setClient_id(account.getClient_id()); oauthParams.setClient_id(account.getClient_id());
oauthParams.setClient_secret(account.getClient_secret()); oauthParams.setClient_secret(account.getClient_secret());
oauthParams.setRefresh_token(account.getRefresh_token()); oauthParams.setRefresh_token(account.getRefresh_token());
oauthParams.setAccess_token(account.getToken()); oauthParams.setAccess_token(account.getToken());
try { try {
Token token = new RetrofitPeertubeAPI(MainActivity.this).manageToken(oauthParams); Token token = new RetrofitPeertubeAPI(MainActivity.this).manageToken(oauthParams);
if (token == null && Helper.instanceOnline(instance)) { if (token == null && Helper.instanceOnline(instance)) {
runOnUiThread(() -> Helper.logoutCurrentUser(MainActivity.this, finalAccount)); runOnUiThread(() -> Helper.logoutCurrentUser(MainActivity.this, finalAccount));
return; return;
}else if(token == null) { } else if (token == null) {
return; return;
} }
runOnUiThread(() -> { runOnUiThread(() -> {
@ -290,7 +340,8 @@ public class MainActivity extends AppCompatActivity {
runOnUiThread(() -> Helper.logoutCurrentUser(MainActivity.this, finalAccount)); runOnUiThread(() -> Helper.logoutCurrentUser(MainActivity.this, finalAccount));
error.printStackTrace(); error.printStackTrace();
} }
}}).start(); }
}).start();
} else { } else {
navView.inflateMenu(R.menu.bottom_nav_menu); 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})$"); 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()); Matcher matcherLink = link.matcher(query.trim());
if (matcherLink.find()) { if (matcherLink.find()) {
Intent intent = new Intent(MainActivity.this, PeertubeActivity.class); Intent intent = new Intent(MainActivity.this, PeertubeActivity.class);
intent.setData(Uri.parse(query.trim())); intent.setData(Uri.parse(query.trim()));
startActivity(intent); startActivity(intent);
myActionMenuItem.collapseActionView(); myActionMenuItem.collapseActionView();
return false; return false;
} }
Intent intent = new Intent(MainActivity.this, SearchActivity.class); Intent intent = new Intent(MainActivity.this, SearchActivity.class);
Bundle b = new Bundle(); Bundle b = new Bundle();
@ -370,18 +421,18 @@ public class MainActivity extends AppCompatActivity {
Toolbar toolbar = findViewById(R.id.toolbar); Toolbar toolbar = findViewById(R.id.toolbar);
ImageButton instances = toolbar.findViewById(R.id.instances); 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.setVisibility(View.VISIBLE);
instances.setOnClickListener(null); instances.setOnClickListener(null);
instances.setOnClickListener(v->{ instances.setOnClickListener(v -> {
Intent intent = new Intent(MainActivity.this, ManageInstancesActivity.class); Intent intent = new Intent(MainActivity.this, ManageInstancesActivity.class);
startActivity(intent); 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); instances.setVisibility(View.GONE);
} }
switch (typeOfConnection){ switch (typeOfConnection) {
case UNKNOWN: case UNKNOWN:
instanceItem.setVisible(false); instanceItem.setVisible(false);
accountItem.setVisible(false); accountItem.setVisible(false);
@ -438,14 +489,14 @@ public class MainActivity extends AppCompatActivity {
return true; return true;
} }
private void checkIfConnectedUsers(){ private void checkIfConnectedUsers() {
new Thread(() -> { new Thread(() -> {
try { try {
typeOfConnection = NORMAL; 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(); SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
List<Account> accounts = new AccountDAO(MainActivity.this, db).getAllAccount(); List<Account> 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 //The user is not authenticated and there accounts in db. That means the user is surfing some other instances
typeOfConnection = TypeOfConnection.SURFING; typeOfConnection = TypeOfConnection.SURFING;
} }
@ -472,7 +523,7 @@ public class MainActivity extends AppCompatActivity {
startActivity(intent); startActivity(intent);
} else if (item.getItemId() == R.id.action_account) { } else if (item.getItemId() == R.id.action_account) {
Intent intent; Intent intent;
if( typeOfConnection == SURFING) { if (typeOfConnection == SURFING) {
SwitchAccountHelper.switchDialog(MainActivity.this, false); SwitchAccountHelper.switchDialog(MainActivity.this, false);
} else { } else {
if (Helper.isLoggedIn(MainActivity.this)) { if (Helper.isLoggedIn(MainActivity.this)) {
@ -590,68 +641,6 @@ public class MainActivity extends AppCompatActivity {
alert.show(); 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") @SuppressLint("ApplySharedPref")
@Override @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { public void onActivityResult(int requestCode, int resultCode, Intent data) {
@ -662,17 +651,15 @@ public class MainActivity extends AppCompatActivity {
SharedPreferences.Editor editor = sharedpreferences.edit(); SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_INSTANCE, String.valueOf(data.getData())); editor.putString(Helper.PREF_INSTANCE, String.valueOf(data.getData()));
editor.commit(); 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(); finish();
} }
} }
} }
public enum TypeOfConnection {
UNKNOWN,
NORMAL,
SURFING
}
} }

View File

@ -17,20 +17,26 @@ package app.fedilab.fedilabtube;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.app.Activity; import android.app.Activity;
import android.content.Intent; import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler;
import android.view.MenuItem; import android.view.MenuItem;
import android.view.View; import android.view.View;
import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider; import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import app.fedilab.fedilabtube.client.RetrofitPeertubeAPI;
import app.fedilab.fedilabtube.client.data.InstanceData; import app.fedilab.fedilabtube.client.data.InstanceData;
import app.fedilab.fedilabtube.databinding.ActivityManageInstancesBinding; import app.fedilab.fedilabtube.databinding.ActivityManageInstancesBinding;
import app.fedilab.fedilabtube.drawer.AboutInstanceAdapter; import app.fedilab.fedilabtube.drawer.AboutInstanceAdapter;
import app.fedilab.fedilabtube.helper.Helper; 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 app.fedilab.fedilabtube.viewmodel.InfoInstanceVM;
import static app.fedilab.fedilabtube.MainActivity.PICK_INSTANCE_SURF; 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 { public class ManageInstancesActivity extends AppCompatActivity implements AboutInstanceAdapter.AllInstancesRemoved {
private ActivityManageInstancesBinding binding; private ActivityManageInstancesBinding binding;
private List<InstanceData.AboutInstance> aboutInstances;
private AboutInstanceAdapter aboutInstanceAdapter;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
@ -54,34 +62,43 @@ public class ManageInstancesActivity extends AppCompatActivity implements AboutI
binding.loader.setVisibility(View.VISIBLE); binding.loader.setVisibility(View.VISIBLE);
binding.noAction.setVisibility(View.GONE); binding.noAction.setVisibility(View.GONE);
binding.lvInstances.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); InfoInstanceVM viewModelInfoInstance = new ViewModelProvider(ManageInstancesActivity.this).get(InfoInstanceVM.class);
viewModelInfoInstance.getInstances().observe(ManageInstancesActivity.this, this::manageVIewInfoInstance); viewModelInfoInstance.getInstances().observe(ManageInstancesActivity.this, this::manageVIewInfoInstance);
} }
private void manageVIewInfoInstance(List<InstanceData.AboutInstance> aboutInstances) { private void manageVIewInfoInstance(List<InstanceData.AboutInstance> aboutInstances) {
binding.loader.setVisibility(View.GONE); binding.loader.setVisibility(View.GONE);
if( aboutInstances == null || aboutInstances.size() == 0) { if (aboutInstances == null || aboutInstances.size() == 0) {
binding.noAction.setVisibility(View.VISIBLE); binding.noAction.setVisibility(View.VISIBLE);
binding.lvInstances.setVisibility(View.GONE); binding.lvInstances.setVisibility(View.GONE);
return; return;
} }
binding.noAction.setVisibility(View.GONE); binding.noAction.setVisibility(View.GONE);
binding.lvInstances.setVisibility(View.VISIBLE); binding.lvInstances.setVisibility(View.VISIBLE);
this.aboutInstances.addAll(aboutInstances);
aboutInstanceAdapter.notifyItemRangeInserted(0, aboutInstances.size());
} }
@Override @Override
public void onBackPressed() { public void onBackPressed() {
super.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 @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) { if (item.getItemId() == android.R.id.home) {
finish(); 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 true;
} }
return super.onOptionsItemSelected(item); return super.onOptionsItemSelected(item);
@ -94,7 +111,13 @@ public class ManageInstancesActivity extends AppCompatActivity implements AboutI
super.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_INSTANCE_SURF && resultCode == Activity.RESULT_OK) { if (requestCode == PICK_INSTANCE_SURF && resultCode == Activity.RESULT_OK) {
if (data != null && data.getData() != null) { 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();
} }
} }
} }

View File

@ -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, * You should have received a copy of the GNU General Public License along with TubeLab; if not,
* see <http://www.gnu.org/licenses>. */ * see <http://www.gnu.org/licenses>. */
import android.Manifest; import android.Manifest;
import android.app.Activity; import android.app.Activity;
import android.content.Context; import android.content.Context;
@ -59,10 +60,10 @@ import static app.fedilab.fedilabtube.worker.WorkHelper.NOTIFICATION_WORKER;
public class MyAccountActivity extends AppCompatActivity { public class MyAccountActivity extends AppCompatActivity {
ActivityMyAccountSettingsBinding binding;
private static final int PICK_IMAGE = 466; private static final int PICK_IMAGE = 466;
ActivityMyAccountSettingsBinding binding;
private Uri inputData; private Uri inputData;
private String fileName; private String fileName;
private NotificationSettings notificationSettings; private NotificationSettings notificationSettings;
@Override @Override
@ -74,11 +75,11 @@ public class MyAccountActivity extends AppCompatActivity {
if (getSupportActionBar() != null) if (getSupportActionBar() != null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if( MainActivity.userMe == null) { if (MainActivity.userMe == null) {
finish(); finish();
return; return;
} }
setTitle(String.format("@%s",MainActivity.userMe.getUsername())); setTitle(String.format("@%s", MainActivity.userMe.getUsername()));
binding.displayname.setText(MainActivity.userMe.getAccount().getDisplayName()); binding.displayname.setText(MainActivity.userMe.getAccount().getDisplayName());
binding.description.setText(MainActivity.userMe.getAccount().getDescription()); 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.getNewCommentOnMyVideo(), binding.notifNewCommentApp, binding.notifNewCommentMail);
initializeValues(notificationSettings.getNewVideoFromSubscription(), binding.notifNewVideoApp, binding.notifNewVideoMail); 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); String[] refresh_array = getResources().getStringArray(R.array.refresh_time);
ArrayAdapter<String> refreshArray = new ArrayAdapter<>(MyAccountActivity.this, ArrayAdapter<String> refreshArray = new ArrayAdapter<>(MyAccountActivity.this,
@ -132,7 +133,7 @@ public class MyAccountActivity extends AppCompatActivity {
editor.putInt(Helper.NOTIFICATION_INTERVAL, time); editor.putInt(Helper.NOTIFICATION_INTERVAL, time);
editor.apply(); editor.apply();
WorkManager.getInstance(getApplicationContext()).cancelAllWorkByTag(NOTIFICATION_WORKER); WorkManager.getInstance(getApplicationContext()).cancelAllWorkByTag(NOTIFICATION_WORKER);
if( time > 0 ) { if (time > 0) {
WorkHelper.fetchNotifications(getApplication(), time); WorkHelper.fetchNotifications(getApplication(), time);
} }
@ -169,7 +170,7 @@ public class MyAccountActivity extends AppCompatActivity {
} }
binding.refreshTime.setSelection(position, false); binding.refreshTime.setSelection(position, false);
binding.selectFile.setOnClickListener(v->{ binding.selectFile.setOnClickListener(v -> {
if (ContextCompat.checkSelfPermission(MyAccountActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != if (ContextCompat.checkSelfPermission(MyAccountActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) { PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MyAccountActivity.this, ActivityCompat.requestPermissions(MyAccountActivity.this,
@ -204,13 +205,13 @@ public class MyAccountActivity extends AppCompatActivity {
new Thread(() -> { new Thread(() -> {
UserSettings userSettings = new UserSettings(); UserSettings userSettings = new UserSettings();
userSettings.setNotificationSettings(notificationSettings); userSettings.setNotificationSettings(notificationSettings);
if( binding.displayname.getText() != null) { if (binding.displayname.getText() != null) {
userSettings.setDisplayName(binding.displayname.getText().toString().trim()); userSettings.setDisplayName(binding.displayname.getText().toString().trim());
} }
if( binding.description.getText() != null) { if (binding.description.getText() != null) {
userSettings.setDescription(binding.description.getText().toString().trim()); userSettings.setDescription(binding.description.getText().toString().trim());
} }
if( inputData != null ) { if (inputData != null) {
userSettings.setAvatarfile(inputData); userSettings.setAvatarfile(inputData);
userSettings.setFileName(fileName); userSettings.setFileName(fileName);
} }
@ -219,7 +220,7 @@ public class MyAccountActivity extends AppCompatActivity {
UserMe.AvatarResponse avatarResponse = api.updateUser(userSettings); UserMe.AvatarResponse avatarResponse = api.updateUser(userSettings);
MainActivity.userMe.getAccount().setDisplayName(binding.displayname.getText().toString().trim()); MainActivity.userMe.getAccount().setDisplayName(binding.displayname.getText().toString().trim());
MainActivity.userMe.getAccount().setDescription(binding.description.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()); 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; int newValue;
if( checked && email.isChecked()) { if (checked && email.isChecked()) {
newValue = 3; newValue = 3;
}else if( !checked && email.isChecked()) { } else if (!checked && email.isChecked()) {
newValue = 2; newValue = 2;
} else if( checked && !email.isChecked()) { } else if (checked && !email.isChecked()) {
newValue = 1; newValue = 1;
}else { } else {
newValue = 0; newValue = 0;
} }
return newValue; return newValue;
} }
private int getNewMailCheckedValue(boolean checked, SwitchCompat app){ private int getNewMailCheckedValue(boolean checked, SwitchCompat app) {
int newValue; int newValue;
if( checked && app.isChecked()) { if (checked && app.isChecked()) {
newValue = 3; newValue = 3;
}else if( !checked && app.isChecked()) { } else if (!checked && app.isChecked()) {
newValue = 1; newValue = 1;
} else if( checked && !app.isChecked()) { } else if (checked && !app.isChecked()) {
newValue = 2; newValue = 2;
}else { } else {
newValue = 0; newValue = 0;
} }
return newValue; return newValue;

View File

@ -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 class PeertubeActivity extends AppCompatActivity implements CommentListAdapter.AllCommentRemoved, Player.EventListener, VideoListener, TorrentListener {
public static String video_id; public static String video_id;
public static List<String> playedVideos = new ArrayList<>();
private String peertubeInstance, videoUuid; private String peertubeInstance, videoUuid;
private FullScreenMediaController.fullscreen fullscreen; private FullScreenMediaController.fullscreen fullscreen;
private ImageView fullScreenIcon; private ImageView fullScreenIcon;
@ -175,16 +176,25 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
private List<Comment> commentsThread; private List<Comment> commentsThread;
private BroadcastReceiver mPowerKeyReceiver = null; private BroadcastReceiver mPowerKeyReceiver = null;
private boolean isPlayInMinimized; private boolean isPlayInMinimized;
public static List<String> playedVideos = new ArrayList<>();
private VideoData.Video nextVideo; private VideoData.Video nextVideo;
private TorrentStream torrentStream; private TorrentStream torrentStream;
private String show_more_content; 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 @Override
public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) { public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) {
if(width < height){ if (width < height) {
videoOrientationType = videoOrientation.PORTRAIT; videoOrientationType = videoOrientation.PORTRAIT;
}else{ } else {
videoOrientationType = videoOrientation.LANDSCAPE; videoOrientationType = videoOrientation.LANDSCAPE;
} }
} }
@ -213,22 +223,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
} }
@Override @Override
public void onStreamStopped() {} 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);
}
} }
@Override @Override
@ -286,12 +281,12 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
manageIntentUrl(intent); manageIntentUrl(intent);
binding.peertubeDescriptionMore.setOnClickListener(v->{ binding.peertubeDescriptionMore.setOnClickListener(v -> {
if( show_more_content != null && peertube != null) { if (show_more_content != null && peertube != null) {
if( binding.peertubeDescriptionMore.getText().toString().compareTo(getString(R.string.show_more)) == 0) { if (binding.peertubeDescriptionMore.getText().toString().compareTo(getString(R.string.show_more)) == 0) {
binding.peertubeDescriptionMore.setText(getString(R.string.show_less)); binding.peertubeDescriptionMore.setText(getString(R.string.show_less));
binding.peertubeDescription.setText(show_more_content); binding.peertubeDescription.setText(show_more_content);
}else{ } else {
binding.peertubeDescriptionMore.setText(getString(R.string.show_more)); binding.peertubeDescriptionMore.setText(getString(R.string.show_more));
binding.peertubeDescription.setText(peertube.getDescription()); binding.peertubeDescription.setText(peertube.getDescription());
} }
@ -327,7 +322,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
binding.peertubeInformationContainer.setVisibility(View.GONE); binding.peertubeInformationContainer.setVisibility(View.GONE);
if (videoOrientationType == videoOrientation.LANDSCAPE) { if (videoOrientationType == videoOrientation.LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}else { } else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} }
} else { } else {
@ -371,11 +366,11 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
public void onAnimationEnd() { public void onAnimationEnd() {
binding.mediaVideo.setVisibility(View.GONE); binding.mediaVideo.setVisibility(View.GONE);
} }
}) .playerView(binding.doubleTapPlayerView).seekSeconds(10); }).playerView(binding.doubleTapPlayerView).seekSeconds(10);
binding.doubleTapPlayerView.setPlayer(player); binding.doubleTapPlayerView.setPlayer(player);
binding.doubleTapPlayerView.controller(binding.mediaVideo); binding.doubleTapPlayerView.controller(binding.mediaVideo);
if( player != null) if (player != null)
binding.mediaVideo.player(player); binding.mediaVideo.player(player);
} }
flag_loading = true; flag_loading = true;
comments = new ArrayList<>(); comments = new ArrayList<>();
@ -411,26 +406,25 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
playVideo(); playVideo();
} }
registBroadcastReceiver(); registBroadcastReceiver();
if( autoFullscreen && autoPlay) { if (autoFullscreen && autoPlay) {
openFullscreenDialog(); openFullscreenDialog();
if (videoOrientationType == videoOrientation.LANDSCAPE) { if (videoOrientationType == videoOrientation.LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}else { } else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} }
} }
binding.postCommentButton.setOnClickListener(v-> openPostComment(null, 0)); binding.postCommentButton.setOnClickListener(v -> openPostComment(null, 0));
} }
private void manageVIewVideos(APIResponse apiResponse) { private void manageVIewVideos(APIResponse apiResponse) {
if (apiResponse == null || apiResponse.getPeertubes() == null || apiResponse.getPeertubes().size() == 0) { if (apiResponse == null || apiResponse.getPeertubes() == null || apiResponse.getPeertubes().size() == 0) {
playVideo(); playVideo();
return; return;
} }
peertube = apiResponse.getPeertubes().get(0); peertube = apiResponse.getPeertubes().get(0);
if( peertube.getUserHistory() != null) { if (peertube.getUserHistory() != null) {
player.seekTo(peertube.getUserHistory().getCurrentTime()*1000); player.seekTo(peertube.getUserHistory().getCurrentTime() * 1000);
} }
sepiaSearch = false; sepiaSearch = false;
playVideo(); playVideo();
@ -459,7 +453,6 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
} }
} }
public void manageVIewCommentReply(Comment comment, APIResponse apiResponse) { public void manageVIewCommentReply(Comment comment, APIResponse apiResponse) {
if (apiResponse == null || apiResponse.getError() != null || apiResponse.getCommentThreadData() == null) { if (apiResponse == null || apiResponse.getError() != null || apiResponse.getCommentThreadData() == null) {
if (apiResponse == null || apiResponse.getError() == null) if (apiResponse == null || apiResponse.getError() == null)
@ -504,7 +497,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
if (b != null) { if (b != null) {
peertubeInstance = b.getString("peertube_instance", Helper.getLiveInstance(PeertubeActivity.this)); peertubeInstance = b.getString("peertube_instance", Helper.getLiveInstance(PeertubeActivity.this));
videoUuid = b.getString("video_uuid", null); videoUuid = b.getString("video_uuid", null);
if( comments != null && comments.size() > 0) { if (comments != null && comments.size() > 0) {
int number = comments.size(); int number = comments.size();
comments.clear(); comments.clear();
commentListAdapter.notifyItemRangeRemoved(0, number); commentListAdapter.notifyItemRangeRemoved(0, number);
@ -515,14 +508,14 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
} }
private void manageIntentUrl(Intent intent) { 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(); 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})$"); 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); Matcher matcherLink = link.matcher(url);
if (matcherLink.find()) { if (matcherLink.find()) {
String instance = matcherLink.group(1); String instance = matcherLink.group(1);
String uuid = matcherLink.group(2); String uuid = matcherLink.group(2);
if(instance != null && uuid != null) { if (instance != null && uuid != null) {
peertubeInstance = instance.replace("https://", "").replace("http://", ""); 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. sepiaSearch = true; // Sepia search flag is used because, at this time we don't know if the video is federated.
videoUuid = uuid; videoUuid = uuid;
@ -531,11 +524,11 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
peertube.setEmbedUrl(url); peertube.setEmbedUrl(url);
SearchVM viewModelSearch = new ViewModelProvider(PeertubeActivity.this).get(SearchVM.class); SearchVM viewModelSearch = new ViewModelProvider(PeertubeActivity.this).get(SearchVM.class);
viewModelSearch.getVideos("0", peertube.getEmbedUrl()).observe(PeertubeActivity.this, this::manageVIewVideos); viewModelSearch.getVideos("0", peertube.getEmbedUrl()).observe(PeertubeActivity.this, this::manageVIewVideos);
}else { } else {
Helper.forwardToAnotherApp(PeertubeActivity.this, intent); Helper.forwardToAnotherApp(PeertubeActivity.this, intent);
finish(); finish();
} }
}else{ } else {
Helper.forwardToAnotherApp(PeertubeActivity.this, intent); Helper.forwardToAnotherApp(PeertubeActivity.this, intent);
finish(); finish();
} }
@ -554,14 +547,14 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
} }
show_more_content = null; show_more_content = null;
binding.peertubeDescriptionMore.setVisibility(View.GONE); binding.peertubeDescriptionMore.setVisibility(View.GONE);
if( autoFullscreen && autoPlay) { if (autoFullscreen && autoPlay) {
fullscreen = FullScreenMediaController.fullscreen.ON; fullscreen = FullScreenMediaController.fullscreen.ON;
setFullscreen(FullScreenMediaController.fullscreen.ON); setFullscreen(FullScreenMediaController.fullscreen.ON);
fullScreenMode = true; fullScreenMode = true;
openFullscreenDialog(); openFullscreenDialog();
if (videoOrientationType == videoOrientation.LANDSCAPE) { if (videoOrientationType == videoOrientation.LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}else { } else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} }
} else { } else {
@ -581,11 +574,11 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
VideoData.Description description = api.getVideoDescription(videoUuid); VideoData.Description description = api.getVideoDescription(videoUuid);
Handler mainHandler = new Handler(Looper.getMainLooper()); Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> { Runnable myRunnable = () -> {
if( description == null) { if (description == null) {
binding.peertubeDescriptionMore.setVisibility(View.GONE); binding.peertubeDescriptionMore.setVisibility(View.GONE);
show_more_content = null; show_more_content = null;
}else{ } else {
if( !PeertubeActivity.this.isFinishing()) { if (!PeertubeActivity.this.isFinishing()) {
if (peertube != null && peertube.getDescription() != null && description.getDescription().compareTo(peertube.getDescription()) > 0) { if (peertube != null && peertube.getDescription() != null && description.getDescription().compareTo(peertube.getDescription()) > 0) {
binding.peertubeDescriptionMore.setVisibility(View.VISIBLE); binding.peertubeDescriptionMore.setVisibility(View.VISIBLE);
show_more_content = description.getDescription(); show_more_content = description.getDescription();
@ -618,7 +611,6 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
} }
} }
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) { if (item.getItemId() == android.R.id.home) {
@ -676,7 +668,6 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
this.fullscreen = fullscreen; this.fullscreen = fullscreen;
} }
public void manageCaptions(APIResponse apiResponse) { public void manageCaptions(APIResponse apiResponse) {
if (apiResponse == null || (apiResponse.getError() != null) || apiResponse.getCaptions() == null || apiResponse.getCaptions().size() == 0) { if (apiResponse == null || (apiResponse.getError() != null) || apiResponse.getCaptions() == null || apiResponse.getCaptions().size() == 0) {
return; return;
@ -684,14 +675,13 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
captions = apiResponse.getCaptions(); captions = apiResponse.getCaptions();
} }
public void manageNextVideos(APIResponse apiResponse) { public void manageNextVideos(APIResponse apiResponse) {
if (apiResponse == null || apiResponse.getError() != null || apiResponse.getPeertubes() == null || apiResponse.getPeertubes().size() == 0) { if (apiResponse == null || apiResponse.getError() != null || apiResponse.getPeertubes() == null || apiResponse.getPeertubes().size() == 0) {
return; return;
} }
List<VideoData.Video> suggestedVideos = apiResponse.getPeertubes(); List<VideoData.Video> suggestedVideos = apiResponse.getPeertubes();
for(VideoData.Video video: suggestedVideos) { for (VideoData.Video video : suggestedVideos) {
if(!playedVideos.contains(video.getId())){ if (!playedVideos.contains(video.getId())) {
TimelineVM feedsViewModel = new ViewModelProvider(PeertubeActivity.this).get(TimelineVM.class); TimelineVM feedsViewModel = new ViewModelProvider(PeertubeActivity.this).get(TimelineVM.class);
feedsViewModel.getVideo(null, suggestedVideos.get(0).getUuid(), false).observe(PeertubeActivity.this, this::nextVideoDetails); feedsViewModel.getVideo(null, suggestedVideos.get(0).getUuid(), false).observe(PeertubeActivity.this, this::nextVideoDetails);
return; return;
@ -705,7 +695,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
return; return;
} }
int i = 0; 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++; i++;
} }
nextVideo = apiResponse.getPeertubes().get(i); nextVideo = apiResponse.getPeertubes().get(i);
@ -713,7 +703,6 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
player.addMediaItem(mediaItem); player.addMediaItem(mediaItem);
} }
@SuppressLint("ClickableViewAccessibility") @SuppressLint("ClickableViewAccessibility")
public void manageVIewVideo(APIResponse apiResponse) { public void manageVIewVideo(APIResponse apiResponse) {
if (apiResponse == null || (apiResponse.getError() != null) || apiResponse.getPeertubes() == null || apiResponse.getPeertubes().size() == 0) { 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; return;
} }
long position = -1; long position = -1;
if( peertube.getUserHistory() != null) { if (peertube.getUserHistory() != null) {
position = peertube.getUserHistory().getCurrentTime() * 1000; position = peertube.getUserHistory().getCurrentTime() * 1000;
} }
peertube = apiResponse.getPeertubes().get(0); 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); SearchVM searchViewModel = new ViewModelProvider(PeertubeActivity.this).get(SearchVM.class);
searchViewModel.searchNextVideos(peertube.getTags()).observe(PeertubeActivity.this, this::manageNextVideos); 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.peertubeDislikeCount.setText(Helper.withSuffix(peertube.getDislikes()));
binding.peertubeLikeCount.setText(Helper.withSuffix(peertube.getLikes())); binding.peertubeLikeCount.setText(Helper.withSuffix(peertube.getLikes()));
binding.peertubeViewCount.setText(Helper.withSuffix(peertube.getViews())); binding.peertubeViewCount.setText(Helper.withSuffix(peertube.getViews()));
loadGiF(PeertubeActivity.this,peertube.getChannel().getAvatar()!=null?peertube.getChannel().getAvatar().getPath():null, binding.ppChannel); loadGiF(PeertubeActivity.this, peertube.getChannel().getAvatar() != null ? peertube.getChannel().getAvatar().getPath() : null, binding.ppChannel);
binding.ppChannel.setOnClickListener(v->{ binding.ppChannel.setOnClickListener(v -> {
Intent intent = new Intent(PeertubeActivity.this, ShowChannelActivity.class); Intent intent = new Intent(PeertubeActivity.this, ShowChannelActivity.class);
Bundle b = new Bundle(); Bundle b = new Bundle();
b.putParcelable("channel", peertube.getChannel()); b.putParcelable("channel", peertube.getChannel());
@ -857,8 +846,8 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
binding.loader.setVisibility(View.GONE); binding.loader.setVisibility(View.GONE);
startStream( startStream(
apiResponse.getPeertubes().get(0).getFileUrl(null, PeertubeActivity.this), apiResponse.getPeertubes().get(0).getFileUrl(null, PeertubeActivity.this),
apiResponse.getPeertubes().get(0).getStreamingPlaylists().size()>0?apiResponse.getPeertubes().get(0).getStreamingPlaylists().get(0).getPlaylistUrl():null, apiResponse.getPeertubes().get(0).getStreamingPlaylists().size() > 0 ? apiResponse.getPeertubes().get(0).getStreamingPlaylists().get(0).getPlaylistUrl() : null,
autoPlay,position, null, null); autoPlay, position, null, null);
player.prepare(); player.prepare();
player.setPlayWhenReady(autoPlay); 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) { private void startStream(String videoURL, String streamingPlaylistsURLS, boolean autoPlay, long position, Uri subtitles, String lang) {
if (videoURL != null) { if (videoURL != null) {
if( videoURL.endsWith(".torrent")) { if (videoURL.endsWith(".torrent")) {
torrentStream.startStream(videoURL); torrentStream.startStream(videoURL);
return; return;
}else { } else {
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
int video_cache = sharedpreferences.getInt(Helper.SET_VIDEO_CACHE, Helper.DEFAULT_VIDEO_CACHE_MB); int video_cache = sharedpreferences.getInt(Helper.SET_VIDEO_CACHE, Helper.DEFAULT_VIDEO_CACHE_MB);
ProgressiveMediaSource videoSource; ProgressiveMediaSource videoSource;
@ -1019,7 +1008,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
Util.getUserAgent(PeertubeActivity.this, null), null); Util.getUserAgent(PeertubeActivity.this, null), null);
if (subtitles != 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); subtitleSource = new SingleSampleMediaSource.Factory(dataSourceFactory).createMediaSource(mediaSubtitle, C.TIME_UNSET);
} }
MediaItem mediaItem = new MediaItem.Builder().setUri(videoURL).build(); MediaItem mediaItem = new MediaItem.Builder().setUri(videoURL).build();
@ -1030,7 +1019,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
videoSource = new ProgressiveMediaSource.Factory(cacheDataSourceFactory) videoSource = new ProgressiveMediaSource.Factory(cacheDataSourceFactory)
.createMediaSource(mediaItem); .createMediaSource(mediaItem);
if (subtitles != null) { 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); subtitleSource = new SingleSampleMediaSource.Factory(cacheDataSourceFactory).createMediaSource(mediaSubtitle, C.TIME_UNSET);
} }
} }
@ -1038,7 +1027,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
MergingMediaSource mergedSource = MergingMediaSource mergedSource =
new MergingMediaSource(videoSource, subtitleSource); new MergingMediaSource(videoSource, subtitleSource);
player.setMediaSource(mergedSource); player.setMediaSource(mergedSource);
}else { } else {
player.setMediaSource(videoSource); player.setMediaSource(videoSource);
} }
} }
@ -1049,7 +1038,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
player.setMediaSource(hlsMediaSource); player.setMediaSource(hlsMediaSource);
} }
player.prepare(); player.prepare();
if( position > 0) { if (position > 0) {
player.seekTo(0, position); player.seekTo(0, position);
} }
player.setPlayWhenReady(autoPlay); player.setPlayWhenReady(autoPlay);
@ -1072,7 +1061,6 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
change(); change();
} }
@Override @Override
public void onDestroy() { public void onDestroy() {
super.onDestroy(); super.onDestroy();
@ -1080,7 +1068,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
if (player != null) { if (player != null) {
player.release(); player.release();
} }
if( torrentStream != null && torrentStream.isStreaming()) { if (torrentStream != null && torrentStream.isStreaming()) {
torrentStream.stopStream(); torrentStream.stopStream();
} }
unregisterReceiver(); unregisterReceiver();
@ -1107,12 +1095,12 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
@Override @Override
protected void onPause() { protected void onPause() {
super.onPause(); super.onPause();
if( player != null) { if (player != null) {
updateHistory(player.getCurrentPosition()/1000); updateHistory(player.getCurrentPosition() / 1000);
} }
if (player != null && (!isPlayInMinimized || !playInMinimized)) { if (player != null && (!isPlayInMinimized || !playInMinimized)) {
player.setPlayWhenReady(false); player.setPlayWhenReady(false);
}else if (playInMinimized) { } else if (playInMinimized) {
enterVideoMode(); enterVideoMode();
} }
} }
@ -1128,7 +1116,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
String strAction = intent.getAction(); String strAction = intent.getAction();
if (strAction.equals(Intent.ACTION_SCREEN_OFF)) { if (strAction.equals(Intent.ACTION_SCREEN_OFF)) {
if (player != null && isPlayInMinimized) { 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); player.setPlayWhenReady(false);
} }
} }
@ -1153,7 +1141,6 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
} }
} }
@RequiresApi(api = Build.VERSION_CODES.N) @RequiresApi(api = Build.VERSION_CODES.N)
@Override @Override
public void onUserLeaveHint() { public void onUserLeaveHint() {
@ -1175,14 +1162,13 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
} }
} }
@Override @Override
public void onBackPressed() { public void onBackPressed() {
if(binding.postComment.getVisibility() == View.VISIBLE){ if (binding.postComment.getVisibility() == View.VISIBLE) {
closePostComment(); closePostComment();
} else if (binding.replyThread.getVisibility() == View.VISIBLE) { } else if (binding.replyThread.getVisibility() == View.VISIBLE) {
closeCommentThread(); closeCommentThread();
} else { } else {
if (playInMinimized && player != null) { if (playInMinimized && player != null) {
enterVideoMode(); enterVideoMode();
} else { } else {
@ -1191,7 +1177,6 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
} }
} }
@Override @Override
public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode, Configuration newConfig) { public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode, Configuration newConfig) {
if (isInPictureInPictureMode) { if (isInPictureInPictureMode) {
@ -1205,7 +1190,6 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
} }
} }
public void displayResolution() { public void displayResolution() {
AlertDialog.Builder builderSingle = new AlertDialog.Builder(PeertubeActivity.this); AlertDialog.Builder builderSingle = new AlertDialog.Builder(PeertubeActivity.this);
builderSingle.setTitle(R.string.pickup_resolution); builderSingle.setTitle(R.string.pickup_resolution);
@ -1235,7 +1219,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
binding.loader.setVisibility(View.GONE); binding.loader.setVisibility(View.GONE);
startStream( startStream(
peertube.getFileUrl(res, PeertubeActivity.this), 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); true, position, null, null);
} }
@ -1243,15 +1227,14 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
builderSingle.show(); builderSingle.show();
} }
private void initFullscreenDialog() { private void initFullscreenDialog() {
fullScreenDialog = new Dialog(this, android.R.style.Theme_Black_NoTitleBar_Fullscreen) { fullScreenDialog = new Dialog(this, android.R.style.Theme_Black_NoTitleBar_Fullscreen) {
public void onBackPressed() { public void onBackPressed() {
if( player != null && player.isPlaying() && fullScreenMode) { if (player != null && player.isPlaying() && fullScreenMode) {
player.setPlayWhenReady(false); player.setPlayWhenReady(false);
} }
if( fullScreenMode) { if (fullScreenMode) {
closeFullscreenDialog(); closeFullscreenDialog();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Handler handler = new Handler(); Handler handler = new Handler();
@ -1272,16 +1255,12 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
fullScreenDialog.show(); fullScreenDialog.show();
} }
public void openCommentThread(Comment comment) { public void openCommentThread(Comment comment) {
CommentVM commentViewModel = new ViewModelProvider(PeertubeActivity.this).get(CommentVM.class); CommentVM commentViewModel = new ViewModelProvider(PeertubeActivity.this).get(CommentVM.class);
binding.peertubeReply.setVisibility(View.GONE); 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); binding.replyThread.setVisibility(View.VISIBLE);
@ -1310,14 +1289,14 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
private void sendComment(Comment comment, int position) { private void sendComment(Comment comment, int position) {
if (isLoggedIn(PeertubeActivity.this) && !sepiaSearch) { if (isLoggedIn(PeertubeActivity.this) && !sepiaSearch) {
if( comment == null) { if (comment == null) {
String commentStr = binding.addCommentWrite.getText().toString(); String commentStr = binding.addCommentWrite.getText().toString();
if (commentStr.trim().length() > 0) { if (commentStr.trim().length() > 0) {
PostActionsVM viewModelComment = new ViewModelProvider(PeertubeActivity.this).get(PostActionsVM.class); 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)); viewModelComment.comment(ADD_COMMENT, peertube.getId(), null, commentStr).observe(PeertubeActivity.this, apiResponse1 -> manageVIewPostActions(ADD_COMMENT, 0, apiResponse1));
binding.addCommentWrite.setText(""); binding.addCommentWrite.setText("");
} }
}else{ } else {
String commentView = binding.addCommentWrite.getText().toString(); String commentView = binding.addCommentWrite.getText().toString();
if (commentView.trim().length() > 0) { if (commentView.trim().length() > 0) {
PostActionsVM viewModelComment = new ViewModelProvider(PeertubeActivity.this).get(PostActionsVM.class); PostActionsVM viewModelComment = new ViewModelProvider(PeertubeActivity.this).get(PostActionsVM.class);
@ -1359,9 +1338,8 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
binding.replyThread.startAnimation(animate); binding.replyThread.startAnimation(animate);
} }
public void openPostComment(Comment comment, int position) { public void openPostComment(Comment comment, int position) {
if( comment != null) { if (comment != null) {
binding.replyContent.setVisibility(View.VISIBLE); binding.replyContent.setVisibility(View.VISIBLE);
Account account = comment.getAccount(); Account account = comment.getAccount();
Helper.loadGiF(PeertubeActivity.this, account.getAvatar() != null ? account.getAvatar().getPath() : null, binding.commentAccountProfile); 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()); commentSpan = Html.fromHtml(comment.getText());
binding.commentContent.setText(commentSpan); binding.commentContent.setText(commentSpan);
binding.commentDate.setText(Helper.dateDiff(PeertubeActivity.this, comment.getCreatedAt())); binding.commentDate.setText(Helper.dateDiff(PeertubeActivity.this, comment.getCreatedAt()));
}else{ } else {
binding.replyContent.setVisibility(View.GONE); binding.replyContent.setVisibility(View.GONE);
} }
binding.postComment.setVisibility(View.VISIBLE); binding.postComment.setVisibility(View.VISIBLE);
@ -1402,13 +1380,13 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
}); });
animateComment.setDuration(500); animateComment.setDuration(500);
binding.postComment.startAnimation(animateComment); binding.postComment.startAnimation(animateComment);
if( comment != null) { if (comment != null) {
binding.addCommentWrite.setText(String.format("@%s ", comment.getAccount().getAcct())); binding.addCommentWrite.setText(String.format("@%s ", comment.getAccount().getAcct()));
binding.addCommentWrite.setSelection(binding.addCommentWrite.getText().length()); binding.addCommentWrite.setSelection(binding.addCommentWrite.getText().length());
} }
binding.send.setOnClickListener(null); binding.send.setOnClickListener(null);
binding.send.setOnClickListener(v-> sendComment(comment, position)); binding.send.setOnClickListener(v -> sendComment(comment, position));
} }
private void closePostComment() { private void closePostComment() {
@ -1478,7 +1456,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
openFullscreenDialog(); openFullscreenDialog();
if (videoOrientationType == videoOrientation.LANDSCAPE) { if (videoOrientationType == videoOrientation.LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}else { } else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} }
} else { } else {
@ -1490,12 +1468,12 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
} }
}); });
ImageButton playButton = controlView.findViewById(R.id.exo_play); ImageButton playButton = controlView.findViewById(R.id.exo_play);
playButton.setOnClickListener(v->{ playButton.setOnClickListener(v -> {
if(autoFullscreen && !fullScreenMode) { if (autoFullscreen && !fullScreenMode) {
openFullscreenDialog(); openFullscreenDialog();
if (videoOrientationType == videoOrientation.LANDSCAPE) { if (videoOrientationType == videoOrientation.LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}else { } else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 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) { public void addElement(String playlistId, String videoId, APIResponse apiResponse) {
if (apiResponse != null && apiResponse.getActionReturn() != null) { if (apiResponse != null && apiResponse.getActionReturn() != null) {
@ -1626,12 +1603,10 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
} }
} }
private void updateHistory(long position) { private void updateHistory(long position) {
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
boolean storeInHistory = sharedpreferences.getBoolean(getString(R.string.set_store_in_history), true); 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(() -> { new Thread(() -> {
try { try {
RetrofitPeertubeAPI api = new RetrofitPeertubeAPI(PeertubeActivity.this); RetrofitPeertubeAPI api = new RetrofitPeertubeAPI(PeertubeActivity.this);
@ -1648,13 +1623,11 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
binding.noActionText.setVisibility(View.VISIBLE); binding.noActionText.setVisibility(View.VISIBLE);
} }
private void playNextVideo() { private void playNextVideo() {
if( nextVideo != null) { if (nextVideo != null) {
Intent intent = new Intent(PeertubeActivity.this, PeertubeActivity.class); Intent intent = new Intent(PeertubeActivity.this, PeertubeActivity.class);
Bundle b = new Bundle(); Bundle b = new Bundle();
b.putParcelable("video",nextVideo); b.putParcelable("video", nextVideo);
b.putString("video_id", nextVideo.getId()); b.putString("video_id", nextVideo.getId());
b.putString("video_uuid", nextVideo.getUuid()); b.putString("video_uuid", nextVideo.getUuid());
playedVideos.add(nextVideo.getId()); playedVideos.add(nextVideo.getId());
@ -1664,22 +1637,24 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
} }
} }
@Override @Override
public void onMediaItemTransition(MediaItem mediaItem, int reason) { public void onMediaItemTransition(MediaItem mediaItem, int reason) {
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
boolean autoplayNextVideo = sharedpreferences.getBoolean(getString(R.string.set_autoplay_next_video_choice), true); 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()); player.removeMediaItems(0, player.getMediaItemCount());
playNextVideo(); playNextVideo();
} }
} }
@Override @Override
public void onPlayerError(ExoPlaybackException error) { public void onPlayerError(ExoPlaybackException error) {
} }
enum videoOrientation {
LANDSCAPE,
PORTRAIT
}
} }

View File

@ -61,7 +61,6 @@ public class PeertubeRegisterActivity extends AppCompatActivity {
getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (BuildConfig.full_instances) { if (BuildConfig.full_instances) {
binding.loginInstanceContainer.setVisibility(View.VISIBLE); binding.loginInstanceContainer.setVisibility(View.VISIBLE);
binding.titleLoginInstance.setVisibility(View.VISIBLE); binding.titleLoginInstance.setVisibility(View.VISIBLE);
@ -114,21 +113,21 @@ public class PeertubeRegisterActivity extends AppCompatActivity {
setTextAgreement(); setTextAgreement();
binding.signup.setOnClickListener(view -> { binding.signup.setOnClickListener(view -> {
binding.errorMessage.setVisibility(View.GONE); 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 || 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()) { 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(); Toasty.error(PeertubeRegisterActivity.this, getString(R.string.all_field_filled)).show();
return; 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(); Toasty.error(PeertubeRegisterActivity.this, getString(R.string.password_error)).show();
return; 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(); Toasty.error(PeertubeRegisterActivity.this, getString(R.string.email_error)).show();
return; return;
} }
String[] emailArray = binding.email.getText().toString().split("@"); String[] emailArray = binding.email.getText().toString().split("@");
if (!BuildConfig.full_instances) { if (!BuildConfig.full_instances) {
if (emailArray.length > 1 && !Arrays.asList(Helper.valideEmails).contains(emailArray[1])) { if (emailArray.length > 1 && !Arrays.asList(Helper.valideEmails).contains(emailArray[1])) {
Toasty.error(PeertubeRegisterActivity.this, getString(R.string.email_error_domain, emailArray[1])).show(); 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(); Toasty.error(PeertubeRegisterActivity.this, getString(R.string.password_too_short)).show();
return; 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(); Toasty.error(PeertubeRegisterActivity.this, getString(R.string.username_error)).show();
return; return;
} }
binding.signup.setEnabled(false); binding.signup.setEnabled(false);
if (BuildConfig.full_instances) { if (BuildConfig.full_instances) {
if ( binding.loginInstance.getText() != null) { if (binding.loginInstance.getText() != null) {
instance = binding.loginInstance.getText().toString(); instance = binding.loginInstance.getText().toString();
} else { } else {
instance = ""; instance = "";
} }
@ -166,10 +165,10 @@ public class PeertubeRegisterActivity extends AppCompatActivity {
} }
AccountCreation accountCreation = new AccountCreation(); AccountCreation accountCreation = new AccountCreation();
accountCreation.setEmail( binding.email.getText().toString().trim()); accountCreation.setEmail(binding.email.getText().toString().trim());
accountCreation.setPassword( binding.password.getText().toString().trim()); accountCreation.setPassword(binding.password.getText().toString().trim());
accountCreation.setPasswordConfirm( binding.passwordConfirm.getText().toString().trim()); accountCreation.setPasswordConfirm(binding.passwordConfirm.getText().toString().trim());
accountCreation.setUsername( binding.username.getText().toString().trim()); accountCreation.setUsername(binding.username.getText().toString().trim());
accountCreation.setInstance(instance); accountCreation.setInstance(instance);
new Thread(() -> { new Thread(() -> {
@ -259,7 +258,7 @@ public class PeertubeRegisterActivity extends AppCompatActivity {
agreement_text.setMovementMethod(null); agreement_text.setMovementMethod(null);
agreement_text.setText(null); agreement_text.setText(null);
if (BuildConfig.full_instances) { if (BuildConfig.full_instances) {
if ( binding.loginInstance.getText() != null) { if (binding.loginInstance.getText() != null) {
content_agreement = getString(R.string.agreement_check_peertube, content_agreement = getString(R.string.agreement_check_peertube,
"<a href='https://" + binding.loginInstance.getText().toString() + "/about/instance#terms-section' >" + tos + "</a>" "<a href='https://" + binding.loginInstance.getText().toString() + "/about/instance#terms-section' >" + tos + "</a>"
); );

View File

@ -66,8 +66,8 @@ import static app.fedilab.fedilabtube.client.RetrofitPeertubeAPI.DataType.MY_CHA
public class PeertubeUploadActivity extends AppCompatActivity { public class PeertubeUploadActivity extends AppCompatActivity {
private final int PICK_IVDEO = 52378;
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 724; 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 Button set_upload_file, set_upload_submit;
private Spinner set_upload_privacy, set_upload_channel; private Spinner set_upload_privacy, set_upload_channel;
private TextView set_upload_file_name; private TextView set_upload_file_name;

View File

@ -134,7 +134,7 @@ public class ShowAccountActivity extends AppCompatActivity {
}); });
AlertDialog alertDialog = dialogBuilder.create(); AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show(); 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); Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.shared_via)); sendIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.shared_via));
String extra_text = account.getUrl(); String extra_text = account.getUrl();

View File

@ -159,7 +159,7 @@ public class ShowChannelActivity extends AppCompatActivity {
}); });
androidx.appcompat.app.AlertDialog alertDialog = dialogBuilder.create(); androidx.appcompat.app.AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show(); 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); Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.shared_via)); sendIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.shared_via));
String extra_text = channel.getUrl(); String extra_text = channel.getUrl();

View File

@ -68,7 +68,7 @@ public interface PeertubeService {
//Instance info //Instance info
@GET("config/about") @GET("config/about")
Call<InstanceData.AboutInstance> configAbout(); Call<InstanceData.InstanceInfo> configAbout();
@GET("{nodeInfoPath}") @GET("{nodeInfoPath}")
Call<WellKnownNodeinfo.NodeInfo> getNodeinfo(@Path(value = "nodeInfoPath", encoded = true) String nodeInfoPath); Call<WellKnownNodeinfo.NodeInfo> getNodeinfo(@Path(value = "nodeInfoPath", encoded = true) String nodeInfoPath);
@ -140,7 +140,7 @@ public interface PeertubeService {
@Field("description") String description, @Field("description") String description,
@Field("displayName") String displayName, @Field("displayName") String displayName,
@Field("nsfwPolicy") String nsfwPolicy @Field("nsfwPolicy") String nsfwPolicy
); );
@Multipart @Multipart
@POST("users/me/avatar/pick") @POST("users/me/avatar/pick")

View File

@ -166,9 +166,9 @@ public class RetrofitPeertubeAPI {
} }
private String getToken() { private String getToken() {
if( token != null) { if (token != null) {
return "Bearer " + token; return "Bearer " + token;
}else{ } else {
return null; return null;
} }
} }
@ -454,7 +454,7 @@ public class RetrofitPeertubeAPI {
/** /**
* Update history * Update history
* *
* @param videoId String * @param videoId String
* @param currentTime int * @param currentTime int
*/ */
public void updateHistory(String videoId, long currentTime) { public void updateHistory(String videoId, long currentTime) {
@ -525,10 +525,10 @@ public class RetrofitPeertubeAPI {
} }
byte[] imageBytes = byteBuffer.toByteArray(); byte[] imageBytes = byteBuffer.toByteArray();
String mime = MimeTypeMap.getFileExtensionFromUrl(userSettings.getAvatarfile().toString()); String mime = MimeTypeMap.getFileExtensionFromUrl(userSettings.getAvatarfile().toString());
if( mime == null || mime.trim().length() == 0) { if (mime == null || mime.trim().length() == 0) {
mime = "png"; 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); MultipartBody.Part bodyThumbnail = MultipartBody.Part.createFormData("avatarfile", userSettings.getFileName(), requestFile);
Call<UserMe.AvatarResponse> updateProfilePicture = peertubeService.updateProfilePicture(getToken(), bodyThumbnail); Call<UserMe.AvatarResponse> updateProfilePicture = peertubeService.updateProfilePicture(getToken(), bodyThumbnail);
Response<UserMe.AvatarResponse> responseAvatar = updateProfilePicture.execute(); Response<UserMe.AvatarResponse> responseAvatar = updateProfilePicture.execute();
@ -599,16 +599,17 @@ public class RetrofitPeertubeAPI {
/** /**
* About the instance * About the instance
*
* @return AboutInstance * @return AboutInstance
*/ */
public InstanceData.AboutInstance getAboutInstance() { public InstanceData.AboutInstance getAboutInstance() {
PeertubeService peertubeService = init(); PeertubeService peertubeService = init();
Call<InstanceData.AboutInstance> about = peertubeService.configAbout(); Call<InstanceData.InstanceInfo> about = peertubeService.configAbout();
try { try {
Response<InstanceData.AboutInstance> response = about.execute(); Response<InstanceData.InstanceInfo> response = about.execute();
if (response.isSuccessful() && response.body() != null) { if (response.isSuccessful() && response.body() != null) {
return response.body(); return response.body().getInstance();
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
@ -800,7 +801,7 @@ public class RetrofitPeertubeAPI {
*/ */
public APIResponse searchNextVideos(List<String> tags) { public APIResponse searchNextVideos(List<String> tags) {
PeertubeService peertubeService = init(); PeertubeService peertubeService = init();
Call<VideoData> searchVideosCall = peertubeService.searchNextVideo(getToken(), tags, "0" , "20"); Call<VideoData> searchVideosCall = peertubeService.searchNextVideo(getToken(), tags, "0", "20");
APIResponse apiResponse = new APIResponse(); APIResponse apiResponse = new APIResponse();
try { try {
Response<VideoData> response = searchVideosCall.execute(); Response<VideoData> response = searchVideosCall.execute();
@ -1058,7 +1059,6 @@ public class RetrofitPeertubeAPI {
} }
/** /**
* Get video description * Get video description
* *
@ -1071,9 +1071,10 @@ public class RetrofitPeertubeAPI {
try { try {
Response<VideoData.Description> response = videoDescription.execute(); Response<VideoData.Description> response = videoDescription.execute();
if (response.isSuccessful() && response.body() != null) { if (response.isSuccessful() && response.body() != null) {
return response.body(); return response.body();
} }
} catch (IOException ignored) {} } catch (IOException ignored) {
}
return null; return null;
} }

View File

@ -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") public AboutInstance getInstance() {
private String name; return instance;
@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 void setInstance(AboutInstance instance) {
this.instance = instance;
}
}
public static class AboutInstance implements Parcelable, Serializable {
public static final Creator<AboutInstance> CREATOR = new Creator<AboutInstance>() { public static final Creator<AboutInstance> CREATOR = new Creator<AboutInstance>() {
@Override @Override
public AboutInstance createFromParcel(Parcel in) { public AboutInstance createFromParcel(Parcel in) {
@ -276,6 +268,26 @@ public class InstanceData {
return new AboutInstance[size]; 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() { public String getName() {
return name; return name;

View File

@ -180,7 +180,7 @@ public class VideoData {
this.trackerUrls = in.createStringArrayList(); this.trackerUrls = in.createStringArrayList();
long tmpUpdatedAt = in.readLong(); long tmpUpdatedAt = in.readLong();
this.updatedAt = tmpUpdatedAt == -1 ? null : new Date(tmpUpdatedAt); 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.uuid = in.readString();
this.views = in.readInt(); this.views = in.readInt();
this.waitTranscoding = in.readByte() != 0; this.waitTranscoding = in.readByte() != 0;
@ -198,7 +198,7 @@ public class VideoData {
return file.getMagnetUri(); return file.getMagnetUri();
} else if (mode == Helper.VIDEO_MODE_TORRENT) { } else if (mode == Helper.VIDEO_MODE_TORRENT) {
return file.getTorrentUrl(); return file.getTorrentUrl();
}else { } else {
return file.getFileUrl(); 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<UserHistory> CREATOR = new Creator<UserHistory>() { public static final Creator<UserHistory> CREATOR = new Creator<UserHistory>() {
@Override @Override
@ -743,7 +743,7 @@ public class VideoData {
} }
public static class Description{ public static class Description {
@SerializedName("description") @SerializedName("description")
private String description; private String description;

View File

@ -9,6 +9,17 @@ import com.google.gson.annotations.SerializedName;
@SuppressWarnings({"unused", "RedundantSuppression"}) @SuppressWarnings({"unused", "RedundantSuppression"})
public class File implements Parcelable { public class File implements Parcelable {
public static final Parcelable.Creator<File> CREATOR = new Parcelable.Creator<File>() {
@Override
public File createFromParcel(Parcel source) {
return new File(source);
}
@Override
public File[] newArray(int size) {
return new File[size];
}
};
@SerializedName("fileDownloadUrl") @SerializedName("fileDownloadUrl")
private String fileDownloadUrl; private String fileDownloadUrl;
@SerializedName("fileUrl") @SerializedName("fileUrl")
@ -28,6 +39,21 @@ public class File implements Parcelable {
@SerializedName("torrentUrl") @SerializedName("torrentUrl")
private String 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() { public String getFileDownloadUrl() {
return fileDownloadUrl; return fileDownloadUrl;
} }
@ -100,7 +126,6 @@ public class File implements Parcelable {
this.torrentUrl = torrentUrl; this.torrentUrl = torrentUrl;
} }
@Override @Override
public int describeContents() { public int describeContents() {
return 0; return 0;
@ -118,31 +143,4 @@ public class File implements Parcelable {
dest.writeString(this.torrentDownloadUrl); dest.writeString(this.torrentDownloadUrl);
dest.writeString(this.torrentUrl); 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<File> CREATOR = new Parcelable.Creator<File>() {
@Override
public File createFromParcel(Parcel source) {
return new File(source);
}
@Override
public File[] newArray(int size) {
return new File[size];
}
};
} }

View File

@ -37,26 +37,14 @@ public class UserSettings {
return videosHistoryEnabled; return videosHistoryEnabled;
} }
public void setVideosHistoryEnabled(Boolean videosHistoryEnabled) {
this.videosHistoryEnabled = videosHistoryEnabled;
}
public Boolean isAutoPlayVideo() { public Boolean isAutoPlayVideo() {
return autoPlayVideo; return autoPlayVideo;
} }
public void setAutoPlayVideo(Boolean autoPlayVideo) {
this.autoPlayVideo = autoPlayVideo;
}
public Boolean isWebTorrentEnabled() { public Boolean isWebTorrentEnabled() {
return webTorrentEnabled; return webTorrentEnabled;
} }
public void setWebTorrentEnabled(Boolean webTorrentEnabled) {
this.webTorrentEnabled = webTorrentEnabled;
}
public List<String> getVideoLanguages() { public List<String> getVideoLanguages() {
return videoLanguages; return videoLanguages;
} }
@ -93,32 +81,44 @@ public class UserSettings {
return videosHistoryEnabled; return videosHistoryEnabled;
} }
public void setVideosHistoryEnabled(Boolean videosHistoryEnabled) {
this.videosHistoryEnabled = videosHistoryEnabled;
}
public Boolean getAutoPlayVideo() { public Boolean getAutoPlayVideo() {
return autoPlayVideo; return autoPlayVideo;
} }
public void setAutoPlayVideo(Boolean autoPlayVideo) {
this.autoPlayVideo = autoPlayVideo;
}
public Boolean getWebTorrentEnabled() { public Boolean getWebTorrentEnabled() {
return webTorrentEnabled; return webTorrentEnabled;
} }
public void setWebTorrentEnabled(Boolean webTorrentEnabled) {
this.webTorrentEnabled = webTorrentEnabled;
}
public Boolean isAutoPlayNextVideo() { public Boolean isAutoPlayNextVideo() {
return autoPlayNextVideo; return autoPlayNextVideo;
} }
public Boolean getAutoPlayNextVideo() {
return autoPlayNextVideo;
}
public void setAutoPlayNextVideo(Boolean autoPlayNextVideo) { public void setAutoPlayNextVideo(Boolean autoPlayNextVideo) {
this.autoPlayNextVideo = autoPlayNextVideo; this.autoPlayNextVideo = autoPlayNextVideo;
} }
public Boolean getAutoPlayNextVideo() {
return autoPlayNextVideo;
}
public String getFileName() { public String getFileName() {
return fileName; return fileName;
} }
public void setFileName(String fileName) { public void setFileName(String fileName) {
if( fileName == null) { if (fileName == null) {
this.fileName = "avatar.png"; this.fileName = "avatar.png";
} else { } else {
this.fileName = fileName; this.fileName = fileName;

View File

@ -22,10 +22,14 @@ import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Handler; import android.os.Handler;
import android.os.Looper; import android.os.Looper;
import android.text.Html;
import android.text.SpannableString;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.appcompat.widget.PopupMenu; import androidx.appcompat.widget.PopupMenu;
@ -35,24 +39,23 @@ import java.util.List;
import app.fedilab.fedilabtube.MainActivity; import app.fedilab.fedilabtube.MainActivity;
import app.fedilab.fedilabtube.R; import app.fedilab.fedilabtube.R;
import app.fedilab.fedilabtube.client.RetrofitPeertubeAPI;
import app.fedilab.fedilabtube.client.data.InstanceData; import app.fedilab.fedilabtube.client.data.InstanceData;
import app.fedilab.fedilabtube.databinding.DrawerAboutInstanceBinding; import app.fedilab.fedilabtube.databinding.DrawerAboutInstanceBinding;
import app.fedilab.fedilabtube.helper.Helper; import app.fedilab.fedilabtube.helper.Helper;
import app.fedilab.fedilabtube.sqlite.Sqlite; import app.fedilab.fedilabtube.sqlite.Sqlite;
import app.fedilab.fedilabtube.sqlite.StoredInstanceDAO; import app.fedilab.fedilabtube.sqlite.StoredInstanceDAO;
import static androidx.core.text.HtmlCompat.FROM_HTML_MODE_LEGACY;
public class AboutInstanceAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public class AboutInstanceAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final List<InstanceData.AboutInstance> aboutInstances; private final List<InstanceData.AboutInstance> aboutInstances;
private final AboutInstanceAdapter aboutInstanceAdapter;
public AllInstancesRemoved allInstancesRemoved; public AllInstancesRemoved allInstancesRemoved;
private Context context; private Context context;
public AboutInstanceAdapter(List<InstanceData.AboutInstance> aboutInstances) { public AboutInstanceAdapter(List<InstanceData.AboutInstance> aboutInstances) {
aboutInstanceAdapter = this;
this.aboutInstances = aboutInstances; this.aboutInstances = aboutInstances;
} }
@ -71,7 +74,7 @@ public class AboutInstanceAdapter extends RecyclerView.Adapter<RecyclerView.View
@Override @Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
context = parent.getContext(); context = parent.getContext();
DrawerAboutInstanceBinding itemBinding = DrawerAboutInstanceBinding .inflate(LayoutInflater.from(parent.getContext()), parent, false); DrawerAboutInstanceBinding itemBinding = DrawerAboutInstanceBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
return new ViewHolder(itemBinding); return new ViewHolder(itemBinding);
} }
@ -85,19 +88,29 @@ public class AboutInstanceAdapter extends RecyclerView.Adapter<RecyclerView.View
final InstanceData.AboutInstance aboutInstance = aboutInstances.get(i); final InstanceData.AboutInstance aboutInstance = aboutInstances.get(i);
holder.binding.aboutInstanceDescription.setText(aboutInstance.getShortDescription()); holder.binding.aboutInstanceHost.setText(aboutInstance.getHost());
SpannableString spannableString;
if (aboutInstance.getShortDescription() != null) {
if (Build.VERSION.SDK_INT >= 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.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); final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit(); SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_INSTANCE, aboutInstance.getHost()); editor.putString(Helper.PREF_INSTANCE, aboutInstance.getHost());
editor.commit(); editor.commit();
((Activity)context).runOnUiThread(() -> { ((Activity) context).runOnUiThread(() -> {
Intent intent = new Intent(context, MainActivity.class); Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent); context.startActivity(intent);
}); });
}); });
holder.binding.instanceMore.setOnClickListener(v->{ holder.binding.instanceMore.setOnClickListener(v -> {
PopupMenu popup = new PopupMenu(context, holder.binding.instanceMore); PopupMenu popup = new PopupMenu(context, holder.binding.instanceMore);
popup.getMenuInflater() popup.getMenuInflater()
.inflate(R.menu.instance_menu, popup.getMenu()); .inflate(R.menu.instance_menu, popup.getMenu());
@ -112,8 +125,10 @@ public class AboutInstanceAdapter extends RecyclerView.Adapter<RecyclerView.View
new Thread(() -> { new Thread(() -> {
SQLiteDatabase db = Sqlite.getInstance(context.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); SQLiteDatabase db = Sqlite.getInstance(context.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
new StoredInstanceDAO(context, db).removeInstance(aboutInstance.getHost()); new StoredInstanceDAO(context, db).removeInstance(aboutInstance.getHost());
aboutInstances.remove(aboutInstance);
Handler mainHandler = new Handler(Looper.getMainLooper()); Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> { Runnable myRunnable = () -> {
notifyItemRemoved(i);
if (aboutInstances.size() == 0) { if (aboutInstances.size() == 0) {
allInstancesRemoved.onAllInstancesRemoved(); allInstancesRemoved.onAllInstancesRemoved();
} }
@ -128,6 +143,7 @@ public class AboutInstanceAdapter extends RecyclerView.Adapter<RecyclerView.View
} }
return true; return true;
}); });
popup.show();
}); });
} }

View File

@ -74,10 +74,10 @@ public class CommentListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHo
private final List<Comment> comments; private final List<Comment> comments;
private final CommentListAdapter commentListAdapter; private final CommentListAdapter commentListAdapter;
private final boolean isThread;
public AllCommentRemoved allCommentRemoved; public AllCommentRemoved allCommentRemoved;
boolean isVideoOwner; boolean isVideoOwner;
private Context context; private Context context;
private final boolean isThread;
public CommentListAdapter(List<Comment> comments, boolean isVideoOwner, boolean isThread) { public CommentListAdapter(List<Comment> comments, boolean isVideoOwner, boolean isThread) {
this.comments = comments; this.comments = comments;
@ -125,11 +125,11 @@ public class CommentListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHo
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT LinearLayout.LayoutParams.WRAP_CONTENT
); );
if( comment.isReply()) { if (comment.isReply()) {
int ident = CommentDecorationHelper.getIndentation(comment.getInReplyToCommentId(), comments); int ident = CommentDecorationHelper.getIndentation(comment.getInReplyToCommentId(), comments);
holder.decoration.setVisibility(View.VISIBLE); holder.decoration.setVisibility(View.VISIBLE);
params.setMargins((int)Helper.convertDpToPixel(ident*15, context), 0, 0, 0); params.setMargins((int) Helper.convertDpToPixel(ident * 15, context), 0, 0, 0);
}else{ } else {
holder.decoration.setVisibility(View.GONE); holder.decoration.setVisibility(View.GONE);
params.setMargins(0, 0, 0, 0); params.setMargins(0, 0, 0, 0);
} }
@ -284,9 +284,9 @@ public class CommentListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHo
} else { } else {
holder.replyButton.setVisibility(View.GONE); holder.replyButton.setVisibility(View.GONE);
} }
if( i == 0 && isThread) { if (i == 0 && isThread) {
holder.post_reply_button.setVisibility(View.VISIBLE); holder.post_reply_button.setVisibility(View.VISIBLE);
}else { } else {
holder.post_reply_button.setVisibility(View.GONE); holder.post_reply_button.setVisibility(View.GONE);
} }
holder.post_reply_button.setOnClickListener(v -> ((PeertubeActivity) context).openPostComment(comment, i)); holder.post_reply_button.setOnClickListener(v -> ((PeertubeActivity) context).openPostComment(comment, i));
@ -375,8 +375,8 @@ public class CommentListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHo
more_actions = itemView.findViewById(R.id.more_actions); more_actions = itemView.findViewById(R.id.more_actions);
number_of_replies = itemView.findViewById(R.id.number_of_replies); number_of_replies = itemView.findViewById(R.id.number_of_replies);
replyButton = itemView.findViewById(R.id.replyButton); replyButton = itemView.findViewById(R.id.replyButton);
decoration = itemView.findViewById(R.id.decoration); decoration = itemView.findViewById(R.id.decoration);
post_reply_button = itemView.findViewById(R.id.post_reply_button); post_reply_button = itemView.findViewById(R.id.post_reply_button);
} }

View File

@ -129,11 +129,11 @@ public class PeertubeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde
holder.peertube_views.setText(context.getString(R.string.number_view_video, Helper.withSuffix(video.getViews()))); holder.peertube_views.setText(context.getString(R.string.number_view_video, Helper.withSuffix(video.getViews())));
boolean blur = sharedpreferences.getString(context.getString(R.string.set_video_sensitive_choice), Helper.BLUR).compareTo("blur") == 0 && video.isNsfw(); boolean blur = sharedpreferences.getString(context.getString(R.string.set_video_sensitive_choice), Helper.BLUR).compareTo("blur") == 0 && video.isNsfw();
if(videoInList) { if (videoInList) {
Helper.loadGiF(context, instance, video.getThumbnailPath(), holder.peertube_video_image_small, blur); Helper.loadGiF(context, instance, video.getThumbnailPath(), holder.peertube_video_image_small, blur);
holder.peertube_video_image_small.setVisibility(View.VISIBLE); holder.peertube_video_image_small.setVisibility(View.VISIBLE);
holder.preview_container.setVisibility(View.GONE); holder.preview_container.setVisibility(View.GONE);
}else{ } else {
Helper.loadGiF(context, instance, video.getThumbnailPath(), holder.peertube_video_image, blur); Helper.loadGiF(context, instance, video.getThumbnailPath(), holder.peertube_video_image, blur);
holder.peertube_video_image_small.setVisibility(View.GONE); holder.peertube_video_image_small.setVisibility(View.GONE);
holder.preview_container.setVisibility(View.VISIBLE); holder.preview_container.setVisibility(View.VISIBLE);

View File

@ -21,21 +21,6 @@ import androidx.preference.PreferenceScreen;
import androidx.preference.SeekBarPreference; import androidx.preference.SeekBarPreference;
import androidx.preference.SwitchPreference; import androidx.preference.SwitchPreference;
/* 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 <http://www.gnu.org/licenses>. */
import com.bumptech.glide.Glide; import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget; import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition; 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.peertubeInformation;
import static app.fedilab.fedilabtube.MainActivity.userMe; 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 <http://www.gnu.org/licenses>. */
public class SettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener { public class SettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override @Override
@ -135,7 +135,7 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared
if (set_video_sensitive_choice != null) { if (set_video_sensitive_choice != null) {
editor.putString(getString(R.string.set_video_sensitive_choice), set_video_sensitive_choice.getValue()); editor.putString(getString(R.string.set_video_sensitive_choice), set_video_sensitive_choice.getValue());
editor.apply(); editor.apply();
if(Helper.isLoggedIn(getActivity())) { if (Helper.isLoggedIn(getActivity())) {
new Thread(() -> { new Thread(() -> {
UserSettings userSettings = new UserSettings(); UserSettings userSettings = new UserSettings();
userSettings.setNsfwPolicy(set_video_sensitive_choice.getValue()); 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)); SwitchPreference set_autoplay_choice = findPreference(getString(R.string.set_autoplay_choice));
assert set_autoplay_choice != null; assert set_autoplay_choice != null;
editor.putBoolean(getString(R.string.set_autoplay_choice), set_autoplay_choice.isChecked()); editor.putBoolean(getString(R.string.set_autoplay_choice), set_autoplay_choice.isChecked());
if(Helper.isLoggedIn(getActivity())) { if (Helper.isLoggedIn(getActivity())) {
new Thread(() -> { new Thread(() -> {
UserSettings userSettings = new UserSettings(); UserSettings userSettings = new UserSettings();
userSettings.setAutoPlayVideo(set_autoplay_choice.isChecked()); 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)); SwitchPreference set_autoplay_next_video_choice = findPreference(getString(R.string.set_autoplay_next_video_choice));
assert set_autoplay_next_video_choice != null; assert set_autoplay_next_video_choice != null;
editor.putBoolean(getString(R.string.set_autoplay_next_video_choice), set_autoplay_next_video_choice.isChecked()); 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(() -> { new Thread(() -> {
UserSettings userSettings = new UserSettings(); UserSettings userSettings = new UserSettings();
userSettings.setAutoPlayNextVideo(set_autoplay_next_video_choice.isChecked()); 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)); MultiSelectListPreference set_video_language_choice = findPreference(getString(R.string.set_video_language_choice));
assert set_video_language_choice != null; assert set_video_language_choice != null;
editor.putStringSet(getString(R.string.set_video_language_choice), set_video_language_choice.getValues()); editor.putStringSet(getString(R.string.set_video_language_choice), set_video_language_choice.getValues());
if(Helper.isLoggedIn(getActivity())) { if (Helper.isLoggedIn(getActivity())) {
new Thread(() -> { new Thread(() -> {
UserSettings userSettings = new UserSettings(); UserSettings userSettings = new UserSettings();
Set<String> language_choiceValues = set_video_language_choice.getValues(); Set<String> language_choiceValues = set_video_language_choice.getValues();
@ -266,7 +266,7 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared
Preference my_account = findPreference("my_account"); Preference my_account = findPreference("my_account");
assert my_account != null; assert my_account != null;
if(!Helper.isLoggedIn(getActivity()) || userMe == null) { if (!Helper.isLoggedIn(getActivity()) || userMe == null) {
my_account.setVisible(false); my_account.setVisible(false);
} else { } else {
my_account.setTitle(userMe.getUsername()); 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); Drawable defaultAvatar = ResourcesCompat.getDrawable(resources, R.drawable.missing_peertube, null);
my_account.setIcon(defaultAvatar); my_account.setIcon(defaultAvatar);
Glide.with(getActivity()) Glide.with(getActivity())
.asDrawable() .asDrawable()
.load("https://" + Helper.getLiveInstance(context) + userMe.getAccount().getAvatar().getPath()) .load("https://" + Helper.getLiveInstance(context) + userMe.getAccount().getAvatar().getPath())
.into(new CustomTarget<Drawable>() { .into(new CustomTarget<Drawable>() {
@Override @Override
public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) { public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
my_account.setIcon(resource); my_account.setIcon(resource);
} }
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
} @Override
}); public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
} }
@ -307,7 +308,6 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared
} }
//****** Video mode ******* //****** Video mode *******
ListPreference set_video_mode_choice = findPreference(getString(R.string.set_video_mode_choice)); ListPreference set_video_mode_choice = findPreference(getString(R.string.set_video_mode_choice));
List<String> array = Arrays.asList(getResources().getStringArray(R.array.settings_video_mode)); List<String> 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)); SwitchPreference set_video_minimize_choice = findPreference(getString(R.string.set_video_minimize_choice));
assert set_video_minimize_choice != null; assert set_video_minimize_choice != null;
set_video_minimize_choice.setChecked(minimized); 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)) { || !getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) {
set_video_minimize_choice.setVisible(false); set_video_minimize_choice.setVisible(false);
} }
@ -422,8 +422,8 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared
entryValuesSensitive[1] = Helper.BLUR.toLowerCase(); entryValuesSensitive[1] = Helper.BLUR.toLowerCase();
entryValuesSensitive[2] = Helper.DISPLAY.toLowerCase(); entryValuesSensitive[2] = Helper.DISPLAY.toLowerCase();
int currentSensitivePosition = 0; int currentSensitivePosition = 0;
for(CharSequence val : entryValuesSensitive) { for (CharSequence val : entryValuesSensitive) {
if(val.equals(currentSensitive)) { if (val.equals(currentSensitive)) {
break; break;
} }
currentSensitivePosition++; currentSensitivePosition++;

View File

@ -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, * You should have received a copy of the GNU General Public License along with TubeLab; if not,
* see <http://www.gnu.org/licenses>. */ * see <http://www.gnu.org/licenses>. */
import java.util.List; import java.util.List;
import app.fedilab.fedilabtube.client.data.CommentData; import app.fedilab.fedilabtube.client.data.CommentData;
public class CommentDecorationHelper { public class CommentDecorationHelper {
public static int getIndentation(String replyToCommentId, List<CommentData.Comment> comments){ public static int getIndentation(String replyToCommentId, List<CommentData.Comment> comments) {
return numberOfIndentation(0, replyToCommentId, comments); return numberOfIndentation(0, replyToCommentId, comments);
} }
private static int numberOfIndentation(int currentIdentation, String replyToCommentId, List<CommentData.Comment> comments) { private static int numberOfIndentation(int currentIdentation, String replyToCommentId, List<CommentData.Comment> comments) {
String targetedComment = null; String targetedComment = null;
for(CommentData.Comment comment: comments) { for (CommentData.Comment comment : comments) {
if( replyToCommentId.compareTo(comment.getId()) == 0) { if (replyToCommentId.compareTo(comment.getId()) == 0) {
targetedComment = comment.getInReplyToCommentId(); targetedComment = comment.getInReplyToCommentId();
break; break;
} }
} }
if ( targetedComment != null) { if (targetedComment != null) {
currentIdentation++; currentIdentation++;
return numberOfIndentation(currentIdentation, targetedComment, comments); return numberOfIndentation(currentIdentation, targetedComment, comments);
}else{ } else {
return Math.min(currentIdentation, 5); return Math.min(currentIdentation, 5);
} }
} }

View File

@ -479,12 +479,12 @@ public class Helper {
RequestBuilder<Drawable> requestBuilder = Glide.with(imageView.getContext()) RequestBuilder<Drawable> requestBuilder = Glide.with(imageView.getContext())
.load(url) .load(url)
.thumbnail(0.1f); .thumbnail(0.1f);
if( blur ) { if (blur) {
requestBuilder.apply(new RequestOptions().transform(new BlurTransformation(50, 3), new CenterCrop(), new RoundedCorners(10))); requestBuilder.apply(new RequestOptions().transform(new BlurTransformation(50, 3), new CenterCrop(), new RoundedCorners(10)));
}else { } else {
requestBuilder.apply(new RequestOptions().transform(new CenterCrop(), new RoundedCorners(round))); requestBuilder.apply(new RequestOptions().transform(new CenterCrop(), new RoundedCorners(round)));
} }
requestBuilder.into(imageView); requestBuilder.into(imageView);
} catch (Exception e) { } catch (Exception e) {
try { try {
Glide.with(imageView.getContext()) Glide.with(imageView.getContext())
@ -706,7 +706,7 @@ public class Helper {
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String userName = sharedpreferences.getString(Helper.PREF_KEY_NAME, ""); String userName = sharedpreferences.getString(Helper.PREF_KEY_NAME, "");
String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, ""); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, "");
if( video == null) { if (video == null) {
return false; return false;
} }
Account account = video.getAccount(); Account account = video.getAccount();
@ -748,8 +748,9 @@ public class Helper {
/** /**
* Forward the intent (open an URL) to another app * Forward the intent (open an URL) to another app
*
* @param activity Activity * @param activity Activity
* @param i Intent * @param i Intent
*/ */
public static void forwardToAnotherApp(Activity activity, Intent i) { public static void forwardToAnotherApp(Activity activity, Intent i) {
Intent intent = new Intent(); Intent intent = new Intent();

View File

@ -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, * You should have received a copy of the GNU General Public License along with TubeLab; if not,
* see <http://www.gnu.org/licenses>. */ * see <http://www.gnu.org/licenses>. */
import android.app.Notification; import android.app.Notification;
import android.app.NotificationChannel; import android.app.NotificationChannel;
import android.app.NotificationManager; import android.app.NotificationManager;

View File

@ -23,7 +23,6 @@ import androidx.appcompat.app.AlertDialog;
import java.util.List; import java.util.List;
import app.fedilab.fedilabtube.LoginActivity; import app.fedilab.fedilabtube.LoginActivity;
import app.fedilab.fedilabtube.MainActivity; import app.fedilab.fedilabtube.MainActivity;
import app.fedilab.fedilabtube.R; import app.fedilab.fedilabtube.R;
@ -37,7 +36,7 @@ import static android.content.Context.MODE_PRIVATE;
public class SwitchAccountHelper { 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(); SQLiteDatabase db = Sqlite.getInstance(activity.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
List<AccountData.Account> accounts = new AccountDAO(activity, db).getAllAccount(); List<AccountData.Account> accounts = new AccountDAO(activity, db).getAllAccount();
@ -67,7 +66,7 @@ public class SwitchAccountHelper {
}); });
} }
builderSingle.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()); builderSingle.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
if( withAddAccount) { if (withAddAccount) {
builderSingle.setPositiveButton(R.string.add_account, (dialog, which) -> { builderSingle.setPositiveButton(R.string.add_account, (dialog, which) -> {
Intent intent = new Intent(activity, LoginActivity.class); Intent intent = new Intent(activity, LoginActivity.class);
activity.startActivity(intent); activity.startActivity(intent);

View File

@ -127,7 +127,7 @@ public class RetrieveInfoService extends Service implements NetworkStateReceiver
@Override @Override
public void run() { public void run() {
EmojiHelper.fillMapEmoji(getApplicationContext()); EmojiHelper.fillMapEmoji(getApplicationContext());
if( peertubeInformation == null || peertubeInformation.getCategories().size() == 0) { if (peertubeInformation == null || peertubeInformation.getCategories().size() == 0) {
peertubeInformation = new PeertubeInformation(); peertubeInformation = new PeertubeInformation();
peertubeInformation.setCategories(new LinkedHashMap<>()); peertubeInformation.setCategories(new LinkedHashMap<>());
peertubeInformation.setLanguages(new LinkedHashMap<>()); peertubeInformation.setLanguages(new LinkedHashMap<>());

View File

@ -252,7 +252,7 @@ public class AccountDAO {
/** /**
* Returns an Account by id and instance * Returns an Account by id and instance
* *
* @param id String * @param id String
* @param instance String * @param instance String
* @return Account * @return Account
*/ */
@ -266,6 +266,7 @@ public class AccountDAO {
return null; return null;
} }
} }
/** /**
* Test if the current user is already stored in data base * Test if the current user is already stored in data base
* *

View File

@ -59,6 +59,9 @@ public class Sqlite extends SQLiteOpenHelper {
static final String COL_UUID = "UUID"; static final String COL_UUID = "UUID";
static final String COL_CACHE = "CACHE"; static final String COL_CACHE = "CACHE";
static final String COL_DATE = "DATE"; 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 + " (" 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_USER_ID + " TEXT, " + COL_USERNAME + " TEXT NOT NULL, " + COL_ACCT + " TEXT NOT NULL, "
+ COL_DISPLAYED_NAME + " TEXT NOT NULL, " + COL_LOCKED + " INTEGER 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_INSTANCE + " TEXT NOT NULL, "
+ COL_CACHE + " TEXT NOT NULL, " + COL_CACHE + " TEXT NOT NULL, "
+ COL_DATE + " 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 " private final String CREATE_TABLE_STORED_INSTANCES = "CREATE TABLE "
+ TABLE_BOOKMARKED_INSTANCES + "(" + TABLE_BOOKMARKED_INSTANCES + "("
+ COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
@ -118,7 +117,7 @@ public class Sqlite extends SQLiteOpenHelper {
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch (oldVersion) { switch (oldVersion) {
case 2: case 2:
db.execSQL("DROP TABLE IF EXISTS " +TABLE_BOOKMARKED_INSTANCES); db.execSQL("DROP TABLE IF EXISTS " + TABLE_BOOKMARKED_INSTANCES);
} }
} }

View File

@ -42,36 +42,6 @@ public class StoredInstanceDAO {
this.db = db; 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 * Unserialized AboutInstance
* *
@ -105,7 +75,36 @@ public class StoredInstanceDAO {
/** /**
* Insert instance info in database * 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 * @param targetedInstance String
* @return int * @return int
*/ */
@ -125,11 +124,10 @@ public class StoredInstanceDAO {
public int removeInstance(String instance) { 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 * Returns all Instance in db
* *
@ -147,7 +145,6 @@ public class StoredInstanceDAO {
} }
/*** /***
* Method to hydrate an Account from database * Method to hydrate an Account from database
* @param c Cursor * @param c Cursor
@ -184,7 +181,9 @@ public class StoredInstanceDAO {
List<InstanceData.AboutInstance> aboutInstances = new ArrayList<>(); List<InstanceData.AboutInstance> aboutInstances = new ArrayList<>();
while (c.moveToNext()) { while (c.moveToNext()) {
String aboutInstanceStr = c.getString(c.getColumnIndex(Sqlite.COL_ABOUT)); String aboutInstanceStr = c.getString(c.getColumnIndex(Sqlite.COL_ABOUT));
String instance = c.getString(c.getColumnIndex(Sqlite.COL_INSTANCE));
InstanceData.AboutInstance aboutInstance = restoreAboutInstanceFromString(aboutInstanceStr); InstanceData.AboutInstance aboutInstance = restoreAboutInstanceFromString(aboutInstanceStr);
aboutInstance.setHost(instance);
aboutInstances.add(aboutInstance); aboutInstances.add(aboutInstance);
} }
//Close the cursor //Close the cursor

View File

@ -37,17 +37,15 @@ import app.fedilab.fedilabtube.R;
public class MastalabWebChromeClient extends WebChromeClient implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener { 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 CustomWebview webView;
private final View activityNonVideoView; private final View activityNonVideoView;
private final ViewGroup activityVideoView; private final ViewGroup activityVideoView;
private final ProgressBar pbar; private final ProgressBar pbar;
private boolean isVideoFullscreen;
private final Activity activity; 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) { 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) { public void onShowCustomView(View view, CustomViewCallback callback) {
if (view instanceof FrameLayout) { if (view instanceof FrameLayout) {
if (((AppCompatActivity) activity).getSupportActionBar() != null) if (((AppCompatActivity) activity).getSupportActionBar() != null)
//noinspection ConstantConditions
((AppCompatActivity) activity).getSupportActionBar().hide(); ((AppCompatActivity) activity).getSupportActionBar().hide();
// A video wants to be shown // A video wants to be shown
FrameLayout frameLayout = (FrameLayout) view; FrameLayout frameLayout = (FrameLayout) view;
@ -178,7 +175,6 @@ public class MastalabWebChromeClient extends WebChromeClient implements MediaPla
@Override @Override
public void onHideCustomView() { public void onHideCustomView() {
if (((AppCompatActivity) activity).getSupportActionBar() != null) if (((AppCompatActivity) activity).getSupportActionBar() != null)
//noinspection ConstantConditions
((AppCompatActivity) activity).getSupportActionBar().show(); ((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 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). // This method must be manually called on back key press (from this class' onBackPressed() method).

View File

@ -61,9 +61,9 @@ import static android.content.Context.NOTIFICATION_SERVICE;
public class NotificationsWorker extends Worker { public class NotificationsWorker extends Worker {
private final NotificationManager notificationManager;
public static String FETCH_NOTIFICATION_CHANNEL_ID = "fetch_notification_peertube"; public static String FETCH_NOTIFICATION_CHANNEL_ID = "fetch_notification_peertube";
public static int pendingNotificationID = 1; public static int pendingNotificationID = 1;
private final NotificationManager notificationManager;
public NotificationsWorker( public NotificationsWorker(
@NonNull Context context, @NonNull Context context,
@ -80,7 +80,7 @@ public class NotificationsWorker extends Worker {
Context applicationContext = getApplicationContext(); Context applicationContext = getApplicationContext();
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
List<AccountData.Account> accounts = new AccountDAO(applicationContext, db).getAllAccount(); List<AccountData.Account> accounts = new AccountDAO(applicationContext, db).getAllAccount();
if( accounts == null || accounts.size() == 0) { if (accounts == null || accounts.size() == 0) {
return Result.success(); return Result.success();
} }
setForegroundAsync(createForegroundInfo()); setForegroundAsync(createForegroundInfo());
@ -95,28 +95,28 @@ public class NotificationsWorker extends Worker {
List<AccountData.Account> accounts = new AccountDAO(getApplicationContext(), db).getAllAccount(); List<AccountData.Account> accounts = new AccountDAO(getApplicationContext(), db).getAllAccount();
SharedPreferences sharedpreferences = getApplicationContext().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); SharedPreferences sharedpreferences = getApplicationContext().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit(); SharedPreferences.Editor editor = sharedpreferences.edit();
for(AccountData.Account account: accounts) { for (AccountData.Account account : accounts) {
RetrofitPeertubeAPI retrofitPeertubeAPI = new RetrofitPeertubeAPI(getApplicationContext(), account.getHost(), account.getToken()); RetrofitPeertubeAPI retrofitPeertubeAPI = new RetrofitPeertubeAPI(getApplicationContext(), account.getHost(), account.getToken());
APIResponse apiResponse = retrofitPeertubeAPI.getNotifications(); APIResponse apiResponse = retrofitPeertubeAPI.getNotifications();
if( apiResponse == null) { if (apiResponse == null) {
return; return;
} }
try { try {
UserMe userMe = retrofitPeertubeAPI.verifyCredentials(); UserMe userMe = retrofitPeertubeAPI.verifyCredentials();
if( userMe != null) { if (userMe != null) {
List<NotificationData.Notification> notifications = apiResponse.getPeertubeNotifications(); List<NotificationData.Notification> notifications = apiResponse.getPeertubeNotifications();
NotificationSettings notificationSettings = userMe.getNotificationSettings(); 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); 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.putString(Helper.LAST_NOTIFICATION_READ + account.getId() + account.getHost(), apiResponse.getPeertubeNotifications().get(0).getId());
editor.apply(); editor.apply();
if( last_read != null) { if (last_read != null) {
for(NotificationData.Notification notification: notifications) { for (NotificationData.Notification notification : notifications) {
String title = ""; String title = "";
String message = ""; String message = "";
FutureTarget<Bitmap> futureBitmap = Glide.with(getApplicationContext()) FutureTarget<Bitmap> futureBitmap = Glide.with(getApplicationContext())
.asBitmap() .asBitmap()
.load("https://"+account.getHost()+account.getAvatar()).submit(); .load("https://" + account.getHost() + account.getAvatar()).submit();
Bitmap icon; Bitmap icon;
try { try {
icon = futureBitmap.get(); icon = futureBitmap.get();
@ -126,14 +126,14 @@ public class NotificationsWorker extends Worker {
} }
Intent intent = null; Intent intent = null;
if(notification.getId().compareTo(last_read) > 0) { if (notification.getId().compareTo(last_read) > 0) {
switch (notification.getType()) { switch (notification.getType()) {
case DisplayNotificationsFragment.NEW_VIDEO_FROM_SUBSCRIPTION: case DisplayNotificationsFragment.NEW_VIDEO_FROM_SUBSCRIPTION:
if(notificationSettings.getNewVideoFromSubscription() == 1 || notificationSettings.getNewVideoFromSubscription() == 3) { if (notificationSettings.getNewVideoFromSubscription() == 1 || notificationSettings.getNewVideoFromSubscription() == 3) {
if( notification.getVideo().getChannel().getAvatar() != null ) { if (notification.getVideo().getChannel().getAvatar() != null) {
FutureTarget<Bitmap> futureBitmapChannel = Glide.with(getApplicationContext()) FutureTarget<Bitmap> futureBitmapChannel = Glide.with(getApplicationContext())
.asBitmap() .asBitmap()
.load("https://"+account.getHost()+notification.getVideo().getChannel().getAvatar().getPath()).submit(); .load("https://" + account.getHost() + notification.getVideo().getChannel().getAvatar().getPath()).submit();
try { try {
icon = futureBitmapChannel.get(); icon = futureBitmapChannel.get();
} catch (Exception e) { } catch (Exception e) {
@ -141,7 +141,7 @@ public class NotificationsWorker extends Worker {
R.drawable.missing_peertube); R.drawable.missing_peertube);
} }
}else{ } else {
icon = BitmapFactory.decodeResource(getApplicationContext().getResources(), icon = BitmapFactory.decodeResource(getApplicationContext().getResources(),
R.drawable.missing_peertube); R.drawable.missing_peertube);
} }
@ -158,11 +158,11 @@ public class NotificationsWorker extends Worker {
} }
break; break;
case DisplayNotificationsFragment.NEW_COMMENT_ON_MY_VIDEO: case DisplayNotificationsFragment.NEW_COMMENT_ON_MY_VIDEO:
if(notificationSettings.getNewCommentOnMyVideo() == 1 || notificationSettings.getNewCommentOnMyVideo() == 3) { if (notificationSettings.getNewCommentOnMyVideo() == 1 || notificationSettings.getNewCommentOnMyVideo() == 3) {
if( notification.getComment().getAccount().getAvatar() != null ) { if (notification.getComment().getAccount().getAvatar() != null) {
FutureTarget<Bitmap> futureBitmapChannel = Glide.with(getApplicationContext()) FutureTarget<Bitmap> futureBitmapChannel = Glide.with(getApplicationContext())
.asBitmap() .asBitmap()
.load("https://"+account.getHost()+ notification.getComment().getAccount().getAvatar().getPath()).submit(); .load("https://" + account.getHost() + notification.getComment().getAccount().getAvatar().getPath()).submit();
try { try {
icon = futureBitmapChannel.get(); icon = futureBitmapChannel.get();
} catch (Exception e) { } catch (Exception e) {
@ -170,7 +170,7 @@ public class NotificationsWorker extends Worker {
R.drawable.missing_peertube); R.drawable.missing_peertube);
} }
}else{ } else {
icon = BitmapFactory.decodeResource(getApplicationContext().getResources(), icon = BitmapFactory.decodeResource(getApplicationContext().getResources(),
R.drawable.missing_peertube); R.drawable.missing_peertube);
} }
@ -191,31 +191,31 @@ public class NotificationsWorker extends Worker {
break; break;
case DisplayNotificationsFragment.BLACKLIST_ON_MY_VIDEO: 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); title = getApplicationContext().getString(R.string.new_blacklist);
message = getApplicationContext().getString(R.string.peertube_video_blacklist, notification.getVideo().getName()); message = getApplicationContext().getString(R.string.peertube_video_blacklist, notification.getVideo().getName());
} }
break; break;
case DisplayNotificationsFragment.UNBLACKLIST_ON_MY_VIDEO: 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); title = getApplicationContext().getString(R.string.new_blacklist);
message = getApplicationContext().getString(R.string.peertube_video_unblacklist, notification.getVideo().getName()); message = getApplicationContext().getString(R.string.peertube_video_unblacklist, notification.getVideo().getName());
} }
break; break;
case DisplayNotificationsFragment.MY_VIDEO_PUBLISHED: 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); title = getApplicationContext().getString(R.string.new_my_video_published);
message = getApplicationContext().getString(R.string.peertube_video_published, notification.getVideo().getName()); message = getApplicationContext().getString(R.string.peertube_video_published, notification.getVideo().getName());
} }
break; break;
case DisplayNotificationsFragment.MY_VIDEO_IMPORT_SUCCESS: 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()); message = getApplicationContext().getString(R.string.peertube_video_import_success, notification.getVideo().getName());
title = getApplicationContext().getString(R.string.new_my_video_error); title = getApplicationContext().getString(R.string.new_my_video_error);
} }
break; break;
case DisplayNotificationsFragment.MY_VIDEO_IMPORT_ERROR: 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()); message = getApplicationContext().getString(R.string.peertube_video_import_error, notification.getVideo().getName());
title = getApplicationContext().getString(R.string.new_my_video_error); title = getApplicationContext().getString(R.string.new_my_video_error);
} }
@ -224,14 +224,14 @@ public class NotificationsWorker extends Worker {
break; break;
case DisplayNotificationsFragment.NEW_FOLLOW: case DisplayNotificationsFragment.NEW_FOLLOW:
if(notificationSettings.getNewFollow() == 1 || notificationSettings.getNewFollow() == 3) { if (notificationSettings.getNewFollow() == 1 || notificationSettings.getNewFollow() == 3) {
if( notification.getVideo().getChannel().getAvatar() != null ) { if (notification.getVideo().getChannel().getAvatar() != null) {
FutureTarget<Bitmap> futureBitmapChannel = Glide.with(getApplicationContext()) FutureTarget<Bitmap> futureBitmapChannel = Glide.with(getApplicationContext())
.asBitmap() .asBitmap()
.load("https://"+account.getHost()+notification.getVideo().getChannel().getAvatar().getPath()).submit(); .load("https://" + account.getHost() + notification.getVideo().getChannel().getAvatar().getPath()).submit();
icon = futureBitmapChannel.get(); icon = futureBitmapChannel.get();
}else{ } else {
icon = BitmapFactory.decodeResource(getApplicationContext().getResources(), icon = BitmapFactory.decodeResource(getApplicationContext().getResources(),
R.drawable.missing_peertube); R.drawable.missing_peertube);
} }
@ -250,7 +250,7 @@ public class NotificationsWorker extends Worker {
accountAction.setHost(actor.getHost()); accountAction.setHost(actor.getHost());
accountAction.setUsername(actor.getName()); accountAction.setUsername(actor.getName());
intent = new Intent(getApplicationContext(), ShowAccountActivity.class); intent = new Intent(getApplicationContext(), ShowAccountActivity.class);
b.putParcelable("account", accountAction); b.putParcelable("account", accountAction);
b.putString("accountAcct", accountAction.getUsername() + "@" + accountAction.getHost()); b.putString("accountAcct", accountAction.getUsername() + "@" + accountAction.getHost());
intent.putExtras(b); intent.putExtras(b);
} }
@ -274,14 +274,14 @@ public class NotificationsWorker extends Worker {
break; break;
} }
if( message != null && icon != null && title != null) { if (message != null && icon != null && title != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
message = Html.fromHtml(message, Html.FROM_HTML_MODE_LEGACY).toString(); message = Html.fromHtml(message, Html.FROM_HTML_MODE_LEGACY).toString();
else else
message = Html.fromHtml(message).toString(); message = Html.fromHtml(message).toString();
NotificationHelper.notify_user(getApplicationContext(), account, intent, icon, title, message); NotificationHelper.notify_user(getApplicationContext(), account, intent, icon, title, message);
} }
}else { } else {
break; break;
} }
} }

View File

@ -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, * You should have received a copy of the GNU General Public License along with TubeLab; if not,
* see <http://www.gnu.org/licenses>. */ * see <http://www.gnu.org/licenses>. */
import android.app.Application; import android.app.Application;
import androidx.work.BackoffPolicy; import androidx.work.BackoffPolicy;
import androidx.work.Constraints; import androidx.work.Constraints;
import androidx.work.ExistingPeriodicWorkPolicy; import androidx.work.ExistingPeriodicWorkPolicy;

View File

@ -32,21 +32,34 @@
android:layout_marginBottom="5dp"> android:layout_marginBottom="5dp">
<TextView <TextView
android:id="@+id/about_instance_name" android:id="@+id/about_instance_host"
android:layout_width="0dp" android:layout_width="0dp"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginStart="10dp" android:layout_marginStart="10dp"
android:textSize="18sp" android:textSize="20sp"
android:textStyle="bold" android:textStyle="bold"
app:layout_constraintEnd_toStartOf="@+id/instance_more" app:layout_constraintEnd_toStartOf="@+id/instance_more"
app:layout_constraintStart_toStartOf="parent" app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" /> app:layout_constraintTop_toTopOf="parent" />
<TextView
android:layout_marginTop="5dp"
android:id="@+id/about_instance_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintEnd_toStartOf="@+id/instance_more"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/about_instance_host" />
<TextView <TextView
android:id="@+id/about_instance_description" android:id="@+id/about_instance_description"
android:layout_width="0dp" android:layout_width="0dp"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="center" android:layout_gravity="center"
android:layout_marginStart="10dp"
app:layout_constraintStart_toStartOf="parent" app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="@+id/instance_more" app:layout_constraintEnd_toStartOf="@+id/instance_more"
app:layout_constraintTop_toBottomOf="@+id/about_instance_name" /> app:layout_constraintTop_toBottomOf="@+id/about_instance_name" />