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)
.build();
WorkManager.initialize(FedilabTube.this, myConfig);
if( interval >= 15 ) {
if (interval >= 15) {
WorkHelper.fetchNotifications(this, interval);
}
}

View File

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

View File

@ -83,20 +83,11 @@ public class MainActivity extends AppCompatActivity {
public static int PICK_INSTANCE = 5641;
public static int PICK_INSTANCE_SURF = 5642;
public static UserMe userMe;
final FragmentManager fm = getSupportFragmentManager();
Fragment active;
private DisplayVideosFragment recentFragment, locaFragment, trendingFragment, subscriptionFragment, mostLikedFragment;
private DisplayOverviewFragment overviewFragment;
public static UserMe userMe;
public enum TypeOfConnection{
UNKNOWN,
NORMAL,
SURFING
}
private TypeOfConnection typeOfConnection;
private final BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= item -> {
DisplayVideosFragment displayVideosFragment = null;
@ -130,7 +121,66 @@ public class MainActivity extends AppCompatActivity {
return false;
}
};
private TypeOfConnection typeOfConnection;
@SuppressLint("ApplySharedPref")
public static void showRadioButtonDialogFullInstances(Activity activity, boolean storeInDb) {
final SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
AlertDialog.Builder alt_bld = new AlertDialog.Builder(activity);
alt_bld.setTitle(R.string.instance_choice);
String instance = Helper.getLiveInstance(activity);
final EditText input = new EditText(activity);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
alt_bld.setView(input);
input.setText(instance);
alt_bld.setPositiveButton(R.string.validate,
(dialog, which) -> new Thread(() -> {
try {
String newInstance = input.getText().toString().trim();
WellKnownNodeinfo.NodeInfo instanceNodeInfo = new RetrofitPeertubeAPI(activity, newInstance, null).getNodeInfo();
if (instanceNodeInfo.getSoftware() != null && instanceNodeInfo.getSoftware().getName().trim().toLowerCase().compareTo("peertube") == 0) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_INSTANCE, newInstance);
editor.commit();
if (storeInDb) {
newInstance = newInstance.trim().toLowerCase();
InstanceData.AboutInstance aboutInstance = new RetrofitPeertubeAPI(activity, newInstance, null).getAboutInstance();
SQLiteDatabase db = Sqlite.getInstance(activity.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
new StoredInstanceDAO(activity, db).insertInstance(aboutInstance, newInstance);
activity.runOnUiThread(() -> {
dialog.dismiss();
Helper.logoutNoRemoval(activity);
});
} else {
activity.runOnUiThread(() -> {
dialog.dismiss();
Intent intent = new Intent(activity, MainActivity.class);
activity.startActivity(intent);
});
}
} else {
activity.runOnUiThread(() -> Toasty.error(activity, activity.getString(R.string.not_valide_instance), Toast.LENGTH_LONG).show());
}
} catch (Exception e) {
e.printStackTrace();
}
}).start());
alt_bld.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
alt_bld.setNeutralButton(R.string.help, (dialog, which) -> {
Intent intent = new Intent(activity, InstancePickerActivity.class);
if (storeInDb) {
activity.startActivityForResult(intent, PICK_INSTANCE_SURF);
} else {
activity.startActivityForResult(intent, PICK_INSTANCE);
}
});
AlertDialog alert = alt_bld.create();
alert.show();
}
private void setTitleCustom(int titleRId) {
Toolbar toolbar = findViewById(R.id.toolbar);
@ -152,7 +202,7 @@ public class MainActivity extends AppCompatActivity {
navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
if( getSupportActionBar() != null) {
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowTitleEnabled(false);
}
checkIfConnectedUsers();
@ -225,31 +275,31 @@ public class MainActivity extends AppCompatActivity {
if (Helper.isLoggedIn(MainActivity.this)) {
navView.inflateMenu(R.menu.bottom_nav_menu_connected);
new Thread(() -> {
final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String tokenStr = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);
String instance = Helper.getLiveInstance(MainActivity.this);
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
String instanceShar = sharedpreferences.getString(Helper.PREF_INSTANCE, null);
String userIdShar = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
Account account = new AccountDAO(MainActivity.this, db).getAccountByToken(tokenStr);
if( account == null) {
account = new AccountDAO(MainActivity.this, db).getAccountByIdInstance(userIdShar, instanceShar);
}
if (account != null) {
Account finalAccount = account;
OauthParams oauthParams = new OauthParams();
oauthParams.setGrant_type("refresh_token");
oauthParams.setClient_id(account.getClient_id());
oauthParams.setClient_secret(account.getClient_secret());
oauthParams.setRefresh_token(account.getRefresh_token());
oauthParams.setAccess_token(account.getToken());
new Thread(() -> {
final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String tokenStr = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);
String instance = Helper.getLiveInstance(MainActivity.this);
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
String instanceShar = sharedpreferences.getString(Helper.PREF_INSTANCE, null);
String userIdShar = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
Account account = new AccountDAO(MainActivity.this, db).getAccountByToken(tokenStr);
if (account == null) {
account = new AccountDAO(MainActivity.this, db).getAccountByIdInstance(userIdShar, instanceShar);
}
if (account != null) {
Account finalAccount = account;
OauthParams oauthParams = new OauthParams();
oauthParams.setGrant_type("refresh_token");
oauthParams.setClient_id(account.getClient_id());
oauthParams.setClient_secret(account.getClient_secret());
oauthParams.setRefresh_token(account.getRefresh_token());
oauthParams.setAccess_token(account.getToken());
try {
Token token = new RetrofitPeertubeAPI(MainActivity.this).manageToken(oauthParams);
if (token == null && Helper.instanceOnline(instance)) {
runOnUiThread(() -> Helper.logoutCurrentUser(MainActivity.this, finalAccount));
return;
}else if(token == null) {
} else if (token == null) {
return;
}
runOnUiThread(() -> {
@ -290,7 +340,8 @@ public class MainActivity extends AppCompatActivity {
runOnUiThread(() -> Helper.logoutCurrentUser(MainActivity.this, finalAccount));
error.printStackTrace();
}
}}).start();
}
}).start();
} else {
navView.inflateMenu(R.menu.bottom_nav_menu);
@ -332,11 +383,11 @@ public class MainActivity extends AppCompatActivity {
Pattern link = Pattern.compile("(https?://[\\da-z.-]+\\.[a-z.]{2,10})/videos/watch/(\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12})$");
Matcher matcherLink = link.matcher(query.trim());
if (matcherLink.find()) {
Intent intent = new Intent(MainActivity.this, PeertubeActivity.class);
intent.setData(Uri.parse(query.trim()));
startActivity(intent);
myActionMenuItem.collapseActionView();
return false;
Intent intent = new Intent(MainActivity.this, PeertubeActivity.class);
intent.setData(Uri.parse(query.trim()));
startActivity(intent);
myActionMenuItem.collapseActionView();
return false;
}
Intent intent = new Intent(MainActivity.this, SearchActivity.class);
Bundle b = new Bundle();
@ -370,18 +421,18 @@ public class MainActivity extends AppCompatActivity {
Toolbar toolbar = findViewById(R.id.toolbar);
ImageButton instances = toolbar.findViewById(R.id.instances);
if(BuildConfig.full_instances && ((Helper.isLoggedIn(MainActivity.this) && typeOfConnection == NORMAL) || typeOfConnection == SURFING)) {
if (BuildConfig.full_instances && ((Helper.isLoggedIn(MainActivity.this) && typeOfConnection == NORMAL) || typeOfConnection == SURFING)) {
instances.setVisibility(View.VISIBLE);
instances.setOnClickListener(null);
instances.setOnClickListener(v->{
instances.setOnClickListener(v -> {
Intent intent = new Intent(MainActivity.this, ManageInstancesActivity.class);
startActivity(intent);
overridePendingTransition( R.anim.slide_in_up, R.anim.slide_out_up );
overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up);
});
}else {
} else {
instances.setVisibility(View.GONE);
}
switch (typeOfConnection){
switch (typeOfConnection) {
case UNKNOWN:
instanceItem.setVisible(false);
accountItem.setVisible(false);
@ -438,14 +489,14 @@ public class MainActivity extends AppCompatActivity {
return true;
}
private void checkIfConnectedUsers(){
private void checkIfConnectedUsers() {
new Thread(() -> {
try {
typeOfConnection = NORMAL;
if( !Helper.isLoggedIn(MainActivity.this)) {
if (!Helper.isLoggedIn(MainActivity.this)) {
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
List<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
typeOfConnection = TypeOfConnection.SURFING;
}
@ -472,7 +523,7 @@ public class MainActivity extends AppCompatActivity {
startActivity(intent);
} else if (item.getItemId() == R.id.action_account) {
Intent intent;
if( typeOfConnection == SURFING) {
if (typeOfConnection == SURFING) {
SwitchAccountHelper.switchDialog(MainActivity.this, false);
} else {
if (Helper.isLoggedIn(MainActivity.this)) {
@ -590,68 +641,6 @@ public class MainActivity extends AppCompatActivity {
alert.show();
}
@SuppressLint("ApplySharedPref")
public static void showRadioButtonDialogFullInstances(Activity activity, boolean storeInDb) {
final SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
AlertDialog.Builder alt_bld = new AlertDialog.Builder(activity);
alt_bld.setTitle(R.string.instance_choice);
String instance = Helper.getLiveInstance(activity);
final EditText input = new EditText(activity);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
alt_bld.setView(input);
input.setText(instance);
alt_bld.setPositiveButton(R.string.validate,
(dialog, which) -> new Thread(() -> {
try {
String newInstance = input.getText().toString().trim();
WellKnownNodeinfo.NodeInfo instanceNodeInfo = new RetrofitPeertubeAPI(activity, newInstance, null).getNodeInfo();
if (instanceNodeInfo.getSoftware() != null && instanceNodeInfo.getSoftware().getName().trim().toLowerCase().compareTo("peertube") == 0) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_INSTANCE, newInstance);
editor.commit();
if( storeInDb) {
newInstance = newInstance.trim().toLowerCase();
InstanceData.AboutInstance aboutInstance = new RetrofitPeertubeAPI(activity, newInstance, null).getAboutInstance();
SQLiteDatabase db = Sqlite.getInstance(activity.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
new StoredInstanceDAO(activity, db).insertInstance(aboutInstance, newInstance);
activity.runOnUiThread(() -> {
dialog.dismiss();
Helper.logoutNoRemoval(activity);
});
}else {
activity.runOnUiThread(() -> {
dialog.dismiss();
Intent intent = new Intent(activity, MainActivity.class);
activity.startActivity(intent);
});
}
} else {
activity.runOnUiThread(() -> Toasty.error(activity, activity.getString(R.string.not_valide_instance), Toast.LENGTH_LONG).show());
}
} catch (Exception e) {
e.printStackTrace();
}
}).start());
alt_bld.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
alt_bld.setNeutralButton(R.string.help, (dialog, which) -> {
Intent intent = new Intent(activity, InstancePickerActivity.class);
if(storeInDb) {
activity.startActivityForResult(intent, PICK_INSTANCE_SURF);
}else{
activity.startActivityForResult(intent, PICK_INSTANCE);
}
});
AlertDialog alert = alt_bld.create();
alert.show();
}
@SuppressLint("ApplySharedPref")
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
@ -662,17 +651,15 @@ public class MainActivity extends AppCompatActivity {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_INSTANCE, String.valueOf(data.getData()));
editor.commit();
finish();
}
}else if (requestCode == PICK_INSTANCE_SURF && resultCode == Activity.RESULT_OK) {
if (data != null && data.getData() != null) {
final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_INSTANCE, String.valueOf(data.getData()));
editor.commit();
finish();
}
}
}
public enum TypeOfConnection {
UNKNOWN,
NORMAL,
SURFING
}
}

View File

@ -17,20 +17,26 @@ package app.fedilab.fedilabtube;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.view.MenuItem;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import java.util.ArrayList;
import java.util.List;
import app.fedilab.fedilabtube.client.RetrofitPeertubeAPI;
import app.fedilab.fedilabtube.client.data.InstanceData;
import app.fedilab.fedilabtube.databinding.ActivityManageInstancesBinding;
import app.fedilab.fedilabtube.drawer.AboutInstanceAdapter;
import app.fedilab.fedilabtube.helper.Helper;
import app.fedilab.fedilabtube.sqlite.Sqlite;
import app.fedilab.fedilabtube.sqlite.StoredInstanceDAO;
import app.fedilab.fedilabtube.viewmodel.InfoInstanceVM;
import static app.fedilab.fedilabtube.MainActivity.PICK_INSTANCE_SURF;
@ -39,7 +45,9 @@ import static app.fedilab.fedilabtube.MainActivity.showRadioButtonDialogFullInst
public class ManageInstancesActivity extends AppCompatActivity implements AboutInstanceAdapter.AllInstancesRemoved {
private ActivityManageInstancesBinding binding;
private ActivityManageInstancesBinding binding;
private List<InstanceData.AboutInstance> aboutInstances;
private AboutInstanceAdapter aboutInstanceAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
@ -54,34 +62,43 @@ public class ManageInstancesActivity extends AppCompatActivity implements AboutI
binding.loader.setVisibility(View.VISIBLE);
binding.noAction.setVisibility(View.GONE);
binding.lvInstances.setVisibility(View.GONE);
binding.actionButton.setOnClickListener(v-> showRadioButtonDialogFullInstances(ManageInstancesActivity.this, true));
binding.actionButton.setOnClickListener(v -> showRadioButtonDialogFullInstances(ManageInstancesActivity.this, true));
aboutInstances = new ArrayList<>();
aboutInstanceAdapter = new AboutInstanceAdapter(this.aboutInstances);
aboutInstanceAdapter.allInstancesRemoved = this;
binding.lvInstances.setAdapter(aboutInstanceAdapter);
LinearLayoutManager layoutManager
= new LinearLayoutManager(ManageInstancesActivity.this);
binding.lvInstances.setLayoutManager(layoutManager);
InfoInstanceVM viewModelInfoInstance = new ViewModelProvider(ManageInstancesActivity.this).get(InfoInstanceVM.class);
viewModelInfoInstance.getInstances().observe(ManageInstancesActivity.this, this::manageVIewInfoInstance);
}
private void manageVIewInfoInstance(List<InstanceData.AboutInstance> aboutInstances) {
binding.loader.setVisibility(View.GONE);
if( aboutInstances == null || aboutInstances.size() == 0) {
if (aboutInstances == null || aboutInstances.size() == 0) {
binding.noAction.setVisibility(View.VISIBLE);
binding.lvInstances.setVisibility(View.GONE);
return;
}
binding.noAction.setVisibility(View.GONE);
binding.lvInstances.setVisibility(View.VISIBLE);
this.aboutInstances.addAll(aboutInstances);
aboutInstanceAdapter.notifyItemRangeInserted(0, aboutInstances.size());
}
@Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition( R.anim.slide_out_up, R.anim.slide_in_up_down );
overridePendingTransition(R.anim.slide_out_up, R.anim.slide_in_up_down);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
overridePendingTransition( R.anim.slide_out_up, R.anim.slide_in_up_down );
overridePendingTransition(R.anim.slide_out_up, R.anim.slide_in_up_down);
return true;
}
return super.onOptionsItemSelected(item);
@ -94,7 +111,13 @@ public class ManageInstancesActivity extends AppCompatActivity implements AboutI
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_INSTANCE_SURF && resultCode == Activity.RESULT_OK) {
if (data != null && data.getData() != null) {
Helper.logoutNoRemoval(ManageInstancesActivity.this);
new Thread(() -> {
String newInstance = data.getData().toString().trim().toLowerCase();
InstanceData.AboutInstance aboutInstance = new RetrofitPeertubeAPI(ManageInstancesActivity.this, newInstance, null).getAboutInstance();
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
new StoredInstanceDAO(ManageInstancesActivity.this, db).insertInstance(aboutInstance, newInstance);
runOnUiThread(() -> new Handler().post(() -> Helper.logoutNoRemoval(ManageInstancesActivity.this)));
}).start();
}
}
}

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

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

View File

@ -61,7 +61,6 @@ public class PeertubeRegisterActivity extends AppCompatActivity {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (BuildConfig.full_instances) {
binding.loginInstanceContainer.setVisibility(View.VISIBLE);
binding.titleLoginInstance.setVisibility(View.VISIBLE);
@ -114,21 +113,21 @@ public class PeertubeRegisterActivity extends AppCompatActivity {
setTextAgreement();
binding.signup.setOnClickListener(view -> {
binding.errorMessage.setVisibility(View.GONE);
if ( binding.username.getText() == null || binding.email.getText() == null || binding.password.getText() == null || binding.passwordConfirm.getText() == null || binding.username.getText().toString().trim().length() == 0 || binding.email.getText().toString().trim().length() == 0 ||
binding.password.getText().toString().trim().length() == 0 || binding.passwordConfirm.getText().toString().trim().length() == 0 || ! binding.agreement.isChecked()) {
if (binding.username.getText() == null || binding.email.getText() == null || binding.password.getText() == null || binding.passwordConfirm.getText() == null || binding.username.getText().toString().trim().length() == 0 || binding.email.getText().toString().trim().length() == 0 ||
binding.password.getText().toString().trim().length() == 0 || binding.passwordConfirm.getText().toString().trim().length() == 0 || !binding.agreement.isChecked()) {
Toasty.error(PeertubeRegisterActivity.this, getString(R.string.all_field_filled)).show();
return;
}
if (! binding.password.getText().toString().trim().equals( binding.passwordConfirm.getText().toString().trim())) {
if (!binding.password.getText().toString().trim().equals(binding.passwordConfirm.getText().toString().trim())) {
Toasty.error(PeertubeRegisterActivity.this, getString(R.string.password_error)).show();
return;
}
if (!android.util.Patterns.EMAIL_ADDRESS.matcher( binding.email.getText().toString().trim()).matches()) {
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(binding.email.getText().toString().trim()).matches()) {
Toasty.error(PeertubeRegisterActivity.this, getString(R.string.email_error)).show();
return;
}
String[] emailArray = binding.email.getText().toString().split("@");
String[] emailArray = binding.email.getText().toString().split("@");
if (!BuildConfig.full_instances) {
if (emailArray.length > 1 && !Arrays.asList(Helper.valideEmails).contains(emailArray[1])) {
Toasty.error(PeertubeRegisterActivity.this, getString(R.string.email_error_domain, emailArray[1])).show();
@ -136,19 +135,19 @@ public class PeertubeRegisterActivity extends AppCompatActivity {
}
}
if ( binding.password.getText().toString().trim().length() < 8) {
if (binding.password.getText().toString().trim().length() < 8) {
Toasty.error(PeertubeRegisterActivity.this, getString(R.string.password_too_short)).show();
return;
}
if ( binding.username.getText().toString().matches("[a-z0-9_]")) {
if (binding.username.getText().toString().matches("[a-z0-9_]")) {
Toasty.error(PeertubeRegisterActivity.this, getString(R.string.username_error)).show();
return;
}
binding.signup.setEnabled(false);
if (BuildConfig.full_instances) {
if ( binding.loginInstance.getText() != null) {
instance = binding.loginInstance.getText().toString();
if (binding.loginInstance.getText() != null) {
instance = binding.loginInstance.getText().toString();
} else {
instance = "";
}
@ -166,10 +165,10 @@ public class PeertubeRegisterActivity extends AppCompatActivity {
}
AccountCreation accountCreation = new AccountCreation();
accountCreation.setEmail( binding.email.getText().toString().trim());
accountCreation.setPassword( binding.password.getText().toString().trim());
accountCreation.setPasswordConfirm( binding.passwordConfirm.getText().toString().trim());
accountCreation.setUsername( binding.username.getText().toString().trim());
accountCreation.setEmail(binding.email.getText().toString().trim());
accountCreation.setPassword(binding.password.getText().toString().trim());
accountCreation.setPasswordConfirm(binding.passwordConfirm.getText().toString().trim());
accountCreation.setUsername(binding.username.getText().toString().trim());
accountCreation.setInstance(instance);
new Thread(() -> {
@ -259,7 +258,7 @@ public class PeertubeRegisterActivity extends AppCompatActivity {
agreement_text.setMovementMethod(null);
agreement_text.setText(null);
if (BuildConfig.full_instances) {
if ( binding.loginInstance.getText() != null) {
if (binding.loginInstance.getText() != null) {
content_agreement = getString(R.string.agreement_check_peertube,
"<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 {
private final int PICK_IVDEO = 52378;
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 724;
private final int PICK_IVDEO = 52378;
private Button set_upload_file, set_upload_submit;
private Spinner set_upload_privacy, set_upload_channel;
private TextView set_upload_file_name;

View File

@ -134,7 +134,7 @@ public class ShowAccountActivity extends AppCompatActivity {
});
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
}else if( item.getItemId() == R.id.action_share && account != null) {
} else if (item.getItemId() == R.id.action_share && account != null) {
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.shared_via));
String extra_text = account.getUrl();

View File

@ -159,7 +159,7 @@ public class ShowChannelActivity extends AppCompatActivity {
});
androidx.appcompat.app.AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
} else if( item.getItemId() == R.id.action_share && channel != null) {
} else if (item.getItemId() == R.id.action_share && channel != null) {
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.shared_via));
String extra_text = channel.getUrl();

View File

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

View File

@ -166,9 +166,9 @@ public class RetrofitPeertubeAPI {
}
private String getToken() {
if( token != null) {
if (token != null) {
return "Bearer " + token;
}else{
} else {
return null;
}
}
@ -454,7 +454,7 @@ public class RetrofitPeertubeAPI {
/**
* Update history
*
* @param videoId String
* @param videoId String
* @param currentTime int
*/
public void updateHistory(String videoId, long currentTime) {
@ -525,10 +525,10 @@ public class RetrofitPeertubeAPI {
}
byte[] imageBytes = byteBuffer.toByteArray();
String mime = MimeTypeMap.getFileExtensionFromUrl(userSettings.getAvatarfile().toString());
if( mime == null || mime.trim().length() == 0) {
if (mime == null || mime.trim().length() == 0) {
mime = "png";
}
RequestBody requestFile = RequestBody.create(MediaType.parse("image/"+mime), imageBytes);
RequestBody requestFile = RequestBody.create(MediaType.parse("image/" + mime), imageBytes);
MultipartBody.Part bodyThumbnail = MultipartBody.Part.createFormData("avatarfile", userSettings.getFileName(), requestFile);
Call<UserMe.AvatarResponse> updateProfilePicture = peertubeService.updateProfilePicture(getToken(), bodyThumbnail);
Response<UserMe.AvatarResponse> responseAvatar = updateProfilePicture.execute();
@ -599,16 +599,17 @@ public class RetrofitPeertubeAPI {
/**
* About the instance
*
* @return AboutInstance
*/
public InstanceData.AboutInstance getAboutInstance() {
PeertubeService peertubeService = init();
Call<InstanceData.AboutInstance> about = peertubeService.configAbout();
Call<InstanceData.InstanceInfo> about = peertubeService.configAbout();
try {
Response<InstanceData.AboutInstance> response = about.execute();
Response<InstanceData.InstanceInfo> response = about.execute();
if (response.isSuccessful() && response.body() != null) {
return response.body();
return response.body().getInstance();
}
} catch (IOException e) {
e.printStackTrace();
@ -800,7 +801,7 @@ public class RetrofitPeertubeAPI {
*/
public APIResponse searchNextVideos(List<String> tags) {
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();
try {
Response<VideoData> response = searchVideosCall.execute();
@ -1058,7 +1059,6 @@ public class RetrofitPeertubeAPI {
}
/**
* Get video description
*
@ -1071,9 +1071,10 @@ public class RetrofitPeertubeAPI {
try {
Response<VideoData.Description> response = videoDescription.execute();
if (response.isSuccessful() && response.body() != null) {
return response.body();
return response.body();
}
} catch (IOException ignored) {}
} catch (IOException ignored) {
}
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")
private String name;
@SerializedName("shortDescription")
private String shortDescription;
@SerializedName("description")
private String description;
@SerializedName("terms")
private String terms;
private String host;
public AboutInstance(){}
protected AboutInstance(Parcel in) {
name = in.readString();
shortDescription = in.readString();
description = in.readString();
terms = in.readString();
host = in.readString();
public AboutInstance getInstance() {
return instance;
}
public void setInstance(AboutInstance instance) {
this.instance = instance;
}
}
public static class AboutInstance implements Parcelable, Serializable {
public static final Creator<AboutInstance> CREATOR = new Creator<AboutInstance>() {
@Override
public AboutInstance createFromParcel(Parcel in) {
@ -276,6 +268,26 @@ public class InstanceData {
return new AboutInstance[size];
}
};
@SerializedName("name")
private String name;
@SerializedName("shortDescription")
private String shortDescription;
@SerializedName("description")
private String description;
@SerializedName("terms")
private String terms;
private String host;
public AboutInstance() {
}
protected AboutInstance(Parcel in) {
name = in.readString();
shortDescription = in.readString();
description = in.readString();
terms = in.readString();
host = in.readString();
}
public String getName() {
return name;

View File

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

View File

@ -9,6 +9,17 @@ import com.google.gson.annotations.SerializedName;
@SuppressWarnings({"unused", "RedundantSuppression"})
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")
private String fileDownloadUrl;
@SerializedName("fileUrl")
@ -28,6 +39,21 @@ public class File implements Parcelable {
@SerializedName("torrentUrl")
private String torrentUrl;
public File() {
}
protected File(Parcel in) {
this.fileDownloadUrl = in.readString();
this.fileUrl = in.readString();
this.fps = in.readInt();
this.magnetUri = in.readString();
this.metadataUrl = in.readString();
this.resolutions = in.readParcelable(Item.class.getClassLoader());
this.size = in.readLong();
this.torrentDownloadUrl = in.readString();
this.torrentUrl = in.readString();
}
public String getFileDownloadUrl() {
return fileDownloadUrl;
}
@ -100,7 +126,6 @@ public class File implements Parcelable {
this.torrentUrl = torrentUrl;
}
@Override
public int describeContents() {
return 0;
@ -118,31 +143,4 @@ public class File implements Parcelable {
dest.writeString(this.torrentDownloadUrl);
dest.writeString(this.torrentUrl);
}
public File() {
}
protected File(Parcel in) {
this.fileDownloadUrl = in.readString();
this.fileUrl = in.readString();
this.fps = in.readInt();
this.magnetUri = in.readString();
this.metadataUrl = in.readString();
this.resolutions = in.readParcelable(Item.class.getClassLoader());
this.size = in.readLong();
this.torrentDownloadUrl = in.readString();
this.torrentUrl = in.readString();
}
public static final Parcelable.Creator<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;
}
public void setVideosHistoryEnabled(Boolean videosHistoryEnabled) {
this.videosHistoryEnabled = videosHistoryEnabled;
}
public Boolean isAutoPlayVideo() {
return autoPlayVideo;
}
public void setAutoPlayVideo(Boolean autoPlayVideo) {
this.autoPlayVideo = autoPlayVideo;
}
public Boolean isWebTorrentEnabled() {
return webTorrentEnabled;
}
public void setWebTorrentEnabled(Boolean webTorrentEnabled) {
this.webTorrentEnabled = webTorrentEnabled;
}
public List<String> getVideoLanguages() {
return videoLanguages;
}
@ -93,32 +81,44 @@ public class UserSettings {
return videosHistoryEnabled;
}
public void setVideosHistoryEnabled(Boolean videosHistoryEnabled) {
this.videosHistoryEnabled = videosHistoryEnabled;
}
public Boolean getAutoPlayVideo() {
return autoPlayVideo;
}
public void setAutoPlayVideo(Boolean autoPlayVideo) {
this.autoPlayVideo = autoPlayVideo;
}
public Boolean getWebTorrentEnabled() {
return webTorrentEnabled;
}
public void setWebTorrentEnabled(Boolean webTorrentEnabled) {
this.webTorrentEnabled = webTorrentEnabled;
}
public Boolean isAutoPlayNextVideo() {
return autoPlayNextVideo;
}
public Boolean getAutoPlayNextVideo() {
return autoPlayNextVideo;
}
public void setAutoPlayNextVideo(Boolean autoPlayNextVideo) {
this.autoPlayNextVideo = autoPlayNextVideo;
}
public Boolean getAutoPlayNextVideo() {
return autoPlayNextVideo;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
if( fileName == null) {
if (fileName == null) {
this.fileName = "avatar.png";
} else {
this.fileName = fileName;

View File

@ -22,10 +22,14 @@ import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.Html;
import android.text.SpannableString;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.PopupMenu;
@ -35,24 +39,23 @@ import java.util.List;
import app.fedilab.fedilabtube.MainActivity;
import app.fedilab.fedilabtube.R;
import app.fedilab.fedilabtube.client.RetrofitPeertubeAPI;
import app.fedilab.fedilabtube.client.data.InstanceData;
import app.fedilab.fedilabtube.databinding.DrawerAboutInstanceBinding;
import app.fedilab.fedilabtube.helper.Helper;
import app.fedilab.fedilabtube.sqlite.Sqlite;
import app.fedilab.fedilabtube.sqlite.StoredInstanceDAO;
import static androidx.core.text.HtmlCompat.FROM_HTML_MODE_LEGACY;
public class AboutInstanceAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final List<InstanceData.AboutInstance> aboutInstances;
private final AboutInstanceAdapter aboutInstanceAdapter;
public AllInstancesRemoved allInstancesRemoved;
private Context context;
public AboutInstanceAdapter(List<InstanceData.AboutInstance> aboutInstances) {
aboutInstanceAdapter = this;
this.aboutInstances = aboutInstances;
}
@ -71,7 +74,7 @@ public class AboutInstanceAdapter extends RecyclerView.Adapter<RecyclerView.View
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
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);
}
@ -85,19 +88,29 @@ public class AboutInstanceAdapter extends RecyclerView.Adapter<RecyclerView.View
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.playlistContainer.setOnClickListener(v->{
holder.binding.playlistContainer.setOnClickListener(v -> {
final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_INSTANCE, aboutInstance.getHost());
editor.commit();
((Activity)context).runOnUiThread(() -> {
((Activity) context).runOnUiThread(() -> {
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);
});
});
holder.binding.instanceMore.setOnClickListener(v->{
holder.binding.instanceMore.setOnClickListener(v -> {
PopupMenu popup = new PopupMenu(context, holder.binding.instanceMore);
popup.getMenuInflater()
.inflate(R.menu.instance_menu, popup.getMenu());
@ -112,8 +125,10 @@ public class AboutInstanceAdapter extends RecyclerView.Adapter<RecyclerView.View
new Thread(() -> {
SQLiteDatabase db = Sqlite.getInstance(context.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
new StoredInstanceDAO(context, db).removeInstance(aboutInstance.getHost());
aboutInstances.remove(aboutInstance);
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> {
notifyItemRemoved(i);
if (aboutInstances.size() == 0) {
allInstancesRemoved.onAllInstancesRemoved();
}
@ -128,6 +143,7 @@ public class AboutInstanceAdapter extends RecyclerView.Adapter<RecyclerView.View
}
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 CommentListAdapter commentListAdapter;
private final boolean isThread;
public AllCommentRemoved allCommentRemoved;
boolean isVideoOwner;
private Context context;
private final boolean isThread;
public CommentListAdapter(List<Comment> comments, boolean isVideoOwner, boolean isThread) {
this.comments = comments;
@ -125,11 +125,11 @@ public class CommentListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHo
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
if( comment.isReply()) {
if (comment.isReply()) {
int ident = CommentDecorationHelper.getIndentation(comment.getInReplyToCommentId(), comments);
holder.decoration.setVisibility(View.VISIBLE);
params.setMargins((int)Helper.convertDpToPixel(ident*15, context), 0, 0, 0);
}else{
params.setMargins((int) Helper.convertDpToPixel(ident * 15, context), 0, 0, 0);
} else {
holder.decoration.setVisibility(View.GONE);
params.setMargins(0, 0, 0, 0);
}
@ -284,9 +284,9 @@ public class CommentListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHo
} else {
holder.replyButton.setVisibility(View.GONE);
}
if( i == 0 && isThread) {
if (i == 0 && isThread) {
holder.post_reply_button.setVisibility(View.VISIBLE);
}else {
} else {
holder.post_reply_button.setVisibility(View.GONE);
}
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);
number_of_replies = itemView.findViewById(R.id.number_of_replies);
replyButton = itemView.findViewById(R.id.replyButton);
decoration = itemView.findViewById(R.id.decoration);
post_reply_button = itemView.findViewById(R.id.post_reply_button);
decoration = itemView.findViewById(R.id.decoration);
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())));
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);
holder.peertube_video_image_small.setVisibility(View.VISIBLE);
holder.preview_container.setVisibility(View.GONE);
}else{
} else {
Helper.loadGiF(context, instance, video.getThumbnailPath(), holder.peertube_video_image, blur);
holder.peertube_video_image_small.setVisibility(View.GONE);
holder.preview_container.setVisibility(View.VISIBLE);

View File

@ -21,21 +21,6 @@ import androidx.preference.PreferenceScreen;
import androidx.preference.SeekBarPreference;
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.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
@ -60,6 +45,21 @@ import es.dmoral.toasty.Toasty;
import static app.fedilab.fedilabtube.MainActivity.peertubeInformation;
import static app.fedilab.fedilabtube.MainActivity.userMe;
/* Copyright 2020 Thomas Schneider
*
* This file is a part of TubeLab
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* TubeLab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along with TubeLab; if not,
* see <http://www.gnu.org/licenses>. */
public class SettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override
@ -135,7 +135,7 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared
if (set_video_sensitive_choice != null) {
editor.putString(getString(R.string.set_video_sensitive_choice), set_video_sensitive_choice.getValue());
editor.apply();
if(Helper.isLoggedIn(getActivity())) {
if (Helper.isLoggedIn(getActivity())) {
new Thread(() -> {
UserSettings userSettings = new UserSettings();
userSettings.setNsfwPolicy(set_video_sensitive_choice.getValue());
@ -182,7 +182,7 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared
SwitchPreference set_autoplay_choice = findPreference(getString(R.string.set_autoplay_choice));
assert set_autoplay_choice != null;
editor.putBoolean(getString(R.string.set_autoplay_choice), set_autoplay_choice.isChecked());
if(Helper.isLoggedIn(getActivity())) {
if (Helper.isLoggedIn(getActivity())) {
new Thread(() -> {
UserSettings userSettings = new UserSettings();
userSettings.setAutoPlayVideo(set_autoplay_choice.isChecked());
@ -204,7 +204,7 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared
SwitchPreference set_autoplay_next_video_choice = findPreference(getString(R.string.set_autoplay_next_video_choice));
assert set_autoplay_next_video_choice != null;
editor.putBoolean(getString(R.string.set_autoplay_next_video_choice), set_autoplay_next_video_choice.isChecked());
if(Helper.isLoggedIn(getActivity())) {
if (Helper.isLoggedIn(getActivity())) {
new Thread(() -> {
UserSettings userSettings = new UserSettings();
userSettings.setAutoPlayNextVideo(set_autoplay_next_video_choice.isChecked());
@ -233,7 +233,7 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared
MultiSelectListPreference set_video_language_choice = findPreference(getString(R.string.set_video_language_choice));
assert set_video_language_choice != null;
editor.putStringSet(getString(R.string.set_video_language_choice), set_video_language_choice.getValues());
if(Helper.isLoggedIn(getActivity())) {
if (Helper.isLoggedIn(getActivity())) {
new Thread(() -> {
UserSettings userSettings = new UserSettings();
Set<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");
assert my_account != null;
if(!Helper.isLoggedIn(getActivity()) || userMe == null) {
if (!Helper.isLoggedIn(getActivity()) || userMe == null) {
my_account.setVisible(false);
} else {
my_account.setTitle(userMe.getUsername());
@ -275,18 +275,19 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared
Drawable defaultAvatar = ResourcesCompat.getDrawable(resources, R.drawable.missing_peertube, null);
my_account.setIcon(defaultAvatar);
Glide.with(getActivity())
.asDrawable()
.load("https://" + Helper.getLiveInstance(context) + userMe.getAccount().getAvatar().getPath())
.into(new CustomTarget<Drawable>() {
@Override
public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
my_account.setIcon(resource);
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
.asDrawable()
.load("https://" + Helper.getLiveInstance(context) + userMe.getAccount().getAvatar().getPath())
.into(new CustomTarget<Drawable>() {
@Override
public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
my_account.setIcon(resource);
}
}
});
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
}
@ -307,7 +308,6 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared
}
//****** Video mode *******
ListPreference set_video_mode_choice = findPreference(getString(R.string.set_video_mode_choice));
List<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));
assert set_video_minimize_choice != null;
set_video_minimize_choice.setChecked(minimized);
if ( Build.VERSION.SDK_INT < Build.VERSION_CODES.O
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O
|| !getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) {
set_video_minimize_choice.setVisible(false);
}
@ -422,8 +422,8 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared
entryValuesSensitive[1] = Helper.BLUR.toLowerCase();
entryValuesSensitive[2] = Helper.DISPLAY.toLowerCase();
int currentSensitivePosition = 0;
for(CharSequence val : entryValuesSensitive) {
if(val.equals(currentSensitive)) {
for (CharSequence val : entryValuesSensitive) {
if (val.equals(currentSensitive)) {
break;
}
currentSensitivePosition++;

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,
* see <http://www.gnu.org/licenses>. */
import java.util.List;
import app.fedilab.fedilabtube.client.data.CommentData;
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);
}
private static int numberOfIndentation(int currentIdentation, String replyToCommentId, List<CommentData.Comment> comments) {
String targetedComment = null;
for(CommentData.Comment comment: comments) {
if( replyToCommentId.compareTo(comment.getId()) == 0) {
for (CommentData.Comment comment : comments) {
if (replyToCommentId.compareTo(comment.getId()) == 0) {
targetedComment = comment.getInReplyToCommentId();
break;
}
}
if ( targetedComment != null) {
if (targetedComment != null) {
currentIdentation++;
return numberOfIndentation(currentIdentation, targetedComment, comments);
}else{
} else {
return Math.min(currentIdentation, 5);
}
}

View File

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

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,
* see <http://www.gnu.org/licenses>. */
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;

View File

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

View File

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

View File

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

View File

@ -59,6 +59,9 @@ public class Sqlite extends SQLiteOpenHelper {
static final String COL_UUID = "UUID";
static final String COL_CACHE = "CACHE";
static final String COL_DATE = "DATE";
static final String COL_USER_INSTANCE = "USER_INSTANCE";
static final String TABLE_BOOKMARKED_INSTANCES = "BOOKMARKED_INSTANCES";
static final String COL_ABOUT = "ABOUT";
private static final String CREATE_TABLE_USER_ACCOUNT = "CREATE TABLE " + TABLE_USER_ACCOUNT + " ("
+ COL_USER_ID + " TEXT, " + COL_USERNAME + " TEXT NOT NULL, " + COL_ACCT + " TEXT NOT NULL, "
+ COL_DISPLAYED_NAME + " TEXT NOT NULL, " + COL_LOCKED + " INTEGER NOT NULL, "
@ -82,10 +85,6 @@ public class Sqlite extends SQLiteOpenHelper {
+ COL_INSTANCE + " TEXT NOT NULL, "
+ COL_CACHE + " TEXT NOT NULL, "
+ COL_DATE + " TEXT NOT NULL)";
static final String COL_USER_INSTANCE = "USER_INSTANCE";
static final String TABLE_BOOKMARKED_INSTANCES = "BOOKMARKED_INSTANCES";
static final String COL_ABOUT = "ABOUT";
private final String CREATE_TABLE_STORED_INSTANCES = "CREATE TABLE "
+ TABLE_BOOKMARKED_INSTANCES + "("
+ COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
@ -118,7 +117,7 @@ public class Sqlite extends SQLiteOpenHelper {
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch (oldVersion) {
case 2:
db.execSQL("DROP TABLE IF EXISTS " +TABLE_BOOKMARKED_INSTANCES);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_BOOKMARKED_INSTANCES);
}
}

View File

@ -42,36 +42,6 @@ public class StoredInstanceDAO {
this.db = db;
}
/**
* Insert instance info in database
*
* @param aboutInstance AboutInstance
* @param targetedInstance String
* @return boolean
*/
public boolean insertInstance(InstanceData.AboutInstance aboutInstance, String targetedInstance) {
ContentValues values = new ContentValues();
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
String instance = Helper.getLiveInstance(context);
values.put(Sqlite.COL_USER_ID, userId);
values.put(Sqlite.COL_USER_INSTANCE, instance);
values.put(Sqlite.COL_ABOUT, aboutInstanceToStringStorage(aboutInstance));
values.put(Sqlite.COL_INSTANCE, targetedInstance);
//Inserts account
try {
db.insertOrThrow(Sqlite.TABLE_BOOKMARKED_INSTANCES, null, values);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* Unserialized AboutInstance
*
@ -105,7 +75,36 @@ public class StoredInstanceDAO {
/**
* Insert instance info in database
*
* @param aboutInstance AboutInstance
* @param aboutInstance AboutInstance
* @param targetedInstance String
* @return boolean
*/
public boolean insertInstance(InstanceData.AboutInstance aboutInstance, String targetedInstance) {
ContentValues values = new ContentValues();
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
String instance = Helper.getLiveInstance(context);
values.put(Sqlite.COL_USER_ID, userId != null ? userId : "_ALL_");
values.put(Sqlite.COL_USER_INSTANCE, instance != null ? instance : "_ALL_");
values.put(Sqlite.COL_ABOUT, aboutInstanceToStringStorage(aboutInstance));
values.put(Sqlite.COL_INSTANCE, targetedInstance);
//Inserts account
try {
db.insertOrThrow(Sqlite.TABLE_BOOKMARKED_INSTANCES, null, values);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* Insert instance info in database
*
* @param aboutInstance AboutInstance
* @param targetedInstance String
* @return int
*/
@ -125,11 +124,10 @@ public class StoredInstanceDAO {
public int removeInstance(String instance) {
return db.delete(Sqlite.TABLE_BOOKMARKED_INSTANCES, Sqlite.COL_INSTANCE + " = '" +instance + "'", null);
return db.delete(Sqlite.TABLE_BOOKMARKED_INSTANCES, Sqlite.COL_INSTANCE + " = '" + instance + "'", null);
}
/**
* Returns all Instance in db
*
@ -147,7 +145,6 @@ public class StoredInstanceDAO {
}
/***
* Method to hydrate an Account from database
* @param c Cursor
@ -184,7 +181,9 @@ public class StoredInstanceDAO {
List<InstanceData.AboutInstance> aboutInstances = new ArrayList<>();
while (c.moveToNext()) {
String aboutInstanceStr = c.getString(c.getColumnIndex(Sqlite.COL_ABOUT));
String instance = c.getString(c.getColumnIndex(Sqlite.COL_INSTANCE));
InstanceData.AboutInstance aboutInstance = restoreAboutInstanceFromString(aboutInstanceStr);
aboutInstance.setHost(instance);
aboutInstances.add(aboutInstance);
}
//Close the cursor

View File

@ -37,17 +37,15 @@ import app.fedilab.fedilabtube.R;
public class MastalabWebChromeClient extends WebChromeClient implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener {
private FrameLayout videoViewContainer;
private CustomViewCallback videoViewCallback;
private ToggledFullscreenCallback toggledFullscreenCallback;
private final CustomWebview webView;
private final View activityNonVideoView;
private final ViewGroup activityVideoView;
private final ProgressBar pbar;
private boolean isVideoFullscreen;
private final Activity activity;
private FrameLayout videoViewContainer;
private CustomViewCallback videoViewCallback;
private ToggledFullscreenCallback toggledFullscreenCallback;
private boolean isVideoFullscreen;
public MastalabWebChromeClient(Activity activity, CustomWebview webView, FrameLayout activityNonVideoView, ViewGroup activityVideoView) {
@ -113,7 +111,6 @@ public class MastalabWebChromeClient extends WebChromeClient implements MediaPla
public void onShowCustomView(View view, CustomViewCallback callback) {
if (view instanceof FrameLayout) {
if (((AppCompatActivity) activity).getSupportActionBar() != null)
//noinspection ConstantConditions
((AppCompatActivity) activity).getSupportActionBar().hide();
// A video wants to be shown
FrameLayout frameLayout = (FrameLayout) view;
@ -178,7 +175,6 @@ public class MastalabWebChromeClient extends WebChromeClient implements MediaPla
@Override
public void onHideCustomView() {
if (((AppCompatActivity) activity).getSupportActionBar() != null)
//noinspection ConstantConditions
((AppCompatActivity) activity).getSupportActionBar().show();
// This method should be manually called on video end in all cases because it's not always called automatically.
// This method must be manually called on back key press (from this class' onBackPressed() method).

View File

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

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,
* see <http://www.gnu.org/licenses>. */
import android.app.Application;
import androidx.work.BackoffPolicy;
import androidx.work.Constraints;
import androidx.work.ExistingPeriodicWorkPolicy;

View File

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