diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 6ada85881..36357e4a5 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -1,5 +1,4 @@ - - + android:pathPrefix="/@" /> - + + - - + + android:label="@string/app_name"> - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + - + + + + + + + - + + + + + + - + - + - + - + + + + - + - + - + - + - + - + - + - - - - - - - - - + - + - + - + - + - + - + - + - + - + - + + android:label="@string/app_name" /> + + android:resource="@xml/file_paths" /> \ No newline at end of file diff --git a/app/src/main/java/app/fedilab/android/activities/AboutActivity.java b/app/src/main/java/app/fedilab/android/activities/AboutActivity.java index 7b43d7390..7fcb22b28 100644 --- a/app/src/main/java/app/fedilab/android/activities/AboutActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/AboutActivity.java @@ -22,8 +22,10 @@ import android.content.pm.PackageManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; + import androidx.appcompat.app.ActionBar; import androidx.appcompat.widget.Toolbar; + import android.text.SpannableString; import android.text.style.UnderlineSpan; import android.view.LayoutInflater; @@ -78,7 +80,7 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou super.onCreate(savedInstanceState); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme); break; @@ -92,10 +94,10 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou setTheme(R.style.AppThemeDark); } - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null ) { + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); assert inflater != null; View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); @@ -110,7 +112,7 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou } }); toolbar_title.setText(R.string.action_about); - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Toolbar toolbar = actionBar.getCustomView().findViewById(R.id.toolbar); Helper.colorizeToolbar(toolbar, R.color.black, AboutActivity.this); } @@ -121,7 +123,8 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); String version = pInfo.versionName; about_version.setText(getResources().getString(R.string.about_vesrion, version)); - } catch (PackageManager.NameNotFoundException ignored) {} + } catch (PackageManager.NameNotFoundException ignored) { + } ExpandableHeightListView lv_developers = findViewById(R.id.lv_developers); ExpandableHeightListView lv_designers = findViewById(R.id.lv_designers); @@ -143,11 +146,11 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou about_code.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://framagit.org/tom79/fedilab")); - startActivity(browserIntent); - } + @Override + public void onClick(View v) { + Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://framagit.org/tom79/fedilab")); + startActivity(browserIntent); + } }); about_thekinrar.setOnClickListener(new View.OnClickListener() { @@ -203,9 +206,9 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou startActivity(browserIntent); } }); - if(BuildConfig.DONATIONS){ + if (BuildConfig.DONATIONS) { about_support.setVisibility(View.VISIBLE); - }else{ + } else { about_support.setVisibility(View.GONE); } @@ -218,14 +221,13 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou } }); - if(BuildConfig.DONATIONS){ + if (BuildConfig.DONATIONS) { paypal.setVisibility(View.VISIBLE); - }else{ + } else { paypal.setVisibility(View.GONE); } - TextView about_website = findViewById(R.id.about_website); about_website.setOnClickListener(new View.OnClickListener() { @Override @@ -236,9 +238,6 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou }); - - - setTitle(R.string.action_about); lv_contributors.setExpanded(true); lv_developers.setExpanded(true); @@ -254,14 +253,14 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou accountSearchWebAdapterUxUiDesigners = new AccountSearchDevAdapter(uxuidesigners); lv_ux.setAdapter(accountSearchWebAdapterUxUiDesigners); - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA ) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { new RetrieveRemoteDataAsyncTask(getApplicationContext(), "fedilab", "framapiaf.org", AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); new RetrieveRemoteDataAsyncTask(getApplicationContext(), "mmarif", "mastodon.social", AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); new RetrieveRemoteDataAsyncTask(getApplicationContext(), "kasun", "mastodon.social", AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); new RetrieveRemoteDataAsyncTask(getApplicationContext(), "PhotonQyv", "mastodon.xyz", AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); new RetrieveRemoteDataAsyncTask(getApplicationContext(), "angrytux", "social.tchncs.de", AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); new RetrieveRemoteDataAsyncTask(getApplicationContext(), "guzzisti", "mastodon.social", AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else{ + } else { SpannableString name = new SpannableString("@fedilab@framapiaf.org"); name.setSpan(new UnderlineSpan(), 0, name.length(), 0); txt_developers.setText(name); @@ -321,13 +320,13 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou @Override public void onRetrieveRemoteAccount(Results results) { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); - if( results == null){ - Toasty.error(getApplicationContext(), getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + if (results == null) { + Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); return; } List accounts = results.getAccounts(); Account account; - if( accounts != null && accounts.size() > 0){ + if (accounts != null && accounts.size() > 0) { account = accounts.get(0); account.setFollowing(true); switch (account.getUsername()) { @@ -348,32 +347,32 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou accountSearchWebAdapterContributors.notifyDataSetChanged(); break; } - new RetrieveRelationshipAsyncTask(getApplicationContext(), account.getId(),AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new RetrieveRelationshipAsyncTask(getApplicationContext(), account.getId(), AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } @Override - public void onResume(){ + public void onResume() { super.onResume(); - if( developers != null){ - for(Account account: developers){ - new RetrieveRelationshipAsyncTask(getApplicationContext(), account.getId(),AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + if (developers != null) { + for (Account account : developers) { + new RetrieveRelationshipAsyncTask(getApplicationContext(), account.getId(), AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } - if( designers != null){ - for(Account account: designers){ - new RetrieveRelationshipAsyncTask(getApplicationContext(), account.getId(),AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + if (designers != null) { + for (Account account : designers) { + new RetrieveRelationshipAsyncTask(getApplicationContext(), account.getId(), AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } - if( contributors != null){ - for(Account account: contributors){ - new RetrieveRelationshipAsyncTask(getApplicationContext(), account.getId(),AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + if (contributors != null) { + for (Account account : contributors) { + new RetrieveRelationshipAsyncTask(getApplicationContext(), account.getId(), AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } - if( uxuidesigners != null){ - for(Account account: uxuidesigners){ - new RetrieveRelationshipAsyncTask(getApplicationContext(), account.getId(),AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + if (uxuidesigners != null) { + for (Account account : uxuidesigners) { + new RetrieveRelationshipAsyncTask(getApplicationContext(), account.getId(), AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } } @@ -382,32 +381,32 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou public void onRetrieveRelationship(Relationship relationship, Error error) { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, ""); - if( error != null){ + if (error != null) { return; } - for( int i = 0 ; i < developers.size() ; i++){ - if( developers.get(i).getId() != null && developers.get(i).getId().equals(relationship.getId())){ + for (int i = 0; i < developers.size(); i++) { + if (developers.get(i).getId() != null && developers.get(i).getId().equals(relationship.getId())) { developers.get(i).setFollowing(relationship.isFollowing() || userId.trim().equals(relationship.getId())); accountSearchWebAdapterDeveloper.notifyDataSetChanged(); break; } } - for( int i = 0 ; i < designers.size() ; i++){ - if( designers.get(i).getId() != null && designers.get(i).getId().equals(relationship.getId())){ + for (int i = 0; i < designers.size(); i++) { + if (designers.get(i).getId() != null && designers.get(i).getId().equals(relationship.getId())) { designers.get(i).setFollowing(relationship.isFollowing() || userId.trim().equals(relationship.getId())); accountSearchWebAdapterDesigner.notifyDataSetChanged(); break; } } - for( int i = 0 ; i < contributors.size() ; i++){ - if( contributors.get(i).getId() != null && contributors.get(i).getId().equals(relationship.getId())){ + for (int i = 0; i < contributors.size(); i++) { + if (contributors.get(i).getId() != null && contributors.get(i).getId().equals(relationship.getId())) { contributors.get(i).setFollowing(relationship.isFollowing() || userId.trim().equals(relationship.getId())); accountSearchWebAdapterContributors.notifyDataSetChanged(); break; } } - for( int i = 0 ; i < uxuidesigners.size() ; i++){ - if( uxuidesigners.get(i).getId() != null && uxuidesigners.get(i).getId().equals(relationship.getId())){ + for (int i = 0; i < uxuidesigners.size(); i++) { + if (uxuidesigners.get(i).getId() != null && uxuidesigners.get(i).getId().equals(relationship.getId())) { uxuidesigners.get(i).setFollowing(relationship.isFollowing() || userId.trim().equals(relationship.getId())); accountSearchWebAdapterUxUiDesigners.notifyDataSetChanged(); break; diff --git a/app/src/main/java/app/fedilab/android/activities/AccountReportActivity.java b/app/src/main/java/app/fedilab/android/activities/AccountReportActivity.java index 69efddadf..b4d7ac5d1 100644 --- a/app/src/main/java/app/fedilab/android/activities/AccountReportActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/AccountReportActivity.java @@ -86,7 +86,7 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction if (b != null) { account_id = b.getString("account_id", null); targeted_account = b.getParcelable("targeted_account"); - report = b.getParcelable("report"); + report = b.getParcelable("report"); } if (getSupportActionBar() != null) @@ -136,22 +136,22 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction email_user = findViewById(R.id.email_user); comment = findViewById(R.id.comment); - if( account_id == null && report == null && targeted_account == null){ + if (account_id == null && report == null && targeted_account == null) { Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); finish(); } assign.setVisibility(View.GONE); status.setVisibility(View.GONE); - if( account_id != null){ + if (account_id != null) { new PostAdminActionAsyncTask(getApplicationContext(), API.adminAction.GET_ONE_ACCOUNT, account_id, null, AccountReportActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); return; } - if( report != null) { + if (report != null) { targeted_account = report.getTarget_account(); RecyclerView lv_statuses = findViewById(R.id.lv_statuses); ArrayList contents = new ArrayList<>(); - for(Status status: report.getStatuses()){ + for (Status status : report.getStatuses()) { contents.add(status.getContent()); } lv_statuses.setLayoutManager(new LinearLayoutManager(this)); @@ -160,15 +160,15 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction Group statuses_group = findViewById(R.id.statuses_group); statuses_group.setVisibility(View.VISIBLE); - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA){ + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { new PostAdminActionAsyncTask(getApplicationContext(), API.adminAction.GET_ONE_ACCOUNT, report.getTarget_account().getUsername(), null, AccountReportActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } - if( targeted_account != null) { + if (targeted_account != null) { account_id = targeted_account.getId(); fillReport(targeted_account); - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA){ + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { account_id = targeted_account.getUsername(); } } @@ -178,37 +178,37 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction @Override public void onAdminAction(APIResponse apiResponse) { - if( apiResponse.getError() != null){ - if( apiResponse.getError().getStatusCode() == 403){ + if (apiResponse.getError() != null) { + if (apiResponse.getError().getStatusCode() == 403) { AlertDialog.Builder builderInner; builderInner = new AlertDialog.Builder(AccountReportActivity.this, R.style.AdminDialog); builderInner.setTitle(R.string.reconnect_account); builderInner.setMessage(R.string.reconnect_account_message); builderInner.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog,int which) { + public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builderInner.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog,int which) { + public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(AccountReportActivity.this, LoginActivity.class); intent.putExtra("admin", true); startActivity(intent); } }); builderInner.show(); - }else{ - Toasty.error(getApplicationContext(), apiResponse.getError().getError(),Toast.LENGTH_LONG).show(); + } else { + Toasty.error(getApplicationContext(), apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); } return; } - if( apiResponse.getReports() != null && apiResponse.getReports().size() > 0){ + if (apiResponse.getReports() != null && apiResponse.getReports().size() > 0) { report = apiResponse.getReports().get(0); fillReport(report.getTarget_account()); - } else if( apiResponse.getAccountAdmins() != null && apiResponse.getAccountAdmins().size() > 0) { - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA){ + } else if (apiResponse.getAccountAdmins() != null && apiResponse.getAccountAdmins().size() > 0) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { account_id = apiResponse.getAccountAdmins().get(0).getUsername(); } fillReport(apiResponse.getAccountAdmins().get(0)); @@ -216,29 +216,29 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction } - private void fillReport(AccountAdmin accountAdmin){ + private void fillReport(AccountAdmin accountAdmin) { - if( accountAdmin == null){ + if (accountAdmin == null) { Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); return; } - if(!accountAdmin.isApproved() && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA && (accountAdmin.getDomain() == null || accountAdmin.getDomain().equals("null"))){ + if (!accountAdmin.isApproved() && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA && (accountAdmin.getDomain() == null || accountAdmin.getDomain().equals("null"))) { allow_reject_group.setVisibility(View.VISIBLE); } - reject.setOnClickListener(view->{ + reject.setOnClickListener(view -> { AdminAction adminAction = new AdminAction(); adminAction.setType(REJECT); new PostAdminActionAsyncTask(getApplicationContext(), REJECT, account_id, adminAction, AccountReportActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); }); - allow.setOnClickListener(view->{ + allow.setOnClickListener(view -> { AdminAction adminAction = new AdminAction(); adminAction.setType(APPROVE); new PostAdminActionAsyncTask(getApplicationContext(), APPROVE, account_id, adminAction, AccountReportActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); }); - warn.setOnClickListener(view->{ + warn.setOnClickListener(view -> { AdminAction adminAction = new AdminAction(); adminAction.setType(NONE); adminAction.setSend_email_notification(email_user.isChecked()); @@ -247,58 +247,58 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction }); - if( !accountAdmin.isSilenced() ) { + if (!accountAdmin.isSilenced()) { silence.setText(getString(R.string.silence)); - }else{ + } else { silence.setText(getString(R.string.unsilence)); } - silence.setOnClickListener(view->{ - if( !accountAdmin.isSilenced() ) { + silence.setOnClickListener(view -> { + if (!accountAdmin.isSilenced()) { AdminAction adminAction = new AdminAction(); adminAction.setType(SILENCE); adminAction.setSend_email_notification(email_user.isChecked()); adminAction.setText(comment.getText().toString().trim()); new PostAdminActionAsyncTask(getApplicationContext(), SILENCE, account_id, adminAction, AccountReportActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else{ + } else { new PostAdminActionAsyncTask(getApplicationContext(), API.adminAction.UNSILENCE, account_id, null, AccountReportActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } }); - if( !accountAdmin.isDisabled() ) { + if (!accountAdmin.isDisabled()) { disable.setText(getString(R.string.disable)); - }else{ + } else { disable.setText(getString(R.string.undisable)); } - disable.setOnClickListener(view->{ - if( !accountAdmin.isDisabled()) { + disable.setOnClickListener(view -> { + if (!accountAdmin.isDisabled()) { AdminAction adminAction = new AdminAction(); adminAction.setType(DISABLE); adminAction.setSend_email_notification(email_user.isChecked()); adminAction.setText(comment.getText().toString().trim()); new PostAdminActionAsyncTask(getApplicationContext(), DISABLE, account_id, adminAction, AccountReportActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else{ + } else { new PostAdminActionAsyncTask(getApplicationContext(), API.adminAction.ENABLE, account_id, null, AccountReportActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } }); - if( !accountAdmin.isSuspended() ) { + if (!accountAdmin.isSuspended()) { suspend.setText(getString(R.string.suspend)); - }else{ + } else { suspend.setText(getString(R.string.unsuspend)); } - suspend.setOnClickListener(view->{ - if( !accountAdmin.isSuspended() ){ + suspend.setOnClickListener(view -> { + if (!accountAdmin.isSuspended()) { AdminAction adminAction = new AdminAction(); adminAction.setType(SUSPEND); adminAction.setSend_email_notification(email_user.isChecked()); adminAction.setText(comment.getText().toString().trim()); new PostAdminActionAsyncTask(getApplicationContext(), SUSPEND, account_id, adminAction, AccountReportActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else{ + } else { new PostAdminActionAsyncTask(getApplicationContext(), API.adminAction.UNSUSPEND, account_id, null, AccountReportActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } }); - if( accountAdmin.getAction() != null) { + if (accountAdmin.getAction() != null) { String message = null; switch (accountAdmin.getAction()) { case SILENCE: @@ -331,7 +331,7 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction message = getString(R.string.account_rejected); break; } - if( message != null){ + if (message != null) { Toasty.success(getApplicationContext(), message, Toast.LENGTH_LONG).show(); } comment.setText(""); @@ -340,35 +340,32 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction } - - - username.setText(String.format("@%s", accountAdmin.getAccount().getAcct())); email.setText(accountAdmin.getEmail()); - if( accountAdmin.getEmail() == null || accountAdmin.getEmail().trim().equals("")){ + if (accountAdmin.getEmail() == null || accountAdmin.getEmail().trim().equals("")) { email.setVisibility(View.GONE); email_label.setVisibility(View.GONE); } - if( accountAdmin.getIp() == null || accountAdmin.getIp().trim().equals("")){ + if (accountAdmin.getIp() == null || accountAdmin.getIp().trim().equals("")) { recent_ip.setVisibility(View.GONE); recent_ip_label.setVisibility(View.GONE); } - if( accountAdmin.getCreated_at() == null ){ + if (accountAdmin.getCreated_at() == null) { joined.setVisibility(View.GONE); joined_label.setVisibility(View.GONE); } - if( accountAdmin.isDisabled()){ + if (accountAdmin.isDisabled()) { login_status.setText(getString(R.string.disabled)); - }else if( accountAdmin.isSilenced()){ + } else if (accountAdmin.isSilenced()) { login_status.setText(getString(R.string.silenced)); - }else if( accountAdmin.isSuspended()){ + } else if (accountAdmin.isSuspended()) { login_status.setText(getString(R.string.suspended)); - }else{ + } else { login_status.setText(getString(R.string.active)); } - if( accountAdmin.getDomain() == null || accountAdmin.getDomain().equals("null")){ + if (accountAdmin.getDomain() == null || accountAdmin.getDomain().equals("null")) { warn.setVisibility(View.VISIBLE); email_user.setVisibility(View.VISIBLE); comment_label.setVisibility(View.VISIBLE); @@ -376,7 +373,7 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction recent_ip.setText(accountAdmin.getIp()); disable.setVisibility(View.VISIBLE); suspend.setVisibility(View.VISIBLE); - }else{ + } else { warn.setVisibility(View.GONE); email_user.setVisibility(View.GONE); email_user.setChecked(false); @@ -389,7 +386,7 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction comment_label.setVisibility(View.GONE); } - if( accountAdmin.getRole() != null) { + if (accountAdmin.getRole() != null) { switch (accountAdmin.getRole()) { case "user": permissions.setText(getString(R.string.user)); @@ -401,7 +398,7 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction permissions.setText(getString(R.string.administrator)); break; } - if( accountAdmin.getRole().equals("admin") || accountAdmin.getRole().equals("moderator")){ + if (accountAdmin.getRole().equals("admin") || accountAdmin.getRole().equals("moderator")) { warn.setVisibility(View.GONE); suspend.setVisibility(View.GONE); silence.setVisibility(View.GONE); @@ -411,44 +408,44 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction comment.setVisibility(View.GONE); comment_label.setVisibility(View.GONE); } - email_status.setText(accountAdmin.isConfirmed()?getString(R.string.confirmed):getString(R.string.unconfirmed)); + email_status.setText(accountAdmin.isConfirmed() ? getString(R.string.confirmed) : getString(R.string.unconfirmed)); } joined.setText(Helper.dateToString(accountAdmin.getCreated_at())); - if( report != null){ + if (report != null) { assign.setVisibility(View.VISIBLE); status.setVisibility(View.VISIBLE); - if( report.getAssigned_account() == null){ + if (report.getAssigned_account() == null) { assign.setText(getString(R.string.assign_to_me)); - }else{ + } else { assign.setText(getString(R.string.unassign)); } - assign.setOnClickListener(view ->{ - if( report.getAssigned_account() == null){ + assign.setOnClickListener(view -> { + if (report.getAssigned_account() == null) { new PostAdminActionAsyncTask(getApplicationContext(), API.adminAction.ASSIGN_TO_SELF, report.getId(), null, AccountReportActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else{ + } else { new PostAdminActionAsyncTask(getApplicationContext(), API.adminAction.UNASSIGN, report.getId(), null, AccountReportActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } }); - if( report.isAction_taken()){ + if (report.isAction_taken()) { status.setText(getString(R.string.mark_unresolved)); - }else{ + } else { status.setText(getString(R.string.mark_resolved)); } - status.setOnClickListener(view ->{ - if( report.isAction_taken() ){ + status.setOnClickListener(view -> { + if (report.isAction_taken()) { new PostAdminActionAsyncTask(getApplicationContext(), API.adminAction.REOPEN, report.getId(), null, AccountReportActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else{ + } else { new PostAdminActionAsyncTask(getApplicationContext(), API.adminAction.RESOLVE, report.getId(), null, AccountReportActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } }); - }else{ + } else { assign.setVisibility(View.GONE); status.setVisibility(View.GONE); } - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA){ + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { email_user.setVisibility(View.GONE); email_user.setChecked(false); comment.setVisibility(View.INVISIBLE); diff --git a/app/src/main/java/app/fedilab/android/activities/AdminActivity.java b/app/src/main/java/app/fedilab/android/activities/AdminActivity.java index 4a20518c1..2f6dc13c5 100644 --- a/app/src/main/java/app/fedilab/android/activities/AdminActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/AdminActivity.java @@ -25,6 +25,7 @@ import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; + import androidx.appcompat.app.ActionBar; import androidx.appcompat.widget.PopupMenu; import androidx.fragment.app.Fragment; @@ -33,7 +34,9 @@ import androidx.fragment.app.FragmentStatePagerAdapter; import androidx.fragment.app.FragmentTransaction; import androidx.viewpager.widget.PagerAdapter; import androidx.viewpager.widget.ViewPager; + import com.google.android.material.tabs.TabLayout; + import app.fedilab.android.R; import app.fedilab.android.asynctasks.UpdateAccountInfoAsyncTask; import app.fedilab.android.fragments.DisplayAdminAccountsFragment; @@ -49,7 +52,7 @@ import static app.fedilab.android.activities.BaseMainActivity.mPageReferenceMap; * Admin activity */ -public class AdminActivity extends BaseActivity { +public class AdminActivity extends BaseActivity { private boolean unresolved; @@ -65,10 +68,10 @@ public class AdminActivity extends BaseActivity { setTheme(R.style.AppAdminTheme); - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null ) { + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); assert inflater != null; View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); @@ -82,7 +85,7 @@ public class AdminActivity extends BaseActivity { finish(); } }); - toolbar_title.setText(String.format(getString(R.string.administration)+ " %s", Helper.getLiveInstance(getApplicationContext()))); + toolbar_title.setText(String.format(getString(R.string.administration) + " %s", Helper.getLiveInstance(getApplicationContext()))); } setContentView(R.layout.activity_admin); unresolved = local = active = true; @@ -113,7 +116,7 @@ public class AdminActivity extends BaseActivity { FragmentTransaction fragTransaction = getSupportFragmentManager().beginTransaction(); fragTransaction.detach(displayAdminReportsFragment); Bundle bundle = new Bundle(); - bundle.putBoolean("unresolved",unresolved); + bundle.putBoolean("unresolved", unresolved); displayAdminReportsFragment.setArguments(bundle); fragTransaction.attach(displayAdminReportsFragment); fragTransaction.commit(); @@ -161,7 +164,7 @@ public class AdminActivity extends BaseActivity { final MenuItem itemDisabled = menu.findItem(R.id.action_disabled); final MenuItem itemSilenced = menu.findItem(R.id.action_silenced); final MenuItem itemSuspended = menu.findItem(R.id.action_suspended); - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA){ + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { itemSilenced.setVisible(false); itemPending.setVisible(false); itemSuspended.setVisible(false); @@ -181,13 +184,13 @@ public class AdminActivity extends BaseActivity { FragmentTransaction fragTransaction = getSupportFragmentManager().beginTransaction(); fragTransaction.detach(displayAdminAccountsFragment); Bundle bundle = new Bundle(); - bundle.putBoolean("local",local); - bundle.putBoolean("remote",remote); - bundle.putBoolean("active",active); - bundle.putBoolean("pending",pending); - bundle.putBoolean("disabled",disabled); - bundle.putBoolean("silenced",silenced); - bundle.putBoolean("suspended",suspended); + bundle.putBoolean("local", local); + bundle.putBoolean("remote", remote); + bundle.putBoolean("active", active); + bundle.putBoolean("pending", pending); + bundle.putBoolean("disabled", disabled); + bundle.putBoolean("silenced", silenced); + bundle.putBoolean("suspended", suspended); displayAdminAccountsFragment.setArguments(bundle); fragTransaction.attach(displayAdminAccountsFragment); fragTransaction.commit(); @@ -210,21 +213,21 @@ public class AdminActivity extends BaseActivity { return false; } }); - switch (item.getItemId()){ + switch (item.getItemId()) { case R.id.action_local: - if( !local) { + if (!local) { remote = false; local = true; } break; case R.id.action_remote: - if( !remote) { + if (!remote) { remote = true; local = false; } break; case R.id.action_active: - if( !active) { + if (!active) { active = true; pending = false; disabled = false; @@ -233,7 +236,7 @@ public class AdminActivity extends BaseActivity { } break; case R.id.action_pending: - if( !pending) { + if (!pending) { pending = true; active = false; disabled = false; @@ -242,7 +245,7 @@ public class AdminActivity extends BaseActivity { } break; case R.id.action_disabled: - if( !disabled) { + if (!disabled) { disabled = true; active = false; pending = false; @@ -251,7 +254,7 @@ public class AdminActivity extends BaseActivity { } break; case R.id.action_silenced: - if( !silenced) { + if (!silenced) { silenced = true; active = false; pending = false; @@ -260,7 +263,7 @@ public class AdminActivity extends BaseActivity { } break; case R.id.action_suspended: - if( !suspended) { + if (!suspended) { suspended = true; active = false; pending = false; @@ -286,7 +289,6 @@ public class AdminActivity extends BaseActivity { }); - PagerAdapter mPagerAdapter = new AdminPagerAdapter(getSupportFragmentManager()); admin_viewpager.setAdapter(mPagerAdapter); admin_viewpager.setOffscreenPageLimit(2); @@ -305,17 +307,17 @@ public class AdminActivity extends BaseActivity { @Override public void onTabReselected(TabLayout.Tab tab) { Fragment fragment = null; - if( admin_viewpager.getAdapter() != null) + if (admin_viewpager.getAdapter() != null) fragment = (Fragment) admin_viewpager.getAdapter().instantiateItem(admin_viewpager, tab.getPosition()); - switch (tab.getPosition()){ + switch (tab.getPosition()) { case 0: - if( fragment != null) { + if (fragment != null) { displayAdminReportsFragment = ((DisplayAdminReportsFragment) fragment); displayAdminReportsFragment.scrollToTop(); } break; case 1: - if( fragment != null) { + if (fragment != null) { displayAdminAccountsFragment = ((DisplayAdminAccountsFragment) fragment); displayAdminAccountsFragment.scrollToTop(); } @@ -337,23 +339,23 @@ public class AdminActivity extends BaseActivity { @Override public Fragment getItem(int position) { Bundle bundle = new Bundle(); - switch (position){ + switch (position) { case 0: displayAdminReportsFragment = new DisplayAdminReportsFragment(); bundle = new Bundle(); - bundle.putBoolean("unresolved",unresolved); + bundle.putBoolean("unresolved", unresolved); displayAdminReportsFragment.setArguments(bundle); return displayAdminReportsFragment; case 1: displayAdminAccountsFragment = new DisplayAdminAccountsFragment(); bundle = new Bundle(); - bundle.putBoolean("local",local); - bundle.putBoolean("remote",remote); - bundle.putBoolean("active",active); - bundle.putBoolean("pending",pending); - bundle.putBoolean("disabled",disabled); - bundle.putBoolean("silenced",silenced); - bundle.putBoolean("suspended",suspended); + bundle.putBoolean("local", local); + bundle.putBoolean("remote", remote); + bundle.putBoolean("active", active); + bundle.putBoolean("pending", pending); + bundle.putBoolean("disabled", disabled); + bundle.putBoolean("silenced", silenced); + bundle.putBoolean("suspended", suspended); displayAdminAccountsFragment.setArguments(bundle); return displayAdminAccountsFragment; } diff --git a/app/src/main/java/app/fedilab/android/activities/BaseActivity.java b/app/src/main/java/app/fedilab/android/activities/BaseActivity.java index 5b864fef5..eee50b47e 100644 --- a/app/src/main/java/app/fedilab/android/activities/BaseActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/BaseActivity.java @@ -5,8 +5,11 @@ import android.app.ProgressDialog; import android.content.Context; import android.content.pm.PackageManager; import android.content.res.Configuration; + import androidx.annotation.NonNull; + import com.google.android.material.snackbar.Snackbar; + import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.appcompat.app.AppCompatActivity; @@ -67,9 +70,9 @@ public class BaseActivity extends AppCompatActivity { } @Override - public void onDestroy(){ + public void onDestroy() { super.onDestroy(); - if( timer != null){ + if (timer != null) { timer.cancel(); timer = null; } diff --git a/app/src/main/java/app/fedilab/android/activities/BaseMainActivity.java b/app/src/main/java/app/fedilab/android/activities/BaseMainActivity.java index a471efff0..b267aeeea 100644 --- a/app/src/main/java/app/fedilab/android/activities/BaseMainActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/BaseMainActivity.java @@ -37,10 +37,12 @@ import android.os.Parcelable; import android.preference.PreferenceManager; import androidx.annotation.NonNull; + import com.google.android.material.appbar.AppBarLayout; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.navigation.NavigationView; import com.google.android.material.tabs.TabLayout; + import androidx.core.app.ActivityCompat; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; @@ -188,8 +190,6 @@ public abstract class BaseMainActivity extends BaseActivity public static boolean show_boosts, show_replies, show_art_nsfw; - - @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -201,7 +201,7 @@ public abstract class BaseMainActivity extends BaseActivity instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(getApplicationContext())); SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); Account account = new AccountDAO(getApplicationContext(), db).getUniqAccount(userId, instance); - if( account == null){ + if (account == null) { Helper.logout(getApplicationContext()); Intent myIntent = new Intent(BaseMainActivity.this, LoginActivity.class); startActivity(myIntent); @@ -210,17 +210,17 @@ public abstract class BaseMainActivity extends BaseActivity } //Update the static variable which manages account type - if( account.getSocial() == null || account.getSocial().equals("MASTODON")) + if (account.getSocial() == null || account.getSocial().equals("MASTODON")) social = UpdateAccountInfoAsyncTask.SOCIAL.MASTODON; - else if( account.getSocial().equals("PEERTUBE")) + else if (account.getSocial().equals("PEERTUBE")) social = UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE; - else if( account.getSocial().equals("PIXELFED")) + else if (account.getSocial().equals("PIXELFED")) social = UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED; - else if( account.getSocial().equals("PLEROMA")) + else if (account.getSocial().equals("PLEROMA")) social = UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA; - else if( account.getSocial().equals("GNU")) + else if (account.getSocial().equals("GNU")) social = UpdateAccountInfoAsyncTask.SOCIAL.GNU; - else if( account.getSocial().equals("FRIENDICA")) + else if (account.getSocial().equals("FRIENDICA")) social = UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA; countNewStatus = 0; countNewNotifications = 0; @@ -233,7 +233,7 @@ public abstract class BaseMainActivity extends BaseActivity show_boosts = sharedpreferences.getBoolean(Helper.SET_SHOW_BOOSTS, true); show_replies = sharedpreferences.getBoolean(Helper.SET_SHOW_REPLIES, true); - if( mPageReferenceMap == null ){ + if (mPageReferenceMap == null) { mPageReferenceMap = new HashMap<>(); } if (!isTaskRoot() @@ -245,7 +245,7 @@ public abstract class BaseMainActivity extends BaseActivity return; } final int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme_NoActionBar_Fedilab); break; @@ -261,7 +261,7 @@ public abstract class BaseMainActivity extends BaseActivity setContentView(R.layout.activity_main); //Test if user is still log in - if( ! Helper.isLoggedIn(getApplicationContext())) { + if (!Helper.isLoggedIn(getApplicationContext())) { //It is not, the user is redirected to the login page Intent myIntent = new Intent(BaseMainActivity.this, LoginActivity.class); startActivity(myIntent); @@ -273,10 +273,11 @@ public abstract class BaseMainActivity extends BaseActivity //Intialize Peertube information //This task will allow to instance a static PeertubeInformation class - if( social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE){ - try{ + if (social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { + try { new RetrievePeertubeInformationAsyncTask(getApplicationContext()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }catch (Exception ignored){} + } catch (Exception ignored) { + } } //For old Mastodon releases that can't pin, this support could be removed Helper.canPin = false; @@ -284,25 +285,25 @@ public abstract class BaseMainActivity extends BaseActivity //Here, the user is authenticated appBar = findViewById(R.id.appBar); Toolbar toolbar = findViewById(R.id.toolbar); - if( theme == Helper.THEME_BLACK) + if (theme == Helper.THEME_BLACK) toolbar.setBackgroundColor(ContextCompat.getColor(BaseMainActivity.this, R.color.black)); setSupportActionBar(toolbar); - toolbarTitle = toolbar.findViewById(R.id.toolbar_title); + toolbarTitle = toolbar.findViewById(R.id.toolbar_title); toolbar_search = toolbar.findViewById(R.id.toolbar_search); delete_instance = findViewById(R.id.delete_instance); display_timeline = findViewById(R.id.display_timeline); - if( theme == Helper.THEME_LIGHT) { + if (theme == Helper.THEME_LIGHT) { ImageView icon = toolbar_search.findViewById(R.id.search_button); ImageView close = toolbar_search.findViewById(R.id.search_close_btn); - if( icon != null) + if (icon != null) icon.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.dark_icon)); - if( close != null) + if (close != null) close.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.dark_icon)); EditText editText = toolbar_search.findViewById(R.id.search_src_text); editText.setHintTextColor(getResources().getColor(R.color.dark_icon)); editText.setTextColor(getResources().getColor(R.color.dark_icon)); - changeDrawableColor(BaseMainActivity.this,delete_instance, R.color.dark_icon); - changeDrawableColor(BaseMainActivity.this,display_timeline, R.color.dark_icon); + changeDrawableColor(BaseMainActivity.this, delete_instance, R.color.dark_icon); + changeDrawableColor(BaseMainActivity.this, display_timeline, R.color.dark_icon); } tabLayout = findViewById(R.id.tabLayout); @@ -312,7 +313,7 @@ public abstract class BaseMainActivity extends BaseActivity display_timeline.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - if( timelines == null || timelines.size() <= 0 ){ + if (timelines == null || timelines.size() <= 0) { return; } PopupMenu popup = new PopupMenu(BaseMainActivity.this, display_timeline); @@ -326,13 +327,13 @@ public abstract class BaseMainActivity extends BaseActivity int i = 0; for (ManageTimelines tl : timelines) { MenuItem item = null; - switch (tl.getType()){ + switch (tl.getType()) { case LIST: item = popup.getMenu().add(0, 0, Menu.NONE, tl.getListTimeline().getTitle()); item.setIcon(R.drawable.ic_list_top_menu); break; case TAG: - String name = (tl.getTagTimeline().getDisplayname()!= null && tl.getTagTimeline().getDisplayname().length() > 0)?tl.getTagTimeline().getDisplayname():tl.getTagTimeline().getName(); + String name = (tl.getTagTimeline().getDisplayname() != null && tl.getTagTimeline().getDisplayname().length() > 0) ? tl.getTagTimeline().getDisplayname() : tl.getTagTimeline().getName(); item = popup.getMenu().add(0, 0, Menu.NONE, name); item.setIcon(R.drawable.ic_label_top_menu); break; @@ -357,12 +358,12 @@ public abstract class BaseMainActivity extends BaseActivity } break; } - if( item != null){ + if (item != null) { int finalI = i; item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { - if( finalI < tabLayout.getTabCount() && tabLayout.getTabAt(finalI) != null) { + if (finalI < tabLayout.getTabCount() && tabLayout.getTabAt(finalI) != null) { tabLayout.getTabAt(finalI).select(); } return false; @@ -386,10 +387,10 @@ public abstract class BaseMainActivity extends BaseActivity add_new = findViewById(R.id.add_new); main_app_container = findViewById(R.id.main_app_container); - if( social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { new SyncTimelinesAsyncTask(BaseMainActivity.this, 0, BaseMainActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else if (social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE){ + } else if (social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { TabLayout.Tab pTabsub = tabLayout.newTab(); TabLayout.Tab pTabOver = tabLayout.newTab(); TabLayout.Tab pTabTrend = tabLayout.newTab(); @@ -432,7 +433,6 @@ public abstract class BaseMainActivity extends BaseActivity iconLocal.setImageResource(R.drawable.ic_home); - iconSub.setContentDescription(getString(R.string.subscriptions)); iconOver.setContentDescription(getString(R.string.overview)); iconTrend.setContentDescription(getString(R.string.trending)); @@ -463,8 +463,6 @@ public abstract class BaseMainActivity extends BaseActivity tabLayout.addTab(pTabLocal); - - adapter = new PagerAdapter (getSupportFragmentManager(), tabLayout.getTabCount()); viewPager.setAdapter(adapter); @@ -481,10 +479,10 @@ public abstract class BaseMainActivity extends BaseActivity tootShow(); DrawerLayout drawer = findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); - if( tab.getCustomView() != null) { + if (tab.getCustomView() != null) { ImageView icon = tab.getCustomView().findViewById(R.id.tab_icon); - if( icon != null) - if( theme == Helper.THEME_BLACK) + if (icon != null) + if (theme == Helper.THEME_BLACK) icon.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.dark_icon), PorterDuff.Mode.SRC_IN); else icon.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.mastodonC4), PorterDuff.Mode.SRC_IN); @@ -494,10 +492,10 @@ public abstract class BaseMainActivity extends BaseActivity @Override public void onTabUnselected(TabLayout.Tab tab) { - if( tab.getCustomView() != null) { + if (tab.getCustomView() != null) { ImageView icon = tab.getCustomView().findViewById(R.id.tab_icon); - if( icon != null) - if( theme == Helper.THEME_LIGHT) + if (icon != null) + if (theme == Helper.THEME_LIGHT) icon.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.dark_icon), PorterDuff.Mode.SRC_IN); else icon.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.dark_text), PorterDuff.Mode.SRC_IN); @@ -506,14 +504,14 @@ public abstract class BaseMainActivity extends BaseActivity @Override public void onTabReselected(TabLayout.Tab tab) { - if( tab.getCustomView() != null) { + if (tab.getCustomView() != null) { ImageView icon = tab.getCustomView().findViewById(R.id.tab_icon); - if( icon != null) - if( theme == Helper.THEME_BLACK) + if (icon != null) + if (theme == Helper.THEME_BLACK) icon.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.dark_icon), PorterDuff.Mode.SRC_IN); else icon.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.mastodonC4), PorterDuff.Mode.SRC_IN); - if( viewPager.getAdapter() != null) { + if (viewPager.getAdapter() != null) { Fragment fragment = (Fragment) viewPager.getAdapter().instantiateItem(viewPager, tab.getPosition()); DisplayStatusFragment displayStatusFragment = ((DisplayStatusFragment) fragment); displayStatusFragment.scrollToTop(); @@ -530,14 +528,13 @@ public abstract class BaseMainActivity extends BaseActivity displayStatusFragment.scrollToTop(); } }); - }else if (social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED){ + } else if (social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) { TabLayout.Tab pfTabHome = tabLayout.newTab(); TabLayout.Tab pfTabLocal = tabLayout.newTab(); TabLayout.Tab pfTabNotification = tabLayout.newTab(); //TabLayout.Tab pfTabDiscover = tabLayout.newTab(); - pfTabHome.setCustomView(R.layout.tab_badge); pfTabLocal.setCustomView(R.layout.tab_badge); pfTabNotification.setCustomView(R.layout.tab_badge); @@ -560,7 +557,7 @@ public abstract class BaseMainActivity extends BaseActivity iconLocal.setImageResource(R.drawable.ic_people); - @SuppressWarnings("ConstantConditions") @SuppressLint("CutPasteId") + @SuppressWarnings("ConstantConditions") @SuppressLint("CutPasteId") ImageView iconNotif = pfTabNotification.getCustomView().findViewById(R.id.tab_icon); iconNotif.setImageResource(R.drawable.ic_notifications); @@ -569,30 +566,28 @@ public abstract class BaseMainActivity extends BaseActivity iconDiscover.setImageResource(R.drawable.ic_people);*/ - iconHome.setContentDescription(getString(R.string.home_menu)); - // iconDiscover.setContentDescription(getString(R.string.overview)); + // iconDiscover.setContentDescription(getString(R.string.overview)); iconLocal.setContentDescription(getString(R.string.local)); iconNotif.setContentDescription(getString(R.string.notifications)); if (theme == Helper.THEME_LIGHT) { iconHome.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.action_light_header), PorterDuff.Mode.SRC_IN); - // iconDiscover.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.action_light_header), PorterDuff.Mode.SRC_IN); + // iconDiscover.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.action_light_header), PorterDuff.Mode.SRC_IN); iconLocal.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.action_light_header), PorterDuff.Mode.SRC_IN); iconNotif.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.action_light_header), PorterDuff.Mode.SRC_IN); } else { iconHome.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.dark_text), PorterDuff.Mode.SRC_IN); - // iconDiscover.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.dark_text), PorterDuff.Mode.SRC_IN); + // iconDiscover.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.dark_text), PorterDuff.Mode.SRC_IN); iconLocal.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.dark_text), PorterDuff.Mode.SRC_IN); iconNotif.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.dark_text), PorterDuff.Mode.SRC_IN); } - tabLayout.addTab(pfTabHome); tabLayout.addTab(pfTabLocal); tabLayout.addTab(pfTabNotification); - // tabLayout.addTab(pfTabDiscover); + // tabLayout.addTab(pfTabDiscover); tabLayout.setTabMode(TabLayout.MODE_FIXED); tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); @@ -612,10 +607,10 @@ public abstract class BaseMainActivity extends BaseActivity tootShow(); DrawerLayout drawer = findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); - if( tab.getCustomView() != null) { + if (tab.getCustomView() != null) { ImageView icon = tab.getCustomView().findViewById(R.id.tab_icon); - if( icon != null) - if( theme == Helper.THEME_BLACK) + if (icon != null) + if (theme == Helper.THEME_BLACK) icon.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.dark_icon), PorterDuff.Mode.SRC_IN); else icon.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.mastodonC4), PorterDuff.Mode.SRC_IN); @@ -625,10 +620,10 @@ public abstract class BaseMainActivity extends BaseActivity @Override public void onTabUnselected(TabLayout.Tab tab) { - if( tab.getCustomView() != null) { + if (tab.getCustomView() != null) { ImageView icon = tab.getCustomView().findViewById(R.id.tab_icon); - if( icon != null) - if( theme == Helper.THEME_LIGHT) + if (icon != null) + if (theme == Helper.THEME_LIGHT) icon.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.dark_icon), PorterDuff.Mode.SRC_IN); else icon.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.dark_text), PorterDuff.Mode.SRC_IN); @@ -637,10 +632,10 @@ public abstract class BaseMainActivity extends BaseActivity @Override public void onTabReselected(TabLayout.Tab tab) { - if( tab.getCustomView() != null) { + if (tab.getCustomView() != null) { ImageView icon = tab.getCustomView().findViewById(R.id.tab_icon); - if( icon != null) - if( theme == Helper.THEME_BLACK) + if (icon != null) + if (theme == Helper.THEME_BLACK) icon.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.dark_icon), PorterDuff.Mode.SRC_IN); else icon.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.mastodonC4), PorterDuff.Mode.SRC_IN); @@ -660,49 +655,49 @@ public abstract class BaseMainActivity extends BaseActivity if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } - if( theme == Helper.THEME_LIGHT){ - changeDrawableColor(getApplicationContext(), R.drawable.ic_home,R.color.dark_icon); - changeDrawableColor(getApplicationContext(), R.drawable.ic_notifications,R.color.dark_icon); - changeDrawableColor(getApplicationContext(), R.drawable.ic_direct_messages,R.color.dark_icon); - changeDrawableColor(getApplicationContext(), R.drawable.ic_people,R.color.dark_icon); - changeDrawableColor(getApplicationContext(), R.drawable.ic_public,R.color.dark_icon); - changeDrawableColor(getApplicationContext(), R.drawable.ic_color_lens,R.color.dark_icon); + if (theme == Helper.THEME_LIGHT) { + changeDrawableColor(getApplicationContext(), R.drawable.ic_home, R.color.dark_icon); + changeDrawableColor(getApplicationContext(), R.drawable.ic_notifications, R.color.dark_icon); + changeDrawableColor(getApplicationContext(), R.drawable.ic_direct_messages, R.color.dark_icon); + changeDrawableColor(getApplicationContext(), R.drawable.ic_people, R.color.dark_icon); + changeDrawableColor(getApplicationContext(), R.drawable.ic_public, R.color.dark_icon); + changeDrawableColor(getApplicationContext(), R.drawable.ic_color_lens, R.color.dark_icon); - changeDrawableColor(getApplicationContext(), R.drawable.ic_subscriptions,R.color.dark_icon); - changeDrawableColor(getApplicationContext(), R.drawable.ic_overview,R.color.dark_icon); - changeDrawableColor(getApplicationContext(), R.drawable.ic_trending_up,R.color.dark_icon); - changeDrawableColor(getApplicationContext(), R.drawable.ic_recently_added,R.color.dark_icon); + changeDrawableColor(getApplicationContext(), R.drawable.ic_subscriptions, R.color.dark_icon); + changeDrawableColor(getApplicationContext(), R.drawable.ic_overview, R.color.dark_icon); + changeDrawableColor(getApplicationContext(), R.drawable.ic_trending_up, R.color.dark_icon); + changeDrawableColor(getApplicationContext(), R.drawable.ic_recently_added, R.color.dark_icon); - }else { - changeDrawableColor(getApplicationContext(), R.drawable.ic_home,R.color.dark_text); - changeDrawableColor(getApplicationContext(), R.drawable.ic_notifications,R.color.dark_text); - changeDrawableColor(getApplicationContext(), R.drawable.ic_direct_messages,R.color.dark_text); - changeDrawableColor(getApplicationContext(), R.drawable.ic_people,R.color.dark_text); - changeDrawableColor(getApplicationContext(), R.drawable.ic_public,R.color.dark_text); - changeDrawableColor(getApplicationContext(), R.drawable.ic_color_lens,R.color.dark_text); + } else { + changeDrawableColor(getApplicationContext(), R.drawable.ic_home, R.color.dark_text); + changeDrawableColor(getApplicationContext(), R.drawable.ic_notifications, R.color.dark_text); + changeDrawableColor(getApplicationContext(), R.drawable.ic_direct_messages, R.color.dark_text); + changeDrawableColor(getApplicationContext(), R.drawable.ic_people, R.color.dark_text); + changeDrawableColor(getApplicationContext(), R.drawable.ic_public, R.color.dark_text); + changeDrawableColor(getApplicationContext(), R.drawable.ic_color_lens, R.color.dark_text); - changeDrawableColor(getApplicationContext(), R.drawable.ic_subscriptions,R.color.dark_text); - changeDrawableColor(getApplicationContext(), R.drawable.ic_overview,R.color.dark_text); - changeDrawableColor(getApplicationContext(), R.drawable.ic_trending_up,R.color.dark_text); - changeDrawableColor(getApplicationContext(), R.drawable.ic_recently_added,R.color.dark_text); + changeDrawableColor(getApplicationContext(), R.drawable.ic_subscriptions, R.color.dark_text); + changeDrawableColor(getApplicationContext(), R.drawable.ic_overview, R.color.dark_text); + changeDrawableColor(getApplicationContext(), R.drawable.ic_trending_up, R.color.dark_text); + changeDrawableColor(getApplicationContext(), R.drawable.ic_recently_added, R.color.dark_text); } boolean live_notification = sharedpreferences.getBoolean(Helper.SET_LIVE_NOTIFICATIONS, true); - if( live_notification && (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA)) + if (live_notification && (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA)) startSreaming(); - if( hidde_menu != null) + if (hidde_menu != null) LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(hidde_menu); - if( update_topbar != null) + if (update_topbar != null) LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(update_topbar); hidde_menu = new BroadcastReceiver() { @Override @@ -710,36 +705,36 @@ public abstract class BaseMainActivity extends BaseActivity Bundle b = intent.getExtras(); assert b != null; String menu = b.getString("menu"); - if( menu != null){ - if( menu.equals("hide_admin")){ + if (menu != null) { + if (menu.equals("hide_admin")) { NavigationView navigationView = findViewById(R.id.nav_view); MenuItem admin = navigationView.getMenu().findItem(R.id.nav_administration); - if( admin != null){ + if (admin != null) { admin.setVisible(false); } - }else if(menu.equals("show_admin")){ + } else if (menu.equals("show_admin")) { NavigationView navigationView = findViewById(R.id.nav_view); MenuItem admin = navigationView.getMenu().findItem(R.id.nav_administration); - if( admin != null){ + if (admin != null) { admin.setVisible(true); } - }else if(menu.equals("hide_news")){ + } else if (menu.equals("hide_news")) { NavigationView navigationView = findViewById(R.id.nav_view); MenuItem news = navigationView.getMenu().findItem(R.id.nav_news); - if( news != null){ + if (news != null) { news.setVisible(false); } - }else if(menu.equals("show_news")){ + } else if (menu.equals("show_news")) { NavigationView navigationView = findViewById(R.id.nav_view); MenuItem news = navigationView.getMenu().findItem(R.id.nav_news); - if( news != null){ + if (news != null) { news.setVisible(true); } - }else if(menu.equals("show_list_button")){ + } else if (menu.equals("show_list_button")) { displayTimelineMoreButton(true); - }else if(menu.equals("hide_list_button")){ + } else if (menu.equals("hide_list_button")) { displayTimelineMoreButton(false); - }else if(menu.equals("theme")){ + } else if (menu.equals("theme")) { recreate(); } } @@ -750,7 +745,7 @@ public abstract class BaseMainActivity extends BaseActivity @Override public void onReceive(Context context, Intent intent) { int position = 0; - if( tabLayout != null) + if (tabLayout != null) position = tabLayout.getSelectedTabPosition(); new SyncTimelinesAsyncTask(BaseMainActivity.this, position, BaseMainActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } @@ -767,16 +762,16 @@ public abstract class BaseMainActivity extends BaseActivity imm.hideSoftInputFromWindow(toolbar_search.getWindowToken(), 0); String peertube = null; - query= query.replaceAll("^#+", ""); + query = query.replaceAll("^#+", ""); //It's not a peertube search //Peertube search - if(tabLayout != null && timelines != null && (timelines.get(tabLayout.getSelectedTabPosition()).getType() == ManageTimelines.Type.PEERTUBE || (timelines.get(tabLayout.getSelectedTabPosition()).getRemoteInstance() != null && timelines.get(tabLayout.getSelectedTabPosition()).getRemoteInstance().getType().equals("PEERTUBE")))){ + if (tabLayout != null && timelines != null && (timelines.get(tabLayout.getSelectedTabPosition()).getType() == ManageTimelines.Type.PEERTUBE || (timelines.get(tabLayout.getSelectedTabPosition()).getRemoteInstance() != null && timelines.get(tabLayout.getSelectedTabPosition()).getRemoteInstance().getType().equals("PEERTUBE")))) { DisplayStatusFragment statusFragment; Bundle bundle = new Bundle(); statusFragment = new DisplayStatusFragment(); bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE); String instance = "peertube.fedilab.app"; - if(timelines.get(tabLayout.getSelectedTabPosition()).getRemoteInstance() != null && timelines.get(tabLayout.getSelectedTabPosition()).getRemoteInstance().getType().equals("PEERTUBE")) + if (timelines.get(tabLayout.getSelectedTabPosition()).getRemoteInstance() != null && timelines.get(tabLayout.getSelectedTabPosition()).getRemoteInstance().getType().equals("PEERTUBE")) instance = timelines.get(tabLayout.getSelectedTabPosition()).getRemoteInstance().getHost(); bundle.putString("remote_instance", instance); bundle.putString("instanceType", "PEERTUBE"); @@ -786,7 +781,7 @@ public abstract class BaseMainActivity extends BaseActivity FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.main_app_container, statusFragment, fragmentTag).commit(); - if( main_app_container.getVisibility() == View.GONE){ + if (main_app_container.getVisibility() == View.GONE) { main_app_container.setVisibility(View.VISIBLE); toolbarTitle.setVisibility(View.VISIBLE); @@ -795,7 +790,7 @@ public abstract class BaseMainActivity extends BaseActivity manageTimelineList(false); tabLayout.setVisibility(View.GONE); } - }else if ( social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { + } else if (social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { DisplayStatusFragment statusFragment; Bundle bundle = new Bundle(); statusFragment = new DisplayStatusFragment(); @@ -808,7 +803,7 @@ public abstract class BaseMainActivity extends BaseActivity FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.main_app_container, statusFragment, fragmentTag).commit(); - if( main_app_container.getVisibility() == View.GONE){ + if (main_app_container.getVisibility() == View.GONE) { main_app_container.setVisibility(View.VISIBLE); toolbarTitle.setVisibility(View.VISIBLE); @@ -817,24 +812,24 @@ public abstract class BaseMainActivity extends BaseActivity manageTimelineList(false); tabLayout.setVisibility(View.GONE); } - }else{ - if( social != UpdateAccountInfoAsyncTask.SOCIAL.GNU) { + } else { + if (social != UpdateAccountInfoAsyncTask.SOCIAL.GNU) { boolean isAccount = false; - if( query.split("@").length > 1 ){ + if (query.split("@").length > 1) { isAccount = true; } - if( (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) - && !query.contains("http://") && !query.contains("https://") && !isAccount){ + if ((social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) + && !query.contains("http://") && !query.contains("https://") && !isAccount) { Intent intent = new Intent(BaseMainActivity.this, SearchResultTabActivity.class); intent.putExtra("search", query); startActivity(intent); - }else{ + } else { Intent intent = new Intent(BaseMainActivity.this, SearchResultActivity.class); intent.putExtra("search", query); startActivity(intent); } - }else{ + } else { Intent intent = new Intent(BaseMainActivity.this, HashTagActivity.class); Bundle b = new Bundle(); b.putString("tag", query.trim()); @@ -844,14 +839,14 @@ public abstract class BaseMainActivity extends BaseActivity } toolbar_search.setQuery("", false); toolbar_search.setIconified(true); - if( main_app_container.getVisibility() == View.VISIBLE){ + if (main_app_container.getVisibility() == View.VISIBLE) { main_app_container.setVisibility(View.VISIBLE); viewPager.setVisibility(View.GONE); manageTimelineList(false); delete_instance.setVisibility(View.GONE); tabLayout.setVisibility(View.GONE); toolbarTitle.setVisibility(View.VISIBLE); - }else { + } else { main_app_container.setVisibility(View.GONE); viewPager.setVisibility(View.VISIBLE); manageTimelineList(true); @@ -861,6 +856,7 @@ public abstract class BaseMainActivity extends BaseActivity } return false; } + @Override public boolean onQueryTextChange(String newText) { return false; @@ -872,13 +868,13 @@ public abstract class BaseMainActivity extends BaseActivity toolbar_search.setOnCloseListener(new SearchView.OnCloseListener() { @Override public boolean onClose() { - if( main_app_container.getVisibility() == View.VISIBLE){ + if (main_app_container.getVisibility() == View.VISIBLE) { main_app_container.setVisibility(View.VISIBLE); viewPager.setVisibility(View.GONE); manageTimelineList(false); tabLayout.setVisibility(View.GONE); toolbarTitle.setVisibility(View.VISIBLE); - }else { + } else { main_app_container.setVisibility(View.GONE); viewPager.setVisibility(View.VISIBLE); manageTimelineList(true); @@ -893,21 +889,21 @@ public abstract class BaseMainActivity extends BaseActivity toolbar_search.setOnSearchClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - if( toolbar_search.isIconified()){ - if( main_app_container.getVisibility() == View.VISIBLE){ + if (toolbar_search.isIconified()) { + if (main_app_container.getVisibility() == View.VISIBLE) { main_app_container.setVisibility(View.VISIBLE); viewPager.setVisibility(View.GONE); manageTimelineList(false); tabLayout.setVisibility(View.GONE); toolbarTitle.setVisibility(View.VISIBLE); - }else { + } else { main_app_container.setVisibility(View.GONE); viewPager.setVisibility(View.VISIBLE); manageTimelineList(true); tabLayout.setVisibility(View.VISIBLE); toolbarTitle.setVisibility(View.GONE); } - }else { + } else { toolbarTitle.setVisibility(View.GONE); tabLayout.setVisibility(View.GONE); manageTimelineList(false); @@ -917,7 +913,7 @@ public abstract class BaseMainActivity extends BaseActivity }); //Hide the default title - if( getSupportActionBar() != null) { + if (getSupportActionBar() != null) { getSupportActionBar().setDisplayShowTitleEnabled(false); getSupportActionBar().getThemedContext().setTheme(R.style.AppThemeBlack); } @@ -930,7 +926,7 @@ public abstract class BaseMainActivity extends BaseActivity } tabLayout.getTabAt(0).select(); */ - if( social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { toot.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { @@ -945,7 +941,7 @@ public abstract class BaseMainActivity extends BaseActivity return false; } }); - }else if(social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE){ + } else if (social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { toot.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { @@ -968,7 +964,7 @@ public abstract class BaseMainActivity extends BaseActivity drawer.openDrawer(GravityCompat.START); } }); - Helper.loadPictureIcon(BaseMainActivity.this, account,iconbar); + Helper.loadPictureIcon(BaseMainActivity.this, account, iconbar); headerLayout = navigationView.getHeaderView(0); final ImageView menuMore = headerLayout.findViewById(R.id.header_option_menu); @@ -979,18 +975,18 @@ public abstract class BaseMainActivity extends BaseActivity popup.getMenuInflater() .inflate(R.menu.main, popup.getMenu()); - if( social != UpdateAccountInfoAsyncTask.SOCIAL.MASTODON){ + if (social != UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { MenuItem action_about_instance = popup.getMenu().findItem(R.id.action_about_instance); - if( action_about_instance != null) + if (action_about_instance != null) action_about_instance.setVisible(false); MenuItem action_export = popup.getMenu().findItem(R.id.action_export); - if( action_export != null) + if (action_export != null) action_export.setVisible(false); MenuItem action_send_invitation = popup.getMenu().findItem(R.id.action_send_invitation); - if( action_send_invitation != null) + if (action_send_invitation != null) action_send_invitation.setVisible(false); } - if( social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { + if (social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { MenuItem action_size = popup.getMenu().findItem(R.id.action_size); if (action_size != null) action_size.setVisible(false); @@ -1017,8 +1013,8 @@ public abstract class BaseMainActivity extends BaseActivity startActivity(intent); return true; case R.id.action_send_invitation: - if( instanceClass != null){ - if(instanceClass.isRegistration()){ + if (instanceClass != null) { + if (instanceClass.isRegistration()) { Intent sendIntent = new Intent(Intent.ACTION_SEND); String extra_text = getString(R.string.join_instance, Helper.getLiveInstance(getApplicationContext()), "https://f-droid.org/en/packages/fr.gouv.etalab.mastodon/", @@ -1027,7 +1023,7 @@ public abstract class BaseMainActivity extends BaseActivity sendIntent.putExtra(Intent.EXTRA_TEXT, extra_text); sendIntent.setType("text/plain"); startActivity(Intent.createChooser(sendIntent, getString(R.string.share_with))); - }else{ + } else { Toasty.info(getApplicationContext(), getString(R.string.registration_closed), Toast.LENGTH_SHORT).show(); } } @@ -1037,38 +1033,42 @@ public abstract class BaseMainActivity extends BaseActivity return true; case R.id.action_size: final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); - int textSize = sharedpreferences.getInt(Helper.SET_TEXT_SIZE,110); - int iconSize = sharedpreferences.getInt(Helper.SET_ICON_SIZE,130); + int textSize = sharedpreferences.getInt(Helper.SET_TEXT_SIZE, 110); + int iconSize = sharedpreferences.getInt(Helper.SET_ICON_SIZE, 130); AlertDialog.Builder builder = new AlertDialog.Builder(BaseMainActivity.this, style); builder.setTitle(R.string.text_size); - View popup_quick_settings = getLayoutInflater().inflate( R.layout.popup_text_size, new LinearLayout(getApplicationContext()), false ); + View popup_quick_settings = getLayoutInflater().inflate(R.layout.popup_text_size, new LinearLayout(getApplicationContext()), false); builder.setView(popup_quick_settings); SeekBar set_text_size = popup_quick_settings.findViewById(R.id.set_text_size); SeekBar set_icon_size = popup_quick_settings.findViewById(R.id.set_icon_size); final TextView set_text_size_value = popup_quick_settings.findViewById(R.id.set_text_size_value); final TextView set_icon_size_value = popup_quick_settings.findViewById(R.id.set_icon_size_value); - set_text_size_value.setText(String.format("%s%%",String.valueOf(textSize))); - set_icon_size_value.setText(String.format("%s%%",String.valueOf(iconSize))); + set_text_size_value.setText(String.format("%s%%", String.valueOf(textSize))); + set_icon_size_value.setText(String.format("%s%%", String.valueOf(iconSize))); set_text_size.setMax(20); set_icon_size.setMax(20); - set_text_size.setProgress(((textSize-80)/5)); - set_icon_size.setProgress(((iconSize-80)/5)); + set_text_size.setProgress(((textSize - 80) / 5)); + set_icon_size.setProgress(((iconSize - 80) / 5)); set_text_size.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override - public void onStopTrackingTouch(SeekBar seekBar) {} + public void onStopTrackingTouch(SeekBar seekBar) { + } + @Override - public void onStartTrackingTouch(SeekBar seekBar) {} + public void onStartTrackingTouch(SeekBar seekBar) { + } + @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - int value = 80 + progress*5; - set_text_size_value.setText(String.format("%s%%",String.valueOf(value))); + int value = 80 + progress * 5; + set_text_size_value.setText(String.format("%s%%", String.valueOf(value))); SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putInt(Helper.SET_TEXT_SIZE, value); editor.apply(); @@ -1076,13 +1076,17 @@ public abstract class BaseMainActivity extends BaseActivity }); set_icon_size.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override - public void onStopTrackingTouch(SeekBar seekBar) {} + public void onStopTrackingTouch(SeekBar seekBar) { + } + @Override - public void onStartTrackingTouch(SeekBar seekBar) {} + public void onStartTrackingTouch(SeekBar seekBar) { + } + @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - int value = 80 + progress*5; - set_icon_size_value.setText(String.format("%s%%",String.valueOf(value))); + int value = 80 + progress * 5; + set_icon_size_value.setText(String.format("%s%%", String.valueOf(value))); SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putInt(Helper.SET_ICON_SIZE, value); editor.apply(); @@ -1102,14 +1106,14 @@ public abstract class BaseMainActivity extends BaseActivity startActivity(intent); return true; case R.id.action_export: - if(Build.VERSION.SDK_INT >= 23 ){ - if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ) { + if (Build.VERSION.SDK_INT >= 23) { + if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(BaseMainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, Helper.EXTERNAL_STORAGE_REQUEST_CODE); } else { Intent backupIntent = new Intent(BaseMainActivity.this, BackupStatusService.class); startService(backupIntent); } - }else{ + } else { Intent backupIntent = new Intent(BaseMainActivity.this, BackupStatusService.class); startService(backupIntent); } @@ -1132,17 +1136,17 @@ public abstract class BaseMainActivity extends BaseActivity String[] mimetypes = {"*/*"}; intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes); startActivityForResult(intent, PICK_IMPORT); - }else { + } else { intent.setType("*/*"); Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); Intent chooserIntent = Intent.createChooser(intent, getString(R.string.toot_select_import)); - chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent}); + chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{pickIntent}); startActivityForResult(chooserIntent, PICK_IMPORT); } return true; case R.id.action_export_data: - if(Build.VERSION.SDK_INT >= 23 ){ - if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ) { + if (Build.VERSION.SDK_INT >= 23) { + if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(BaseMainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, Helper.EXTERNAL_STORAGE_REQUEST_CODE); return true; } @@ -1165,7 +1169,7 @@ public abstract class BaseMainActivity extends BaseActivity startActivity(intent); } }); - if( social != UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) + if (social != UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) optionInfo.setVisibility(View.GONE); MenuFloating.tags = new ArrayList<>(); Helper.updateHeaderAccountInfo(activity, account, headerLayout); @@ -1178,29 +1182,29 @@ public abstract class BaseMainActivity extends BaseActivity if (!BuildConfig.DONATIONS) { MenuItem openCollectiveItem = navigationView.getMenu().findItem(R.id.nav_opencollective); - if( openCollectiveItem != null){ + if (openCollectiveItem != null) { openCollectiveItem.setVisible(false); } MenuItem partnerShipItem = navigationView.getMenu().findItem(R.id.nav_partnership); - if( partnerShipItem != null){ + if (partnerShipItem != null) { partnerShipItem.setVisible(false); } } - if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.MASTODON && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA){ + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.MASTODON && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { MenuItem adminItem = navigationView.getMenu().findItem(R.id.nav_administration); - if( adminItem != null){ + if (adminItem != null) { adminItem.setVisible(false); } MenuItem notificationArchive = navigationView.getMenu().findItem(R.id.nav_archive_notifications); - if( notificationArchive != null){ + if (notificationArchive != null) { notificationArchive.setVisible(false); } - }else{ + } else { boolean display_admin_menu = sharedpreferences.getBoolean(Helper.SET_DISPLAY_ADMIN_MENU + userId + instance, false); - if( !display_admin_menu){ + if (!display_admin_menu) { MenuItem adminItem = navigationView.getMenu().findItem(R.id.nav_administration); - if( adminItem != null){ + if (adminItem != null) { adminItem.setVisible(false); } } @@ -1210,13 +1214,13 @@ public abstract class BaseMainActivity extends BaseActivity @Override public void onClick(View v) { Helper.menuAccounts(BaseMainActivity.this); - if( main_app_container.getVisibility() == View.VISIBLE){ + if (main_app_container.getVisibility() == View.VISIBLE) { main_app_container.setVisibility(View.VISIBLE); viewPager.setVisibility(View.GONE); manageTimelineList(false); tabLayout.setVisibility(View.GONE); toolbarTitle.setVisibility(View.VISIBLE); - }else { + } else { main_app_container.setVisibility(View.GONE); viewPager.setVisibility(View.VISIBLE); manageTimelineList(true); @@ -1228,11 +1232,9 @@ public abstract class BaseMainActivity extends BaseActivity }); - - // Asked once for notification opt-in boolean popupShown = sharedpreferences.getBoolean(Helper.SET_POPUP_PUSH, false); - if( !popupShown && (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA)){ + if (!popupShown && (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA)) { AlertDialog.Builder dialogBuilderOptin = new AlertDialog.Builder(BaseMainActivity.this, style); LayoutInflater inflater = getLayoutInflater(); View dialogView = inflater.inflate(R.layout.popup_quick_settings, new LinearLayout(getApplicationContext()), false); @@ -1244,7 +1246,7 @@ public abstract class BaseMainActivity extends BaseActivity boolean notif_add = sharedpreferences.getBoolean(Helper.SET_NOTIF_ADD, true); boolean notif_mention = sharedpreferences.getBoolean(Helper.SET_NOTIF_MENTION, true); boolean notif_share = sharedpreferences.getBoolean(Helper.SET_NOTIF_SHARE, true); - boolean notifif_notifications = !( !notif_follow && !notif_add && !notif_mention && !notif_share); + boolean notifif_notifications = !(!notif_follow && !notif_add && !notif_mention && !notif_share); //set_push_hometimeline.setChecked(notif_hometimeline); set_push_notification.setChecked(notifif_notifications); @@ -1275,21 +1277,22 @@ public abstract class BaseMainActivity extends BaseActivity }); try { dialogBuilderOptin.show(); - }catch (Exception ignored){}; + } catch (Exception ignored) { + } + ; } Helper.switchLayout(BaseMainActivity.this); - mamageNewIntent(getIntent()); - if( social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { // Retrieves instance new RetrieveInstanceAsyncTask(getApplicationContext(), BaseMainActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); // Retrieves filters - if( social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { + if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { new ManageFiltersAsyncTask(getApplicationContext(), GET_ALL_FILTER, null, BaseMainActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } @@ -1298,7 +1301,7 @@ public abstract class BaseMainActivity extends BaseActivity AsyncTask.execute(new Runnable() { @Override public void run() { - Date date = new Date( System.currentTimeMillis() - TimeUnit.DAYS.toMillis(10)); + Date date = new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(10)); String dateString = Helper.dateToString(date); new TimelineCacheDAO(BaseMainActivity.this, db).removeAfterDate(dateString); } @@ -1308,15 +1311,15 @@ public abstract class BaseMainActivity extends BaseActivity } - private void manageTimelineList(boolean displayed){ + private void manageTimelineList(boolean displayed) { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); boolean display_timeline_in_list = sharedpreferences.getBoolean(Helper.SET_DISPLAY_TIMELINE_IN_LIST, false); - if( !display_timeline_in_list){ + if (!display_timeline_in_list) { display_timeline.setVisibility(View.GONE); - }else{ - if( displayed){ + } else { + if (displayed) { display_timeline.setVisibility(View.VISIBLE); - }else{ + } else { display_timeline.setVisibility(View.GONE); } } @@ -1333,50 +1336,50 @@ public abstract class BaseMainActivity extends BaseActivity /** * Manages new intents + * * @param intent Intent - intent related to a notification in top bar */ - private void mamageNewIntent(Intent intent){ + private void mamageNewIntent(Intent intent) { - if( intent == null ) + if (intent == null) return; String action = intent.getAction(); String type = intent.getType(); Bundle extras = intent.getExtras(); String userIdIntent, instanceIntent; - if( extras != null && extras.containsKey(Helper.INTENT_ACTION) ){ + if (extras != null && extras.containsKey(Helper.INTENT_ACTION)) { final NavigationView navigationView = findViewById(R.id.nav_view); userIdIntent = extras.getString(Helper.PREF_KEY_ID); //Id of the account in the intent instanceIntent = extras.getString(Helper.PREF_INSTANCE); - if (extras.getInt(Helper.INTENT_ACTION) == Helper.NOTIFICATION_INTENT){ - Helper.changeUser(BaseMainActivity.this, userIdIntent, instanceIntent,true); //Connects the account which is related to the notification + if (extras.getInt(Helper.INTENT_ACTION) == Helper.NOTIFICATION_INTENT) { + Helper.changeUser(BaseMainActivity.this, userIdIntent, instanceIntent, true); //Connects the account which is related to the notification Helper.unCheckAllMenuItems(navigationView); notificationChecked = true; - if( extras.getString(Helper.INTENT_TARGETED_ACCOUNT) != null ){ + if (extras.getString(Helper.INTENT_TARGETED_ACCOUNT) != null) { Intent intentShow = new Intent(BaseMainActivity.this, ShowAccountActivity.class); Bundle b = new Bundle(); b.putString("accountId", extras.getString(Helper.INTENT_TARGETED_ACCOUNT)); intentShow.putExtras(b); startActivity(intentShow); } - }else if( extras.getInt(Helper.INTENT_ACTION) == Helper.RELOAD_MYVIDEOS){ + } else if (extras.getInt(Helper.INTENT_ACTION) == Helper.RELOAD_MYVIDEOS) { Bundle bundle = new Bundle(); DisplayStatusFragment fragment = new DisplayStatusFragment(); bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.MYVIDEOS); - bundle.putString("instanceType","PEERTUBE"); + bundle.putString("instanceType", "PEERTUBE"); SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(getApplicationContext())); Account account = new AccountDAO(getApplicationContext(), db).getUniqAccount(userId, instance); - bundle.putString("targetedid",account.getUsername()); + bundle.putString("targetedid", account.getUsername()); bundle.putBoolean("ownvideos", true); fragment.setArguments(bundle); String fragmentTag = "MY_VIDEOS"; FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.main_app_container, fragment, fragmentTag).commit(); - } - else if( extras.getInt(Helper.INTENT_ACTION) == Helper.SEARCH_INSTANCE){ + } else if (extras.getInt(Helper.INTENT_ACTION) == Helper.SEARCH_INSTANCE) { String instance = extras.getString(Helper.INSTANCE_NAME); DisplayStatusFragment statusFragment; Bundle bundle = new Bundle(); @@ -1395,34 +1398,33 @@ public abstract class BaseMainActivity extends BaseActivity manageTimelineList(false); tabLayout.setVisibility(View.GONE); toolbarTitle.setText(instance); - }else if( extras.getInt(Helper.INTENT_ACTION) == Helper.HOME_TIMELINE_INTENT){ - Helper.changeUser(BaseMainActivity.this, userIdIntent, instanceIntent,false); //Connects the account which is related to the notification - }else if( extras.getInt(Helper.INTENT_ACTION) == Helper.BACK_TO_SETTINGS){ + } else if (extras.getInt(Helper.INTENT_ACTION) == Helper.HOME_TIMELINE_INTENT) { + Helper.changeUser(BaseMainActivity.this, userIdIntent, instanceIntent, false); //Connects the account which is related to the notification + } else if (extras.getInt(Helper.INTENT_ACTION) == Helper.BACK_TO_SETTINGS) { Helper.unCheckAllMenuItems(navigationView); navigationView.setCheckedItem(R.id.nav_settings); navigationView.getMenu().performIdentifierAction(R.id.nav_settings, 0); toolbarTitle.setText(R.string.settings); - }else if( extras.getInt(Helper.INTENT_ACTION) == Helper.BACK_TO_SETTINGS){ + } else if (extras.getInt(Helper.INTENT_ACTION) == Helper.BACK_TO_SETTINGS) { Helper.unCheckAllMenuItems(navigationView); navigationView.setCheckedItem(R.id.nav_peertube_settings); navigationView.getMenu().performIdentifierAction(R.id.nav_peertube_settings, 0); toolbarTitle.setText(R.string.settings); - }else if (extras.getInt(Helper.INTENT_ACTION) == Helper.ADD_USER_INTENT){ + } else if (extras.getInt(Helper.INTENT_ACTION) == Helper.ADD_USER_INTENT) { this.recreate(); - }else if( extras.getInt(Helper.INTENT_ACTION) == Helper.BACKUP_INTENT){ + } else if (extras.getInt(Helper.INTENT_ACTION) == Helper.BACKUP_INTENT) { Intent myIntent = new Intent(BaseMainActivity.this, OwnerStatusActivity.class); startActivity(myIntent); - }else if( extras.getInt(Helper.INTENT_ACTION) == Helper.BACKUP_NOTIFICATION_INTENT){ + } else if (extras.getInt(Helper.INTENT_ACTION) == Helper.BACKUP_NOTIFICATION_INTENT) { Intent myIntent = new Intent(BaseMainActivity.this, OwnerNotificationActivity.class); startActivity(myIntent); - }else if( extras.getInt(Helper.INTENT_ACTION) == Helper.REDRAW_MENU){ + } else if (extras.getInt(Helper.INTENT_ACTION) == Helper.REDRAW_MENU) { Helper.hideMenuItem(BaseMainActivity.this, navigationView.getMenu()); - } - else if( extras.getInt(Helper.INTENT_ACTION) == Helper.SEARCH_TAG){ + } else if (extras.getInt(Helper.INTENT_ACTION) == Helper.SEARCH_TAG) { new SyncTimelinesAsyncTask(BaseMainActivity.this, -1, BaseMainActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } else if( extras.getInt(Helper.INTENT_ACTION) == Helper.REFRESH_TIMELINE){ + } else if (extras.getInt(Helper.INTENT_ACTION) == Helper.REFRESH_TIMELINE) { int position = 0; - if( tabLayout != null) + if (tabLayout != null) position = tabLayout.getSelectedTabPosition(); new SyncTimelinesAsyncTask(BaseMainActivity.this, position, BaseMainActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else if (extras.getInt(Helper.INTENT_ACTION) == Helper.SEARCH_REMOTE) { @@ -1431,7 +1433,7 @@ public abstract class BaseMainActivity extends BaseActivity intent.setAction(""); intent.setData(null); intent.setFlags(0); - if( url == null) + if (url == null) return; Matcher matcher; if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) @@ -1439,15 +1441,15 @@ public abstract class BaseMainActivity extends BaseActivity else matcher = Helper.urlPattern.matcher(url); boolean isUrl = false; - while (matcher.find()){ + while (matcher.find()) { isUrl = true; } - if(!isUrl) + if (!isUrl) return; //Here we know that the intent contains a valid URL new RetrieveRemoteDataAsyncTask(BaseMainActivity.this, url, BaseMainActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } - }else if( Intent.ACTION_SEND.equals(action) && type != null ) { + } else if (Intent.ACTION_SEND.equals(action) && type != null) { if ("text/plain".equals(type)) { String url = null; String sharedSubject = intent.getStringExtra(Intent.EXTRA_SUBJECT); @@ -1464,18 +1466,18 @@ public abstract class BaseMainActivity extends BaseActivity matcher = Patterns.WEB_URL.matcher(sharedText); else matcher = Helper.urlPattern.matcher(sharedText); - while (matcher.find()){ + while (matcher.find()) { int matchStart = matcher.start(1); int matchEnd = matcher.end(); - if(matchStart < matchEnd && sharedText.length() >= matchEnd) + if (matchStart < matchEnd && sharedText.length() >= matchEnd) url = sharedText.substring(matchStart, matchEnd); } - new RetrieveMetaDataAsyncTask(BaseMainActivity.this, shouldRetrieveMetaData, sharedSubject, sharedText, url,BaseMainActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new RetrieveMetaDataAsyncTask(BaseMainActivity.this, shouldRetrieveMetaData, sharedSubject, sharedText, url, BaseMainActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } else if (type.startsWith("image/") || type.startsWith("video/")) { - if( !TootActivity.active){ + if (!TootActivity.active) { Uri imageUri = intent.getParcelableExtra(Intent.EXTRA_STREAM); if (imageUri != null) { Bundle b = new Bundle(); @@ -1483,19 +1485,19 @@ public abstract class BaseMainActivity extends BaseActivity b.putInt("uriNumberMast", 1); CrossActions.doCrossShare(BaseMainActivity.this, b); } - }else{ + } else { Uri imageUri = intent.getParcelableExtra(Intent.EXTRA_STREAM); if (imageUri != null) { intent = new Intent(getApplicationContext(), TootActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); - intent .putExtra("imageUri", imageUri.toString()); - startActivity(intent ); + intent.putExtra("imageUri", imageUri.toString()); + startActivity(intent); } } } - } else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null ) { - if (type.startsWith("image/") || type.startsWith("video/")) { + } else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) { + if (type.startsWith("image/") || type.startsWith("video/")) { ArrayList imageList = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); if (imageList != null) { @@ -1505,10 +1507,10 @@ public abstract class BaseMainActivity extends BaseActivity CrossActions.doCrossShare(BaseMainActivity.this, b); } } - }else if (Intent.ACTION_VIEW.equals(action)) { + } else if (Intent.ACTION_VIEW.equals(action)) { String url = intent.getDataString(); - if( url == null) { + if (url == null) { intent.replaceExtras(new Bundle()); intent.setAction(""); intent.setData(null); @@ -1521,10 +1523,10 @@ public abstract class BaseMainActivity extends BaseActivity else matcher = Helper.urlPattern.matcher(url); boolean isUrl = false; - while (matcher.find()){ + while (matcher.find()) { isUrl = true; } - if(!isUrl) { + if (!isUrl) { intent.replaceExtras(new Bundle()); intent.setAction(""); intent.setData(null); @@ -1532,9 +1534,9 @@ public abstract class BaseMainActivity extends BaseActivity return; } //Here we know that the intent contains a valid URL - if( !url.contains("medium.com")) { + if (!url.contains("medium.com")) { new RetrieveRemoteDataAsyncTask(BaseMainActivity.this, url, BaseMainActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else{ + } else { forwardToBrowser(intent); } } @@ -1555,15 +1557,15 @@ public abstract class BaseMainActivity extends BaseActivity String packageName = currentInfo.activityInfo.packageName; if (!thisPackageName.equals(packageName)) { Intent targetIntent = new Intent(android.content.Intent.ACTION_VIEW); - targetIntent.setDataAndType(intent.getData(),intent.getType()); + targetIntent.setDataAndType(intent.getData(), intent.getType()); targetIntent.setPackage(intent.getPackage()); targetIntent.setComponent(new ComponentName(packageName, currentInfo.activityInfo.name)); targetIntents.add(targetIntent); } } - if(targetIntents.size() > 0) { + if (targetIntents.size() > 0) { Intent chooserIntent = Intent.createChooser(targetIntents.remove(0), getString(R.string.open_with)); - chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetIntents.toArray(new Parcelable[] {})); + chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetIntents.toArray(new Parcelable[]{})); startActivity(chooserIntent); } } @@ -1577,11 +1579,11 @@ public abstract class BaseMainActivity extends BaseActivity } else { displayPeertube = null; //Hide search bar on back pressed - if( !toolbar_search.isIconified()){ + if (!toolbar_search.isIconified()) { toolbar_search.setIconified(true); return; } - if( viewPager.getVisibility() == View.VISIBLE){ + if (viewPager.getVisibility() == View.VISIBLE) { super.onBackPressed(); } else { Helper.switchLayout(BaseMainActivity.this); @@ -1604,22 +1606,22 @@ public abstract class BaseMainActivity extends BaseActivity } @Override - public void onResume(){ + public void onResume() { super.onResume(); PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean("isMainActivityRunning", true).apply(); //Proceeds to update of the authenticated account - if(Helper.isLoggedIn(getApplicationContext())) { + if (Helper.isLoggedIn(getApplicationContext())) { new UpdateAccountInfoByIDAsyncTask(getApplicationContext(), social, BaseMainActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); - String datestr = sharedpreferences.getString(Helper.HOME_LAST_READ + userId + instance,null); + String datestr = sharedpreferences.getString(Helper.HOME_LAST_READ + userId + instance, null); - if( timelines != null && timelines.size() > 0 && mPageReferenceMap != null && datestr != null){ + if (timelines != null && timelines.size() > 0 && mPageReferenceMap != null && datestr != null) { Date date = Helper.stringToDate(getApplicationContext(), datestr); - Date dateAllowed = new Date( System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(30)); + Date dateAllowed = new Date(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(30)); //Refresh home if needed - if( dateAllowed.after(date) ) { + if (dateAllowed.after(date)) { for (ManageTimelines tl : timelines) { if (tl.getType() == ManageTimelines.Type.HOME && mPageReferenceMap != null && mPageReferenceMap.containsKey(tl.getPosition())) { DisplayStatusFragment homeTimeline = (DisplayStatusFragment) mPageReferenceMap.get(tl.getPosition()); @@ -1638,7 +1640,7 @@ public abstract class BaseMainActivity extends BaseActivity @Override protected void onPause() { super.onPause(); - if( userId != null && instance != null) { + if (userId != null && instance != null) { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(Helper.HOME_LAST_READ + userId + instance, Helper.dateToString(new Date())); @@ -1648,13 +1650,13 @@ public abstract class BaseMainActivity extends BaseActivity } @Override - public void onDestroy(){ + public void onDestroy() { super.onDestroy(); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); boolean backgroundProcess = sharedpreferences.getBoolean(Helper.SET_KEEP_BACKGROUND_PROCESS, true); boolean clearCacheExit = sharedpreferences.getBoolean(Helper.SET_CLEAR_CACHE_EXIT, false); WeakReference contextReference = new WeakReference<>(getApplicationContext()); - if( clearCacheExit){ + if (clearCacheExit) { AsyncTask.execute(new Runnable() { @Override public void run() { @@ -1673,13 +1675,13 @@ public abstract class BaseMainActivity extends BaseActivity } }); } - if(!backgroundProcess) + if (!backgroundProcess) sendBroadcast(new Intent(getApplicationContext(), StopLiveNotificationReceiver.class)); - if( hidde_menu != null) + if (hidde_menu != null) LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(hidde_menu); - if( update_topbar != null) + if (update_topbar != null) LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(update_topbar); - if( mPageReferenceMap != null) + if (mPageReferenceMap != null) mPageReferenceMap = null; PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean("isMainActivityRunning", false).apply(); } @@ -1689,43 +1691,43 @@ public abstract class BaseMainActivity extends BaseActivity public boolean onNavigationItemSelected(@NonNull MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); - if( id == R.id.nav_archive) { + if (id == R.id.nav_archive) { Intent myIntent = new Intent(BaseMainActivity.this, OwnerStatusActivity.class); startActivity(myIntent); return false; - }else if( id == R.id.nav_archive_notifications) { + } else if (id == R.id.nav_archive_notifications) { Intent myIntent = new Intent(BaseMainActivity.this, OwnerNotificationActivity.class); startActivity(myIntent); return false; - }else if(id == R.id.nav_drag_timelines){ + } else if (id == R.id.nav_drag_timelines) { Intent intent = new Intent(getApplicationContext(), ReorderTimelinesActivity.class); startActivity(intent); return false; - }else if(id == R.id.nav_administration){ + } else if (id == R.id.nav_administration) { Intent intent = new Intent(getApplicationContext(), AdminActivity.class); startActivity(intent); return false; - } else if( id == R.id.nav_about) { + } else if (id == R.id.nav_about) { Intent intent = new Intent(getApplicationContext(), AboutActivity.class); startActivity(intent); return false; - }else if (id == R.id.nav_opencollective) { + } else if (id == R.id.nav_opencollective) { Intent intent = new Intent(getApplicationContext(), OpencollectiveActivity.class); startActivity(intent); return false; - } else if( id == R.id.nav_upload) { + } else if (id == R.id.nav_upload) { Intent intent = new Intent(getApplicationContext(), PeertubeUploadActivity.class); startActivity(intent); return false; - } else if( id == R.id.nav_partnership) { + } else if (id == R.id.nav_partnership) { Intent intent = new Intent(getApplicationContext(), PartnerShipActivity.class); startActivity(intent); return false; - }else if (id == R.id.nav_settings) { + } else if (id == R.id.nav_settings) { Intent intent = new Intent(getApplicationContext(), SettingsActivity.class); startActivity(intent); return false; - } else if(id == R.id.nav_blocked_domains){ + } else if (id == R.id.nav_blocked_domains) { Intent intent = new Intent(getApplicationContext(), MutedInstanceActivity.class); startActivity(intent); return false; @@ -1752,31 +1754,31 @@ public abstract class BaseMainActivity extends BaseActivity toolbarTitle.setVisibility(View.VISIBLE); delete_instance.setVisibility(View.GONE); appBar.setExpanded(true); - if (id != R.id.nav_drafts && id != R.id.nav_bookmarks && id != R.id.nav_peertube ) { + if (id != R.id.nav_drafts && id != R.id.nav_bookmarks && id != R.id.nav_peertube) { delete_all.hide(); - }else{ + } else { delete_all.show(); } - if( id != R.id.nav_list && id != R.id.nav_filters && id != R.id.nav_peertube_playlists && id != R.id.nav_blocked_domains){ + if (id != R.id.nav_list && id != R.id.nav_filters && id != R.id.nav_peertube_playlists && id != R.id.nav_blocked_domains) { add_new.hide(); - }else{ + } else { add_new.show(); } if (id == R.id.nav_peertube_settings) { toot.hide(); - SettingsPeertubeFragment settingsPeertubeFragment= new SettingsPeertubeFragment(); + SettingsPeertubeFragment settingsPeertubeFragment = new SettingsPeertubeFragment(); fragmentTag = "TABLAYOUT_PEERTUBE_SETTINGS"; fragmentManager.beginTransaction() .replace(R.id.main_app_container, settingsPeertubeFragment, fragmentTag).commit(); - }else if (id == R.id.nav_peertube_notifications) { + } else if (id == R.id.nav_peertube_notifications) { toot.hide(); - DisplayPeertubeNotificationsFragment displayPeertubeNotificationsFragment= new DisplayPeertubeNotificationsFragment(); + DisplayPeertubeNotificationsFragment displayPeertubeNotificationsFragment = new DisplayPeertubeNotificationsFragment(); fragmentTag = "PEERTUBE_NOTIFICATIONS"; fragmentManager.beginTransaction() .replace(R.id.main_app_container, displayPeertubeNotificationsFragment, fragmentTag).commit(); - }else if (id == R.id.nav_favorites || id == R.id.nav_pixelfed_favorites) { + } else if (id == R.id.nav_favorites || id == R.id.nav_pixelfed_favorites) { toot.hide(); statusFragment = new DisplayStatusFragment(); bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.FAVOURITES); @@ -1788,13 +1790,13 @@ public abstract class BaseMainActivity extends BaseActivity bundle = new Bundle(); DisplayStatusFragment fragment = new DisplayStatusFragment(); bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.MYVIDEOS); - bundle.putString("instanceType","PEERTUBE"); + bundle.putString("instanceType", "PEERTUBE"); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(getApplicationContext())); Account account = new AccountDAO(getApplicationContext(), db).getUniqAccount(userId, instance); - bundle.putString("targetedid",account.getUsername()); + bundle.putString("targetedid", account.getUsername()); bundle.putBoolean("ownvideos", true); fragment.setArguments(bundle); fragmentTag = "MY_VIDEOS"; @@ -1804,13 +1806,13 @@ public abstract class BaseMainActivity extends BaseActivity bundle = new Bundle(); DisplayStatusFragment fragment = new DisplayStatusFragment(); bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.PEERTUBE_HISTORY); - bundle.putString("instanceType","PEERTUBE"); + bundle.putString("instanceType", "PEERTUBE"); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(getApplicationContext())); Account account = new AccountDAO(getApplicationContext(), db).getUniqAccount(userId, instance); - bundle.putString("targetedid",account.getUsername()); + bundle.putString("targetedid", account.getUsername()); fragment.setArguments(bundle); fragmentTag = "MY_HISTORY"; fragmentManager.beginTransaction() @@ -1831,13 +1833,13 @@ public abstract class BaseMainActivity extends BaseActivity fragmentTag = "BLOCKS"; fragmentManager.beginTransaction() .replace(R.id.main_app_container, accountsFragment, fragmentTag).commit(); - }else if (id == R.id.nav_how_to) { + } else if (id == R.id.nav_how_to) { toot.hide(); DisplayHowToFragment displayHowToFragment = new DisplayHowToFragment(); fragmentTag = "HOW_TO_VIDEOS"; fragmentManager.beginTransaction() .replace(R.id.main_app_container, displayHowToFragment, fragmentTag).commit(); - }else if (id == R.id.nav_muted || id == R.id.nav_pixelfed_muted) { + } else if (id == R.id.nav_muted || id == R.id.nav_pixelfed_muted) { toot.hide(); accountsFragment = new DisplayAccountsFragment(); bundle.putSerializable("type", RetrieveAccountsAsyncTask.Type.MUTED); @@ -1845,43 +1847,43 @@ public abstract class BaseMainActivity extends BaseActivity fragmentTag = "MUTED"; fragmentManager.beginTransaction() .replace(R.id.main_app_container, accountsFragment, fragmentTag).commit(); - }else if (id == R.id.nav_scheduled) { + } else if (id == R.id.nav_scheduled) { tootShow(); TabLayoutScheduleFragment tabLayoutScheduleFragment = new TabLayoutScheduleFragment(); fragmentTag = "SCHEDULED"; fragmentManager.beginTransaction() .replace(R.id.main_app_container, tabLayoutScheduleFragment, fragmentTag).commit(); - }else if (id == R.id.nav_drafts) { + } else if (id == R.id.nav_drafts) { DisplayDraftsFragment displayDraftsFragment = new DisplayDraftsFragment(); fragmentTag = "DRAFTS"; fragmentManager.beginTransaction() .replace(R.id.main_app_container, displayDraftsFragment, fragmentTag).commit(); toot.hide(); - }else if (id == R.id.nav_bookmarks) { + } else if (id == R.id.nav_bookmarks) { DisplayBookmarksFragment displayBookmarksFragment = new DisplayBookmarksFragment(); fragmentTag = "BOOKMARKS"; fragmentManager.beginTransaction() .replace(R.id.main_app_container, displayBookmarksFragment, fragmentTag).commit(); toot.hide(); - }else if (id == R.id.nav_peertube) { + } else if (id == R.id.nav_peertube) { DisplayFavoritesPeertubeFragment displayFavoritesPeertubeFragment = new DisplayFavoritesPeertubeFragment(); fragmentTag = "BOOKMARKS_PEERTUBE"; fragmentManager.beginTransaction() .replace(R.id.main_app_container, displayFavoritesPeertubeFragment, fragmentTag).commit(); toot.hide(); - }else if( id == R.id.nav_follow_request){ + } else if (id == R.id.nav_follow_request) { toot.hide(); DisplayFollowRequestSentFragment followRequestSentFragment = new DisplayFollowRequestSentFragment(); fragmentTag = "FOLLOW_REQUEST_SENT"; fragmentManager.beginTransaction() .replace(R.id.main_app_container, followRequestSentFragment, fragmentTag).commit(); - }else if(id == R.id.nav_list){ + } else if (id == R.id.nav_list) { toot.hide(); DisplayListsFragment displayListsFragment = new DisplayListsFragment(); fragmentTag = "LISTS"; fragmentManager.beginTransaction() .replace(R.id.main_app_container, displayListsFragment, fragmentTag).commit(); - }else if(id == R.id.nav_group){ + } else if (id == R.id.nav_group) { toot.hide(); accountsFragment = new DisplayAccountsFragment(); bundle.putSerializable("type", RetrieveAccountsAsyncTask.Type.GROUPS); @@ -1889,19 +1891,19 @@ public abstract class BaseMainActivity extends BaseActivity fragmentTag = "GROUPS"; fragmentManager.beginTransaction() .replace(R.id.main_app_container, accountsFragment, fragmentTag).commit(); - }else if(id == R.id.nav_peertube_playlists){ + } else if (id == R.id.nav_peertube_playlists) { toot.hide(); DisplayPlaylistsFragment displayPlaylistsFragment = new DisplayPlaylistsFragment(); fragmentTag = "PLAYLISTS"; fragmentManager.beginTransaction() .replace(R.id.main_app_container, displayPlaylistsFragment, fragmentTag).commit(); - }else if(id == R.id.nav_filters){ + } else if (id == R.id.nav_filters) { toot.hide(); DisplayFiltersFragment displayFiltersFragment = new DisplayFiltersFragment(); fragmentTag = "FILTERS"; fragmentManager.beginTransaction() .replace(R.id.main_app_container, displayFiltersFragment, fragmentTag).commit(); - }else if(id == R.id.nav_who_to_follow){ + } else if (id == R.id.nav_who_to_follow) { toot.hide(); WhoToFollowFragment whoToFollowFragment = new WhoToFollowFragment(); fragmentTag = "WHO_TO_FOLLOW"; @@ -1916,30 +1918,30 @@ public abstract class BaseMainActivity extends BaseActivity } - public void populateTitleWithTag(String tag, String title, int index){ - if( tag == null) + public void populateTitleWithTag(String tag, String title, int index) { + if (tag == null) return; - if ( tagTile.get(tag) == null) + if (tagTile.get(tag) == null) tagTile.put(tag, title); - if ( tagItem.get(tag) == null) + if (tagItem.get(tag) == null) tagItem.put(tag, index); } @Override public void setTitle(CharSequence title) { - if(toolbarTitle != null ) + if (toolbarTitle != null) toolbarTitle.setText(title); } @Override public void onUpdateAccountInfo(boolean error) { - if( error){ + if (error) { //An error occurred, the user is redirected to the login page Helper.logout(getApplicationContext()); Intent myIntent = new Intent(BaseMainActivity.this, LoginActivity.class); startActivity(myIntent); finish(); - }else { + } else { SQLiteDatabase db = Sqlite.getInstance(BaseMainActivity.this, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); Account account = new AccountDAO(getApplicationContext(), db).getUniqAccount(userId, instance); Helper.updateHeaderAccountInfo(activity, account, headerLayout); @@ -1952,23 +1954,22 @@ public abstract class BaseMainActivity extends BaseActivity super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_IMPORT && resultCode == RESULT_OK) { if (data == null || data.getData() == null) { - Toasty.error(getApplicationContext(),getString(R.string.toot_select_file_error),Toast.LENGTH_LONG).show(); + Toasty.error(getApplicationContext(), getString(R.string.toot_select_file_error), Toast.LENGTH_LONG).show(); return; } String filename = Helper.getFilePathFromURI(getApplicationContext(), data.getData()); Sqlite.importDB(BaseMainActivity.this, filename); - }else if(requestCode == PICK_IMPORT ){ - Toasty.error(getApplicationContext(),getString(R.string.toot_select_file_error),Toast.LENGTH_LONG).show(); + } else if (requestCode == PICK_IMPORT) { + Toasty.error(getApplicationContext(), getString(R.string.toot_select_file_error), Toast.LENGTH_LONG).show(); } } - @Override public void onRetrieveMetaData(boolean error, String sharedSubject, String sharedText, String image, String title, String description) { Bundle b = new Bundle(); - if( !error) { + if (!error) { b.putString("image", image); b.putString("title", title); b.putString("description", description); @@ -1980,10 +1981,10 @@ public abstract class BaseMainActivity extends BaseActivity @Override public void onRetrieveInstance(APIResponse apiResponse) { - if( apiResponse.getError() != null){ + if (apiResponse.getError() != null) { return; } - if( apiResponse.getInstance() == null || apiResponse.getInstance().getVersion() == null || apiResponse.getInstance().getVersion().trim().length() == 0) + if (apiResponse.getInstance() == null || apiResponse.getInstance().getVersion() == null || apiResponse.getInstance().getVersion().trim().length() == 0) return; instanceClass = apiResponse.getInstance(); @@ -2003,13 +2004,13 @@ public abstract class BaseMainActivity extends BaseActivity return; List accounts = results.getAccounts(); List statuses = results.getStatuses(); - if( accounts !=null && accounts.size() > 0){ + if (accounts != null && accounts.size() > 0) { Intent intent = new Intent(BaseMainActivity.this, ShowAccountActivity.class); Bundle b = new Bundle(); b.putParcelable("account", accounts.get(0)); intent.putExtras(b); startActivity(intent); - }else if( statuses != null && statuses.size() > 0){ + } else if (statuses != null && statuses.size() > 0) { Intent intent = new Intent(getApplicationContext(), ShowConversationActivity.class); Bundle b = new Bundle(); b.putParcelable("status", statuses.get(0)); @@ -2026,13 +2027,13 @@ public abstract class BaseMainActivity extends BaseActivity @Override public void onActionDone(ManageFiltersAsyncTask.action actionType, APIResponse apiResponse, int statusCode) { - if( apiResponse != null && apiResponse.getFilters() != null && apiResponse.getFilters().size() > 0){ + if (apiResponse != null && apiResponse.getFilters() != null && apiResponse.getFilters().size() > 0) { filters = apiResponse.getFilters(); } } - public void displayTimelineMoreButton(boolean displayed){ + public void displayTimelineMoreButton(boolean displayed) { if (displayed) { display_timeline.setVisibility(View.VISIBLE); } else { @@ -2050,28 +2051,28 @@ public abstract class BaseMainActivity extends BaseActivity timelines = manageTimelines; - if( position >= manageTimelines.size()){ - position = manageTimelines.size()-1; + if (position >= manageTimelines.size()) { + position = manageTimelines.size() - 1; } - if( position == -1) - position = (timelines.size()-1); - if( position < 0) + if (position == -1) + position = (timelines.size() - 1); + if (position < 0) position = 0; - if( toolbarTitle != null) + if (toolbarTitle != null) toolbarTitle.setVisibility(View.GONE); viewPager.setOffscreenPageLimit(2); main_app_container = findViewById(R.id.main_app_container); boolean iconOnly = true; - for(ManageTimelines tl: timelines){ - if( tl.getType() == ManageTimelines.Type.INSTANCE || tl.getType() == ManageTimelines.Type.TAG || tl.getType() == ManageTimelines.Type.LIST){ + for (ManageTimelines tl : timelines) { + if (tl.getType() == ManageTimelines.Type.INSTANCE || tl.getType() == ManageTimelines.Type.TAG || tl.getType() == ManageTimelines.Type.LIST) { iconOnly = false; } } - if( iconOnly && timelines.size() < 5){ + if (iconOnly && timelines.size() < 5) { tabLayout.setTabMode(TabLayout.MODE_FIXED); - }else{ + } else { tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE); } @@ -2092,23 +2093,23 @@ public abstract class BaseMainActivity extends BaseActivity manageTimelineList(true); delete_instance.setVisibility(View.GONE); Helper.switchLayout(BaseMainActivity.this); - if( manageTimelines.size() > tab.getPosition() && (manageTimelines.get(tab.getPosition()).getType() == ManageTimelines.Type.NOTIFICATION ||manageTimelines.get(tab.getPosition()).getType() == ManageTimelines.Type.ART || manageTimelines.get(tab.getPosition()).getType() == ManageTimelines.Type.PEERTUBE)) { + if (manageTimelines.size() > tab.getPosition() && (manageTimelines.get(tab.getPosition()).getType() == ManageTimelines.Type.NOTIFICATION || manageTimelines.get(tab.getPosition()).getType() == ManageTimelines.Type.ART || manageTimelines.get(tab.getPosition()).getType() == ManageTimelines.Type.PEERTUBE)) { toot.hide(); - }else { + } else { tootShow(); } DrawerLayout drawer = findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); - if( tab.getCustomView() != null) { + if (tab.getCustomView() != null) { ImageView icon = tab.getCustomView().findViewById(R.id.tab_icon); TextView tv = tab.getCustomView().findViewById(R.id.host_name); - if( icon != null) - if( theme == Helper.THEME_BLACK) + if (icon != null) + if (theme == Helper.THEME_BLACK) icon.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.dark_icon), PorterDuff.Mode.SRC_IN); else icon.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.mastodonC4), PorterDuff.Mode.SRC_IN); - else if( tv != null){ + else if (tv != null) { tv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.mastodonC4)); } } @@ -2116,16 +2117,16 @@ public abstract class BaseMainActivity extends BaseActivity @Override public void onTabUnselected(TabLayout.Tab tab) { - if( tab.getCustomView() != null) { + if (tab.getCustomView() != null) { ImageView icon = tab.getCustomView().findViewById(R.id.tab_icon); TextView tv = tab.getCustomView().findViewById(R.id.host_name); - if( icon != null) - if( theme == Helper.THEME_LIGHT) + if (icon != null) + if (theme == Helper.THEME_LIGHT) icon.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.dark_icon), PorterDuff.Mode.SRC_IN); else icon.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.dark_text), PorterDuff.Mode.SRC_IN); - else if( tv != null){ - if( theme == Helper.THEME_LIGHT) + else if (tv != null) { + if (theme == Helper.THEME_LIGHT) tv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_icon)); else tv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_text)); @@ -2135,7 +2136,7 @@ public abstract class BaseMainActivity extends BaseActivity @Override public void onTabReselected(TabLayout.Tab tab) { - if( viewPager.getVisibility() == View.GONE){ + if (viewPager.getVisibility() == View.GONE) { viewPager.setVisibility(View.VISIBLE); manageTimelineList(true); delete_instance.setVisibility(View.GONE); @@ -2144,13 +2145,13 @@ public abstract class BaseMainActivity extends BaseActivity DrawerLayout drawer = findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); } - if( manageTimelines.size() > tab.getPosition() && (manageTimelines.get(tab.getPosition()).getType() == ManageTimelines.Type.ART || manageTimelines.get(tab.getPosition()).getType() == ManageTimelines.Type.PEERTUBE)) { + if (manageTimelines.size() > tab.getPosition() && (manageTimelines.get(tab.getPosition()).getType() == ManageTimelines.Type.ART || manageTimelines.get(tab.getPosition()).getType() == ManageTimelines.Type.PEERTUBE)) { toot.hide(); - }else { + } else { tootShow(); } - if( viewPager.getAdapter() != null) { + if (viewPager.getAdapter() != null) { Fragment fragment = (Fragment) viewPager.getAdapter().instantiateItem(viewPager, tab.getPosition()); ManageTimelines tl = timelines.get(tab.getPosition()); DisplayStatusFragment displayStatusFragment; @@ -2160,15 +2161,15 @@ public abstract class BaseMainActivity extends BaseActivity updateHomeCounter(); displayStatusFragment.scrollToTop(); displayStatusFragment.updateLastReadToot(); - } else if(tl.getType() == ManageTimelines.Type.NOTIFICATION) { + } else if (tl.getType() == ManageTimelines.Type.NOTIFICATION) { countNewNotifications = 0; updateNotifCounter(); - }else { + } else { View tabCustom = tab.getCustomView(); - if( tabCustom != null) { + if (tabCustom != null) { TextView tabCountertCustom = tabCustom.findViewById(R.id.tab_counter); - if( tabCountertCustom != null) { + if (tabCountertCustom != null) { tabCountertCustom.setText(String.valueOf(0)); tabCountertCustom.setVisibility(View.GONE); } @@ -2177,10 +2178,10 @@ public abstract class BaseMainActivity extends BaseActivity displayStatusFragment.scrollToTop(); } } - if( tab.getCustomView() != null) { + if (tab.getCustomView() != null) { ImageView icon = tab.getCustomView().findViewById(R.id.tab_icon); - if( icon != null) - if( theme == Helper.THEME_BLACK) + if (icon != null) + if (theme == Helper.THEME_BLACK) icon.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.dark_icon), PorterDuff.Mode.SRC_IN); else icon.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.mastodonC4), PorterDuff.Mode.SRC_IN); @@ -2188,21 +2189,21 @@ public abstract class BaseMainActivity extends BaseActivity } }); - if( tabLayout.getTabCount() > position) { + if (tabLayout.getTabCount() > position) { TabLayout.Tab tab = tabLayout.getTabAt(position); - if( tab != null) { + if (tab != null) { tab.select(); - if( tab.getCustomView() != null){ + if (tab.getCustomView() != null) { ImageView icon = tab.getCustomView().findViewById(R.id.tab_icon); - if( icon != null){ - if( theme == Helper.THEME_BLACK) + if (icon != null) { + if (theme == Helper.THEME_BLACK) icon.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.dark_icon), PorterDuff.Mode.SRC_IN); else icon.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.mastodonC4), PorterDuff.Mode.SRC_IN); - }else{ + } else { TextView tv = tabLayout.getChildAt(0).findViewById(android.R.id.title); - if( tv != null) - if( theme == Helper.THEME_BLACK) + if (tv != null) + if (theme == Helper.THEME_BLACK) tv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_icon)); else tv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.mastodonC4)); @@ -2215,7 +2216,7 @@ public abstract class BaseMainActivity extends BaseActivity toolbarTitle.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { FragmentManager fragmentManager = getSupportFragmentManager(); - if( navigationView.getMenu().findItem(R.id.nav_favorites) != null && navigationView.getMenu().findItem(R.id.nav_favorites).isChecked()){ + if (navigationView.getMenu().findItem(R.id.nav_favorites) != null && navigationView.getMenu().findItem(R.id.nav_favorites).isChecked()) { DisplayStatusFragment faveFrag = (DisplayStatusFragment) fragmentManager.findFragmentByTag("FAVOURITES"); if (faveFrag != null && faveFrag.isVisible()) { faveFrag.scrollToTop(); @@ -2235,10 +2236,10 @@ public abstract class BaseMainActivity extends BaseActivity //Scroll to top when top bar is clicked (THEME_MENU only) } else { int pos = tabLayout.getSelectedTabPosition(); - if( viewPager.getAdapter() != null) { + if (viewPager.getAdapter() != null) { Fragment fragment = (Fragment) viewPager.getAdapter().instantiateItem(viewPager, pos); ManageTimelines tl = timelines.get(pos); - if( tl.getType() != ManageTimelines.Type.NOTIFICATION){ + if (tl.getType() != ManageTimelines.Type.NOTIFICATION) { DisplayStatusFragment displayStatusFragment = ((DisplayStatusFragment) fragment); displayStatusFragment.scrollToTop(); } @@ -2246,12 +2247,12 @@ public abstract class BaseMainActivity extends BaseActivity } } }); - if( notificationChecked){ + if (notificationChecked) { notificationChecked = false; int i = 0; - for(ManageTimelines tl: timelines){ - if( tl.getType() == ManageTimelines.Type.NOTIFICATION){ - if( tabLayout.getTabAt(i) != null) { + for (ManageTimelines tl : timelines) { + if (tl.getType() == ManageTimelines.Type.NOTIFICATION) { + if (tabLayout.getTabAt(i) != null) { tabLayout.getTabAt(i).select(); } break; @@ -2264,7 +2265,7 @@ public abstract class BaseMainActivity extends BaseActivity /** * Page Adapter for Mastodon & Peertube & PixelFed */ - public class PagerAdapter extends FragmentStatePagerAdapter { + public class PagerAdapter extends FragmentStatePagerAdapter { int mNumOfTabs; private PagerAdapter(FragmentManager fm, int NumOfTabs) { @@ -2276,9 +2277,10 @@ public abstract class BaseMainActivity extends BaseActivity public Parcelable saveState() { return null; } + @Override public Fragment getItem(int position) { - if( social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { //Remove the search bar if (!toolbar_search.isIconified()) { toolbarTitle.setVisibility(View.VISIBLE); @@ -2289,11 +2291,11 @@ public abstract class BaseMainActivity extends BaseActivity //Selection comes from another menu, no action to do Bundle bundle = new Bundle(); ManageTimelines tl = null; - if( position < timelines.size()) + if (position < timelines.size()) tl = timelines.get(position); - if( tl == null) + if (tl == null) return null; - if( tl.getType() != ManageTimelines.Type.NOTIFICATION){ + if (tl.getType() != ManageTimelines.Type.NOTIFICATION) { DisplayStatusFragment displayStatusFragment = new DisplayStatusFragment(); RetrieveFeedsAsyncTask.Type type = ManageTimelines.transform(BaseMainActivity.this, tl.getType()); bundle.putSerializable("type", type); @@ -2301,45 +2303,45 @@ public abstract class BaseMainActivity extends BaseActivity if (tl.getType() == ManageTimelines.Type.TAG) { TagTimeline ttl = tl.getTagTimeline(); bundle.putString("tag", ttl.getName()); - if( ttl.isART() ) - bundle.putString("instanceType","ART"); - }else if (tl.getType() == ManageTimelines.Type.ART) { + if (ttl.isART()) + bundle.putString("instanceType", "ART"); + } else if (tl.getType() == ManageTimelines.Type.ART) { bundle.putString("instanceType", "ART"); - }else if (tl.getType() == ManageTimelines.Type.PEERTUBE) { + } else if (tl.getType() == ManageTimelines.Type.PEERTUBE) { bundle.putString("instanceType", "PEERTUBE"); bundle.putString("remote_instance", "peertube.fedilab.app"); bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE); - }else if( tl.getType() == ManageTimelines.Type.INSTANCE){ - if( tl.getRemoteInstance().getFilteredWith() == null){ - bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE); - }else{ + } else if (tl.getType() == ManageTimelines.Type.INSTANCE) { + if (tl.getRemoteInstance().getFilteredWith() == null) { + bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE); + } else { bundle.putString("currentfilter", tl.getRemoteInstance().getFilteredWith()); - bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE_FILTERED); + bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE_FILTERED); } - bundle.putString("remote_instance", tl.getRemoteInstance().getHost()!=null?tl.getRemoteInstance().getHost():""); + bundle.putString("remote_instance", tl.getRemoteInstance().getHost() != null ? tl.getRemoteInstance().getHost() : ""); bundle.putString("instanceType", tl.getRemoteInstance().getType()); - }else if( tl.getType() == ManageTimelines.Type.LIST){ + } else if (tl.getType() == ManageTimelines.Type.LIST) { bundle.putString("targetedid", tl.getListTimeline().getId()); } bundle.putInt("timelineId", tl.getId()); displayStatusFragment.setArguments(bundle); - if( mPageReferenceMap == null){ + if (mPageReferenceMap == null) { mPageReferenceMap = new HashMap<>(); } mPageReferenceMap.put(tl.getPosition(), displayStatusFragment); return displayStatusFragment; - }else{ + } else { TabLayoutNotificationsFragment tabLayoutNotificationsFragment = new TabLayoutNotificationsFragment(); - if( mPageReferenceMap == null){ + if (mPageReferenceMap == null) { mPageReferenceMap = new HashMap<>(); } mPageReferenceMap.put(tl.getPosition(), tabLayoutNotificationsFragment); return tabLayoutNotificationsFragment; } - }else if (social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE){ + } else if (social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { //Remove the search bar - if( !toolbar_search.isIconified() ) { + if (!toolbar_search.isIconified()) { toolbarTitle.setVisibility(View.VISIBLE); tabLayout.setVisibility(View.VISIBLE); toolbar_search.setIconified(true); @@ -2349,21 +2351,21 @@ public abstract class BaseMainActivity extends BaseActivity DisplayStatusFragment fragment = new DisplayStatusFragment(); if (position == 0) { bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.PSUBSCRIPTIONS); - }else if( position == 1) { + } else if (position == 1) { bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.POVERVIEW); - }else if( position == 2) { + } else if (position == 2) { bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.PTRENDING); - }else if( position == 3) { + } else if (position == 3) { bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.PRECENTLYADDED); - }else if( position == 4) { + } else if (position == 4) { bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.PLOCAL); } - bundle.putString("instanceType","PEERTUBE"); + bundle.putString("instanceType", "PEERTUBE"); fragment.setArguments(bundle); return fragment; - }else if (social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED){ + } else if (social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) { //Remove the search bar - if( !toolbar_search.isIconified() ) { + if (!toolbar_search.isIconified()) { toolbarTitle.setVisibility(View.VISIBLE); tabLayout.setVisibility(View.VISIBLE); toolbar_search.setIconified(true); @@ -2374,16 +2376,16 @@ public abstract class BaseMainActivity extends BaseActivity if (position == 0) { DisplayStatusFragment fragment = new DisplayStatusFragment(); bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.PF_HOME); - bundle.putString("instanceType","PIXELFED"); + bundle.putString("instanceType", "PIXELFED"); fragment.setArguments(bundle); return fragment; - }else if( position == 1) { + } else if (position == 1) { DisplayStatusFragment fragment = new DisplayStatusFragment(); bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.PF_LOCAL); - bundle.putString("instanceType","PIXELFED"); + bundle.putString("instanceType", "PIXELFED"); fragment.setArguments(bundle); return fragment; - }else if( position == 2){ + } else if (position == 2) { DisplayNotificationsFragment fragment = new DisplayNotificationsFragment(); bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.PF_NOTIFICATION); fragment.setArguments(bundle); @@ -2400,13 +2402,14 @@ public abstract class BaseMainActivity extends BaseActivity @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { - if( mPageReferenceMap != null) { + if (mPageReferenceMap != null) { mPageReferenceMap.remove(position); - }else{ + } else { mPageReferenceMap = new HashMap<>(); } super.destroyItem(container, position, object); } + @Override public int getCount() { return mNumOfTabs; @@ -2414,29 +2417,27 @@ public abstract class BaseMainActivity extends BaseActivity } - - - public void updateHomeCounter(){ + public void updateHomeCounter() { int i = 0; SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int tootperpage = sharedpreferences.getInt(Helper.SET_TOOT_PER_PAGE, Helper.TOOTS_PER_PAGE); - if( timelines != null && timelines.size() > 0){ - for(ManageTimelines tl: timelines){ - if( tl.getType() == ManageTimelines.Type.HOME){ - if( tabLayout.getTabCount() > i) { + if (timelines != null && timelines.size() > 0) { + for (ManageTimelines tl : timelines) { + if (tl.getType() == ManageTimelines.Type.HOME) { + if (tabLayout.getTabCount() > i) { View tabHome = tabLayout.getTabAt(i).getCustomView(); - if( tabHome != null){ + if (tabHome != null) { TextView tabCounterHome = tabHome.findViewById(R.id.tab_counter); - if(countNewStatus == tootperpage){ + if (countNewStatus == tootperpage) { tabCounterHome.setText(String.format(Locale.getDefault(), "%d+", countNewStatus)); - }else{ + } else { tabCounterHome.setText(String.valueOf(countNewStatus)); } - if( countNewStatus> 0){ + if (countNewStatus > 0) { //New data are available //The fragment is not displayed, so the counter is displayed tabCounterHome.setVisibility(View.VISIBLE); - }else { + } else { tabCounterHome.setVisibility(View.GONE); } } @@ -2448,18 +2449,18 @@ public abstract class BaseMainActivity extends BaseActivity } } - public void manageTab( RetrieveFeedsAsyncTask.Type type, int value){ + public void manageTab(RetrieveFeedsAsyncTask.Type type, int value) { SQLiteDatabase db = Sqlite.getInstance(BaseMainActivity.this, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); List tls = new TimelinesDAO(BaseMainActivity.this, db).getDisplayedTimelines(); - for (ManageTimelines tl: tls){ - if( type == ManageTimelines.transform(BaseMainActivity.this, tl.getType())){ + for (ManageTimelines tl : tls) { + if (type == ManageTimelines.transform(BaseMainActivity.this, tl.getType())) { View tabCustom = tabLayout.getTabAt(tl.getPosition()).getCustomView(); assert tabCustom != null; TextView tabCountertCustom = tabCustom.findViewById(R.id.tab_counter); tabCountertCustom.setText(String.valueOf(value)); - if( value > 0){ + if (value > 0) { tabCountertCustom.setVisibility(View.VISIBLE); - }else { + } else { tabCountertCustom.setVisibility(View.GONE); } break; @@ -2467,55 +2468,56 @@ public abstract class BaseMainActivity extends BaseActivity } } - public void updateNotifCounter(){ - if( timelines == null) + public void updateNotifCounter() { + if (timelines == null) return; int i = 0; int position = -1; - for(ManageTimelines tl: timelines){ - if( tl.getType() == ManageTimelines.Type.NOTIFICATION){ - if( tabLayout.getTabAt(i) != null) { + for (ManageTimelines tl : timelines) { + if (tl.getType() == ManageTimelines.Type.NOTIFICATION) { + if (tabLayout.getTabAt(i) != null) { position = i; } break; } i++; } - if( position == -1) + if (position == -1) return; View tabNotif = tabLayout.getTabAt(position).getCustomView(); - if( tabNotif == null) + if (tabNotif == null) return; TextView tabCounterNotif = tabNotif.findViewById(R.id.tab_counter); - if( tabCounterNotif == null) + if (tabCounterNotif == null) return; - if(countNewNotifications == Helper.NOTIFICATIONS_PER_PAGE){ + if (countNewNotifications == Helper.NOTIFICATIONS_PER_PAGE) { tabCounterNotif.setText(String.format(Locale.getDefault(), "%d+", countNewNotifications)); - }else{ + } else { tabCounterNotif.setText(String.valueOf(countNewNotifications)); } - if( countNewNotifications > 0){ + if (countNewNotifications > 0) { tabCounterNotif.setVisibility(View.VISIBLE); - }else { + } else { tabCounterNotif.setVisibility(View.GONE); } - try{ + try { TabLayoutNotificationsFragment tabLayoutNotificationsFragment = (TabLayoutNotificationsFragment) mPageReferenceMap.get(position); ViewPager notifViewPager = tabLayoutNotificationsFragment.getViewPager(); - if( notifViewPager != null && notifViewPager.getAdapter() != null) { + if (notifViewPager != null && notifViewPager.getAdapter() != null) { DisplayNotificationsFragment displayNotificationsFragment = (DisplayNotificationsFragment) notifViewPager.getAdapter().instantiateItem(notifViewPager, 0); displayNotificationsFragment.updateNotificationRead(); } - }catch (Exception ignored){} + } catch (Exception ignored) { + } } - public void startSreaming(){ + public void startSreaming() { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); boolean liveNotifications = sharedpreferences.getBoolean(Helper.SET_LIVE_NOTIFICATIONS, true); - if( liveNotifications) { + if (liveNotifications) { ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); assert manager != null; for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { @@ -2526,36 +2528,35 @@ public abstract class BaseMainActivity extends BaseActivity try { Intent streamingIntent = new Intent(this, LiveNotificationService.class); startService(streamingIntent); - }catch(Exception ignored){} + } catch (Exception ignored) { + } } } - public void manageFloatingButton(boolean display){ + public void manageFloatingButton(boolean display) { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); - if( social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE ||social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA|| social == UpdateAccountInfoAsyncTask.SOCIAL.GNU|| social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + if (social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE || social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { if (display) { tootShow(); } else { toot.hide(); } - }else { + } else { toot.hide(); } } - public void tootShow(){ - if( social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE ||social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA|| social == UpdateAccountInfoAsyncTask.SOCIAL.GNU|| social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + + public void tootShow() { + if (social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE || social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { toot.show(); - }else{ + } else { toot.hide(); } } - - - - public boolean getFloatingVisibility(){ + public boolean getFloatingVisibility() { return toot.getVisibility() == View.VISIBLE; } diff --git a/app/src/main/java/app/fedilab/android/activities/CustomSharingActivity.java b/app/src/main/java/app/fedilab/android/activities/CustomSharingActivity.java index 1aac94118..c04ffdcef 100644 --- a/app/src/main/java/app/fedilab/android/activities/CustomSharingActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/CustomSharingActivity.java @@ -22,8 +22,10 @@ import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; + import androidx.appcompat.app.ActionBar; import androidx.appcompat.widget.Toolbar; + import android.text.Html; import android.text.TextUtils; import android.view.LayoutInflater; @@ -72,13 +74,14 @@ public class CustomSharingActivity extends BaseActivity implements OnCustomShari private String bundle_content; private String bundle_thumbnailurl; private String bundle_creator; + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme); break; @@ -95,7 +98,7 @@ public class CustomSharingActivity extends BaseActivity implements OnCustomShari setContentView(R.layout.activity_custom_sharing); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null) { + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); assert inflater != null; View view = inflater.inflate(R.layout.simple_action_bar, new LinearLayout(getApplicationContext()), false); @@ -105,7 +108,7 @@ public class CustomSharingActivity extends BaseActivity implements OnCustomShari pp_actionBar = actionBar.getCustomView().findViewById(R.id.pp_actionBar); title.setText(R.string.settings_title_custom_sharing); ImageView close_conversation = actionBar.getCustomView().findViewById(R.id.close_conversation); - if( close_conversation != null){ + if (close_conversation != null) { close_conversation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -113,25 +116,25 @@ public class CustomSharingActivity extends BaseActivity implements OnCustomShari } }); } - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Toolbar toolbar = actionBar.getCustomView().findViewById(R.id.toolbar); Helper.colorizeToolbar(toolbar, R.color.black, CustomSharingActivity.this); } - }else{ + } else { setTitle(R.string.settings_title_custom_sharing); } SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, null); - Account account = new AccountDAO(getApplicationContext(),db).getUniqAccount(userId, instance); + Account account = new AccountDAO(getApplicationContext(), db).getUniqAccount(userId, instance); Helper.loadGiF(getApplicationContext(), account.getAvatar(), pp_actionBar); Bundle b = getIntent().getExtras(); Status status = null; - if(b != null) { + if (b != null) { status = b.getParcelable("status"); } - if( status == null){ + if (status == null) { finish(); return; } @@ -142,7 +145,7 @@ public class CustomSharingActivity extends BaseActivity implements OnCustomShari bundle_source = status.getAccount().getUrl(); String bundle_tags = status.getTagsString(); bundle_content = formatedContent(status.getContent(), status.getEmojis()); - if( status.getCard() != null && status.getCard().getImage() != null) { + if (status.getCard() != null && status.getCard().getImage() != null) { bundle_thumbnailurl = status.getCard().getImage(); } else if (status.getMedia_attachments() != null && status.getMedia_attachments().size() > 0) { ArrayList mediaAttachments = status.getMedia_attachments(); @@ -162,7 +165,7 @@ public class CustomSharingActivity extends BaseActivity implements OnCustomShari String[] lines = bundle_content.split("\n"); //Remove tags in title if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) - lines[0] = Html.fromHtml( lines[0], Html.FROM_HTML_MODE_LEGACY).toString(); + lines[0] = Html.fromHtml(lines[0], Html.FROM_HTML_MODE_LEGACY).toString(); else //noinspection deprecation lines[0] = Html.fromHtml(lines[0]).toString(); @@ -175,7 +178,7 @@ public class CustomSharingActivity extends BaseActivity implements OnCustomShari set_custom_sharing_title.setText(newTitle); String newDescription = ""; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) - newDescription = Html.fromHtml( bundle_content, Html.FROM_HTML_MODE_LEGACY).toString(); + newDescription = Html.fromHtml(bundle_content, Html.FROM_HTML_MODE_LEGACY).toString(); else //noinspection deprecation newDescription = Html.fromHtml(bundle_content).toString(); @@ -192,8 +195,8 @@ public class CustomSharingActivity extends BaseActivity implements OnCustomShari CharSequence comma_only = ","; CharSequence space_only = " "; CharSequence double_space = " "; - keywords = keywords.replace(comma_only,space_only); - keywords = keywords.replace(double_space,space_only); + keywords = keywords.replace(comma_only, space_only); + keywords = keywords.replace(double_space, space_only); // Create encodedCustomSharingURL custom_sharing_url = sharedpreferences.getString(Helper.SET_CUSTOM_SHARING_URL, "http://example.net/add?token=YOUR_TOKEN&url=${url}&title=${title}" + @@ -218,7 +221,7 @@ public class CustomSharingActivity extends BaseActivity implements OnCustomShari @Override public void onCustomSharing(CustomSharingResponse customSharingResponse) { set_custom_sharing_save.setEnabled(true); - if( customSharingResponse.getError() != null){ + if (customSharingResponse.getError() != null) { Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); return; } @@ -244,8 +247,8 @@ public class CustomSharingActivity extends BaseActivity implements OnCustomShari for (String param_name : args) { paramFound = false; String param_value = uri.getQueryParameter(param_name); - if(param_value != null) - switch(param_value) { + if (param_value != null) + switch (param_value) { case "${url}": paramFound = true; builder.appendQueryParameter(param_name, bundle_url); @@ -287,14 +290,14 @@ public class CustomSharingActivity extends BaseActivity implements OnCustomShari } - private String formatedContent(String content, List emojis){ + private String formatedContent(String content, List emojis) { //Avoid null content - if( content == null) + if (content == null) return ""; - if( emojis == null || emojis.size() == 0) + if (emojis == null || emojis.size() == 0) return content; for (Emojis emoji : emojis) { - content = content.replaceAll(":"+emoji.getShortcode()+":",""+emoji.getShortcode()+""); + content = content.replaceAll(":" + emoji.getShortcode() + ":", "" + emoji.getShortcode() + ""); } return content; } diff --git a/app/src/main/java/app/fedilab/android/activities/EditProfileActivity.java b/app/src/main/java/app/fedilab/android/activities/EditProfileActivity.java index f0969ab73..be55d3358 100644 --- a/app/src/main/java/app/fedilab/android/activities/EditProfileActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/EditProfileActivity.java @@ -30,12 +30,14 @@ import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; + import androidx.annotation.NonNull; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.Toolbar; + import android.text.Editable; import android.text.Html; import android.text.TextWatcher; @@ -86,7 +88,6 @@ import app.fedilab.android.interfaces.OnUpdateCredentialInterface; public class EditProfileActivity extends BaseActivity implements OnRetrieveAccountInterface, OnUpdateCredentialInterface { - private EditText set_profile_name, set_profile_description; private ImageView set_profile_picture, set_header_picture; private Button set_change_profile_picture, set_change_header_picture, set_profile_save; @@ -110,7 +111,7 @@ public class EditProfileActivity extends BaseActivity implements OnRetrieveAccou SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme); break; @@ -127,7 +128,7 @@ public class EditProfileActivity extends BaseActivity implements OnRetrieveAccou setContentView(R.layout.activity_edit_profile); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null) { + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); assert inflater != null; View view = inflater.inflate(R.layout.simple_action_bar, new LinearLayout(getApplicationContext()), false); @@ -137,7 +138,7 @@ public class EditProfileActivity extends BaseActivity implements OnRetrieveAccou pp_actionBar = actionBar.getCustomView().findViewById(R.id.pp_actionBar); title.setText(R.string.settings_title_profile); ImageView close_conversation = actionBar.getCustomView().findViewById(R.id.close_conversation); - if( close_conversation != null){ + if (close_conversation != null) { close_conversation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -145,18 +146,17 @@ public class EditProfileActivity extends BaseActivity implements OnRetrieveAccou } }); } - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Toolbar toolbar = actionBar.getCustomView().findViewById(R.id.toolbar); Helper.colorizeToolbar(toolbar, R.color.black, EditProfileActivity.this); } - }else{ + } else { setTitle(R.string.settings_title_profile); } SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, null); - Account account = new AccountDAO(getApplicationContext(),db).getUniqAccount(userId, instance); - + Account account = new AccountDAO(getApplicationContext(), db).getUniqAccount(userId, instance); Helper.loadGiF(getApplicationContext(), account.getAvatar(), pp_actionBar); @@ -174,10 +174,10 @@ public class EditProfileActivity extends BaseActivity implements OnRetrieveAccou String instanceVersion = sharedpreferences.getString(Helper.INSTANCE_VERSION + userId + instance, null); Version currentVersion = new Version(instanceVersion); Version minVersion = new Version("2.3"); - if(currentVersion.compareTo(minVersion) == 1) { + if (currentVersion.compareTo(minVersion) == 1) { set_lock_account.setVisibility(View.VISIBLE); set_sensitive_content.setVisibility(View.VISIBLE); - }else { + } else { set_lock_account.setVisibility(View.GONE); set_sensitive_content.setVisibility(View.GONE); } @@ -207,21 +207,21 @@ public class EditProfileActivity extends BaseActivity implements OnRetrieveAccou @Override public void onRetrieveAccount(Account account, Error error) { - if( error != null ){ - Toasty.error(getApplicationContext(),getString(R.string.toast_error), Toast.LENGTH_LONG).show(); + if (error != null) { + Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); return; } set_profile_name.setText(account.getDisplay_name()); set_profile_name.setSelection(set_profile_name.getText().length()); String content = account.getNote(); - if( content != null) { + if (content != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) content = Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY).toString(); else //noinspection deprecation content = Html.fromHtml(content).toString(); - }else + } else content = ""; set_profile_description.setText(content); @@ -232,40 +232,44 @@ public class EditProfileActivity extends BaseActivity implements OnRetrieveAccou set_profile_description.setEnabled(true); set_lock_account.setEnabled(true); set_sensitive_content.setEnabled(true); - if( account.isLocked()) + if (account.isLocked()) set_lock_account.setChecked(true); else set_lock_account.setChecked(false); - if( account.isSensitive()) + if (account.isSensitive()) set_sensitive_content.setChecked(true); else set_sensitive_content.setChecked(false); set_profile_description.addTextChangedListener(new TextWatcher() { @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) {} + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } + @Override - public void onTextChanged(CharSequence s, int start, int before, int count) {} + public void onTextChanged(CharSequence s, int start, int before, int count) { + } + @Override public void afterTextChanged(Editable s) { - if( s.length() > 160){ - String content = s.toString().substring(0,160); + if (s.length() > 160) { + String content = s.toString().substring(0, 160); set_profile_description.setText(content); set_profile_description.setSelection(set_profile_description.getText().length()); - Toasty.info(getApplicationContext(),getString(R.string.note_no_space),Toast.LENGTH_LONG).show(); + Toasty.info(getApplicationContext(), getString(R.string.note_no_space), Toast.LENGTH_LONG).show(); } } }); - if ( account.getFields() != null && account.getFields().size() > 0){ + if (account.getFields() != null && account.getFields().size() > 0) { HashMap fields = account.getFields(); Iterator it = fields.entrySet().iterator(); int i = 1; while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - String label = (String)pair.getKey(); - String value = (String)pair.getValue(); + Map.Entry pair = (Map.Entry) it.next(); + String label = (String) pair.getKey(); + String value = (String) pair.getValue(); EditText labelView; EditText valueView; - switch(i){ + switch (i) { case 1: labelView = findViewById(R.id.cf_key_1); valueView = findViewById(R.id.cf_val_1); @@ -300,16 +304,20 @@ public class EditProfileActivity extends BaseActivity implements OnRetrieveAccou set_profile_name.addTextChangedListener(new TextWatcher() { @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) {} + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } + @Override - public void onTextChanged(CharSequence s, int start, int before, int count) {} + public void onTextChanged(CharSequence s, int start, int before, int count) { + } + @Override public void afterTextChanged(Editable s) { - if( s.length() > 30){ - String content = s.toString().substring(0,30); + if (s.length() > 30) { + String content = s.toString().substring(0, 30); set_profile_name.setText(content); set_profile_name.setSelection(set_profile_name.getText().length()); - Toasty.info(getApplicationContext(),getString(R.string.username_no_space),Toast.LENGTH_LONG).show(); + Toasty.info(getApplicationContext(), getString(R.string.username_no_space), Toast.LENGTH_LONG).show(); } } }); @@ -334,7 +342,7 @@ public class EditProfileActivity extends BaseActivity implements OnRetrieveAccou pickIntent.setType("image/*"); Intent chooserIntent = Intent.createChooser(getIntent, getString(R.string.toot_select_image)); - chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent}); + chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{pickIntent}); startActivityForResult(chooserIntent, PICK_IMAGE_HEADER); } }); @@ -360,7 +368,7 @@ public class EditProfileActivity extends BaseActivity implements OnRetrieveAccou pickIntent.setType("image/*"); Intent chooserIntent = Intent.createChooser(getIntent, getString(R.string.toot_select_image)); - chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent}); + chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{pickIntent}); startActivityForResult(chooserIntent, PICK_IMAGE_PROFILE); } }); @@ -371,7 +379,7 @@ public class EditProfileActivity extends BaseActivity implements OnRetrieveAccou Glide.with(set_header_picture.getContext()) .load(account.getHeader()) .into(set_header_picture); - if( account.getHeader() == null || account.getHeader().contains("missing.png")) + if (account.getHeader() == null || account.getHeader().contains("missing.png")) set_header_picture_overlay.setVisibility(View.VISIBLE); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); @@ -379,21 +387,21 @@ public class EditProfileActivity extends BaseActivity implements OnRetrieveAccou set_profile_save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - if(set_profile_name.getText() != null && !set_profile_name.getText().toString().equals(set_profile_name.getHint())) + if (set_profile_name.getText() != null && !set_profile_name.getText().toString().equals(set_profile_name.getHint())) profile_username = set_profile_name.getText().toString().trim(); else profile_username = null; - if(set_profile_description.getText() != null && !set_profile_description.getText().toString().equals(set_profile_description.getHint())) + if (set_profile_description.getText() != null && !set_profile_description.getText().toString().equals(set_profile_description.getHint())) profile_note = set_profile_description.getText().toString().trim(); else profile_note = null; int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(EditProfileActivity.this, style); @@ -406,43 +414,43 @@ public class EditProfileActivity extends BaseActivity implements OnRetrieveAccou TextView dialog_profile_name = dialogView.findViewById(R.id.dialog_profile_name); TextView dialog_profile_description = dialogView.findViewById(R.id.dialog_profile_description); - if( profile_username != null) + if (profile_username != null) dialog_profile_name.setText(profile_username); - if( profile_note != null) + if (profile_note != null) dialog_profile_description.setText(profile_note); - if( profile_header_bmp != null) { + if (profile_header_bmp != null) { BitmapDrawable background = new BitmapDrawable(getApplicationContext().getResources(), profile_header_bmp); - if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { //noinspection deprecation back_ground_image.setBackgroundDrawable(background); } else { back_ground_image.setBackground(background); } - }else { - if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { + } else { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { //noinspection deprecation back_ground_image.setBackgroundDrawable(set_header_picture.getDrawable()); } else { back_ground_image.setBackground(set_header_picture.getDrawable()); } } - if( profile_picture_bmp != null) { + if (profile_picture_bmp != null) { BitmapDrawable background = new BitmapDrawable(getApplicationContext().getResources(), profile_picture_bmp); - if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { //noinspection deprecation dialog_profile_picture.setBackgroundDrawable(background); } else { dialog_profile_picture.setBackground(background); } - }else { - if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { + } else { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { //noinspection deprecation dialog_profile_picture.setBackgroundDrawable(set_profile_picture.getDrawable()); } else { dialog_profile_picture.setBackground(set_profile_picture.getDrawable()); } } - profile_privacy = set_lock_account.isChecked()?API.accountPrivacy.LOCKED:API.accountPrivacy.PUBLIC; + profile_privacy = set_lock_account.isChecked() ? API.accountPrivacy.LOCKED : API.accountPrivacy.PUBLIC; sensitive = set_sensitive_content.isChecked(); dialogBuilder.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() { @Override @@ -458,22 +466,22 @@ public class EditProfileActivity extends BaseActivity implements OnRetrieveAccou HashMap newCustomFields = new HashMap<>(); String key1, key2, key3, key4, val1, val2, val3, val4; - key1 = ((EditText)findViewById(R.id.cf_key_1)).getText().toString(); - key2 = ((EditText)findViewById(R.id.cf_key_2)).getText().toString(); - key3 = ((EditText)findViewById(R.id.cf_key_3)).getText().toString(); - key4 = ((EditText)findViewById(R.id.cf_key_4)).getText().toString(); + key1 = ((EditText) findViewById(R.id.cf_key_1)).getText().toString(); + key2 = ((EditText) findViewById(R.id.cf_key_2)).getText().toString(); + key3 = ((EditText) findViewById(R.id.cf_key_3)).getText().toString(); + key4 = ((EditText) findViewById(R.id.cf_key_4)).getText().toString(); - val1 = ((EditText)findViewById(R.id.cf_val_1)).getText().toString(); - val2 = ((EditText)findViewById(R.id.cf_val_2)).getText().toString(); - val3 = ((EditText)findViewById(R.id.cf_val_3)).getText().toString(); - val4 = ((EditText)findViewById(R.id.cf_val_4)).getText().toString(); + val1 = ((EditText) findViewById(R.id.cf_val_1)).getText().toString(); + val2 = ((EditText) findViewById(R.id.cf_val_2)).getText().toString(); + val3 = ((EditText) findViewById(R.id.cf_val_3)).getText().toString(); + val4 = ((EditText) findViewById(R.id.cf_val_4)).getText().toString(); - newCustomFields.put(key1,val1); - newCustomFields.put(key2,val2); - newCustomFields.put(key3,val3); - newCustomFields.put(key4,val4); + newCustomFields.put(key1, val1); + newCustomFields.put(key2, val2); + newCustomFields.put(key3, val3); + newCustomFields.put(key4, val4); - new UpdateCredentialAsyncTask(getApplicationContext(), newCustomFields, profile_username, profile_note, profile_picture, avatarName, header_picture, headerName, profile_privacy, sensitive, EditProfileActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new UpdateCredentialAsyncTask(getApplicationContext(), newCustomFields, profile_username, profile_note, profile_picture, avatarName, header_picture, headerName, profile_privacy, sensitive, EditProfileActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } }); dialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @@ -521,7 +529,7 @@ public class EditProfileActivity extends BaseActivity implements OnRetrieveAccou super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_IMAGE_HEADER && resultCode == RESULT_OK) { if (data == null || data.getData() == null) { - Toasty.error(getApplicationContext(),getString(R.string.toot_select_image_error),Toast.LENGTH_LONG).show(); + Toasty.error(getApplicationContext(), getString(R.string.toot_select_image_error), Toast.LENGTH_LONG).show(); return; } Uri fileUri = data.getData(); @@ -537,9 +545,9 @@ public class EditProfileActivity extends BaseActivity implements OnRetrieveAccou e.printStackTrace(); } header_picture = Helper.compressImage(EditProfileActivity.this, fileUri, Helper.MediaType.MEDIA); - }else if(requestCode == PICK_IMAGE_PROFILE && resultCode == RESULT_OK) { + } else if (requestCode == PICK_IMAGE_PROFILE && resultCode == RESULT_OK) { if (data == null || data.getData() == null) { - Toasty.error(getApplicationContext(),getString(R.string.toot_select_image_error),Toast.LENGTH_LONG).show(); + Toasty.error(getApplicationContext(), getString(R.string.toot_select_image_error), Toast.LENGTH_LONG).show(); return; } Uri fileUri = data.getData(); @@ -561,7 +569,7 @@ public class EditProfileActivity extends BaseActivity implements OnRetrieveAccou @Override public void onUpdateCredential(APIResponse apiResponse) { set_profile_save.setEnabled(true); - if( apiResponse.getError() != null){ + if (apiResponse.getError() != null) { Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); return; } diff --git a/app/src/main/java/app/fedilab/android/activities/GroupActivity.java b/app/src/main/java/app/fedilab/android/activities/GroupActivity.java index 21344797c..3981b6df4 100644 --- a/app/src/main/java/app/fedilab/android/activities/GroupActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/GroupActivity.java @@ -75,7 +75,7 @@ public class GroupActivity extends BaseActivity implements OnRetrieveFeedsInterf SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case THEME_LIGHT: setTheme(R.style.AppTheme_NoActionBar); break; @@ -91,16 +91,16 @@ public class GroupActivity extends BaseActivity implements OnRetrieveFeedsInterf setContentView(R.layout.activity_group); Toolbar toolbar = findViewById(R.id.toolbar); - if( theme == THEME_BLACK) + if (theme == THEME_BLACK) toolbar.setBackgroundColor(ContextCompat.getColor(GroupActivity.this, R.color.black)); setSupportActionBar(toolbar); - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); Bundle b = getIntent().getExtras(); - if(b != null) + if (b != null) groupname = b.getString("groupname", null); - if( groupname == null) + if (groupname == null) finish(); statuses = new ArrayList<>(); max_id = null; @@ -128,23 +128,22 @@ public class GroupActivity extends BaseActivity implements OnRetrieveFeedsInterf statuses = new ArrayList<>(); firstLoad = true; flag_loading = true; - new RetrieveFeedsAsyncTask(getApplicationContext(), RetrieveFeedsAsyncTask.Type.GNU_GROUP_TIMELINE, groupname,null, max_id, GroupActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new RetrieveFeedsAsyncTask(getApplicationContext(), RetrieveFeedsAsyncTask.Type.GNU_GROUP_TIMELINE, groupname, null, max_id, GroupActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } }); final LinearLayoutManager mLayoutManager; mLayoutManager = new LinearLayoutManager(this); lv_status.setLayoutManager(mLayoutManager); lv_status.addOnScrollListener(new RecyclerView.OnScrollListener() { - public void onScrolled(@NotNull RecyclerView recyclerView, int dx, int dy) - { - if(dy > 0){ + public void onScrolled(@NotNull RecyclerView recyclerView, int dx, int dy) { + if (dy > 0) { int visibleItemCount = mLayoutManager.getChildCount(); int totalItemCount = mLayoutManager.getItemCount(); int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition(); - if(firstVisibleItem + visibleItemCount == totalItemCount ) { - if(!flag_loading ) { + if (firstVisibleItem + visibleItemCount == totalItemCount) { + if (!flag_loading) { flag_loading = true; - new RetrieveFeedsAsyncTask(getApplicationContext(), RetrieveFeedsAsyncTask.Type.GNU_GROUP_TIMELINE, groupname,null, max_id, GroupActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new RetrieveFeedsAsyncTask(getApplicationContext(), RetrieveFeedsAsyncTask.Type.GNU_GROUP_TIMELINE, groupname, null, max_id, GroupActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); nextElementLoader.setVisibility(View.VISIBLE); } @@ -154,15 +153,16 @@ public class GroupActivity extends BaseActivity implements OnRetrieveFeedsInterf } } }); - new RetrieveFeedsAsyncTask(getApplicationContext(), RetrieveFeedsAsyncTask.Type.GNU_GROUP_TIMELINE, groupname,null, max_id, GroupActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new RetrieveFeedsAsyncTask(getApplicationContext(), RetrieveFeedsAsyncTask.Type.GNU_GROUP_TIMELINE, groupname, null, max_id, GroupActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } + @Override public boolean onPrepareOptionsMenu(Menu menu) { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if( theme == THEME_LIGHT) + if (theme == THEME_LIGHT) Helper.colorizeIconMenu(menu, R.color.black); return super.onPrepareOptionsMenu(menu); } @@ -183,24 +183,24 @@ public class GroupActivity extends BaseActivity implements OnRetrieveFeedsInterf mainLoader.setVisibility(View.GONE); nextElementLoader.setVisibility(View.GONE); - if( apiResponse == null || apiResponse.getError() != null){ - if( apiResponse != null) { + if (apiResponse == null || apiResponse.getError() != null) { + if (apiResponse != null) { Toasty.error(getApplicationContext(), apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); - }else{ + } else { Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); } return; } List statuses = apiResponse.getStatuses(); - if( firstLoad && (statuses == null || statuses.size() == 0)) + if (firstLoad && (statuses == null || statuses.size() == 0)) textviewNoAction.setVisibility(View.VISIBLE); else textviewNoAction.setVisibility(View.GONE); - if( statuses != null && statuses.size() > 1) - max_id =statuses.get(statuses.size()-1).getId(); + if (statuses != null && statuses.size() > 1) + max_id = statuses.get(statuses.size() - 1).getId(); else max_id = null; - if( statuses != null) { + if (statuses != null) { this.statuses.addAll(statuses); statusListAdapter.notifyDataSetChanged(); } diff --git a/app/src/main/java/app/fedilab/android/activities/HashTagActivity.java b/app/src/main/java/app/fedilab/android/activities/HashTagActivity.java index f19adb2f3..a55b958e4 100644 --- a/app/src/main/java/app/fedilab/android/activities/HashTagActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/HashTagActivity.java @@ -20,11 +20,13 @@ import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.os.Bundle; + import androidx.core.content.ContextCompat; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.appcompat.widget.Toolbar; + import android.view.Menu; import android.view.MenuItem; import android.view.View; @@ -74,7 +76,7 @@ public class HashTagActivity extends BaseActivity implements OnRetrieveFeedsInte SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme_NoActionBar_Fedilab); break; @@ -90,16 +92,16 @@ public class HashTagActivity extends BaseActivity implements OnRetrieveFeedsInte setContentView(R.layout.activity_hashtag); Toolbar toolbar = findViewById(R.id.toolbar); - if( theme == Helper.THEME_BLACK) + if (theme == Helper.THEME_BLACK) toolbar.setBackgroundColor(ContextCompat.getColor(HashTagActivity.this, R.color.black)); setSupportActionBar(toolbar); - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); Bundle b = getIntent().getExtras(); - if(b != null) + if (b != null) tag = b.getString("tag", null); - if( tag == null) + if (tag == null) finish(); statuses = new ArrayList<>(); max_id = null; @@ -126,23 +128,22 @@ public class HashTagActivity extends BaseActivity implements OnRetrieveFeedsInte statuses = new ArrayList<>(); firstLoad = true; flag_loading = true; - new RetrieveFeedsAsyncTask(getApplicationContext(), RetrieveFeedsAsyncTask.Type.TAG, tag,null, max_id, HashTagActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new RetrieveFeedsAsyncTask(getApplicationContext(), RetrieveFeedsAsyncTask.Type.TAG, tag, null, max_id, HashTagActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } }); final LinearLayoutManager mLayoutManager; mLayoutManager = new LinearLayoutManager(this); lv_status.setLayoutManager(mLayoutManager); lv_status.addOnScrollListener(new RecyclerView.OnScrollListener() { - public void onScrolled(@NotNull RecyclerView recyclerView, int dx, int dy) - { - if(dy > 0){ + public void onScrolled(@NotNull RecyclerView recyclerView, int dx, int dy) { + if (dy > 0) { int visibleItemCount = mLayoutManager.getChildCount(); int totalItemCount = mLayoutManager.getItemCount(); int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition(); - if(firstVisibleItem + visibleItemCount == totalItemCount ) { - if(!flag_loading ) { + if (firstVisibleItem + visibleItemCount == totalItemCount) { + if (!flag_loading) { flag_loading = true; - new RetrieveFeedsAsyncTask(getApplicationContext(), RetrieveFeedsAsyncTask.Type.TAG, tag,null, max_id, HashTagActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new RetrieveFeedsAsyncTask(getApplicationContext(), RetrieveFeedsAsyncTask.Type.TAG, tag, null, max_id, HashTagActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); nextElementLoader.setVisibility(View.VISIBLE); } @@ -152,21 +153,22 @@ public class HashTagActivity extends BaseActivity implements OnRetrieveFeedsInte } } }); - new RetrieveFeedsAsyncTask(getApplicationContext(), RetrieveFeedsAsyncTask.Type.TAG, tag,null, max_id, HashTagActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new RetrieveFeedsAsyncTask(getApplicationContext(), RetrieveFeedsAsyncTask.Type.TAG, tag, null, max_id, HashTagActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } + @Override public boolean onPrepareOptionsMenu(Menu menu) { SQLiteDatabase db = Sqlite.getInstance(HashTagActivity.this, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); List searchInDb = new SearchDAO(HashTagActivity.this, db).getSearchByKeyword(tag.trim()); - if( searchInDb == null || searchInDb.size() == 0){ + if (searchInDb == null || searchInDb.size() == 0) { menu.clear(); menu.add(0, 777, Menu.NONE, R.string.pin_add).setIcon(R.drawable.ic_add).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); } SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if( theme == Helper.THEME_LIGHT) + if (theme == Helper.THEME_LIGHT) Helper.colorizeIconMenu(menu, R.color.black); return super.onPrepareOptionsMenu(menu); } @@ -195,23 +197,23 @@ public class HashTagActivity extends BaseActivity implements OnRetrieveFeedsInte mainLoader.setVisibility(View.GONE); nextElementLoader.setVisibility(View.GONE); - if( apiResponse == null || apiResponse.getError() != null){ - if( apiResponse != null) - Toasty.error(getApplicationContext(), apiResponse.getError().getError(),Toast.LENGTH_LONG).show(); + if (apiResponse == null || apiResponse.getError() != null) { + if (apiResponse != null) + Toasty.error(getApplicationContext(), apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); else - Toasty.error(getApplicationContext(), getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); return; } List statuses = apiResponse.getStatuses(); - if( firstLoad && (statuses == null || statuses.size() == 0)) + if (firstLoad && (statuses == null || statuses.size() == 0)) textviewNoAction.setVisibility(View.VISIBLE); else textviewNoAction.setVisibility(View.GONE); - if( statuses != null && statuses.size() > 1) - max_id =statuses.get(statuses.size()-1).getId(); + if (statuses != null && statuses.size() > 1) + max_id = statuses.get(statuses.size() - 1).getId(); else max_id = null; - if( statuses != null) { + if (statuses != null) { this.statuses.addAll(statuses); statusListAdapter.notifyDataSetChanged(); } diff --git a/app/src/main/java/app/fedilab/android/activities/HideItemActivity.java b/app/src/main/java/app/fedilab/android/activities/HideItemActivity.java index abae0c900..0e070cb33 100644 --- a/app/src/main/java/app/fedilab/android/activities/HideItemActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/HideItemActivity.java @@ -27,8 +27,10 @@ import android.widget.CheckBox; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; + import androidx.appcompat.app.ActionBar; import androidx.appcompat.widget.Toolbar; + import app.fedilab.android.R; import app.fedilab.android.client.Entities.MainMenuItem; @@ -50,7 +52,7 @@ public class HideItemActivity extends BaseActivity { super.onCreate(savedInstanceState); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme); break; @@ -64,10 +66,10 @@ public class HideItemActivity extends BaseActivity { setTheme(R.style.AppThemeDark); } - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null ) { + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); assert inflater != null; View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); @@ -82,7 +84,7 @@ public class HideItemActivity extends BaseActivity { } }); toolbar_title.setText(R.string.hide_menu_items); - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Toolbar toolbar = actionBar.getCustomView().findViewById(R.id.toolbar); Helper.colorizeToolbar(toolbar, R.color.black, HideItemActivity.this); } @@ -91,7 +93,7 @@ public class HideItemActivity extends BaseActivity { SQLiteDatabase db = Sqlite.getInstance(HideItemActivity.this, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); MainMenuItem mainMenu = new MainMenuDAO(getApplicationContext(), db).getMainMenu(); - if( mainMenu == null){ + if (mainMenu == null) { mainMenu = new MainMenuItem(); } CheckBox nav_news = findViewById(R.id.nav_news); @@ -139,9 +141,9 @@ public class HideItemActivity extends BaseActivity { mainMenuItem.setNav_howto(nav_how_to.isChecked()); MainMenuItem mainMenuItem1 = new MainMenuDAO(getApplicationContext(), db).getMainMenu(); - if( mainMenuItem1 != null){ + if (mainMenuItem1 != null) { new MainMenuDAO(getApplicationContext(), db).updateMenu(mainMenuItem); - }else{ + } else { new MainMenuDAO(getApplicationContext(), db).insertMenu(mainMenuItem); } Intent mainActivity = new Intent(HideItemActivity.this, MainActivity.class); diff --git a/app/src/main/java/app/fedilab/android/activities/InstanceActivity.java b/app/src/main/java/app/fedilab/android/activities/InstanceActivity.java index 0daf9f774..94ed8ce0c 100644 --- a/app/src/main/java/app/fedilab/android/activities/InstanceActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/InstanceActivity.java @@ -23,9 +23,12 @@ import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; + import com.google.android.material.floatingactionbutton.FloatingActionButton; + import androidx.appcompat.app.ActionBar; import androidx.appcompat.widget.Toolbar; + import android.text.Html; import android.view.LayoutInflater; import android.view.MenuItem; @@ -64,7 +67,7 @@ public class InstanceActivity extends BaseActivity implements OnRetrieveInstance super.onCreate(savedInstanceState); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme); break; @@ -78,10 +81,10 @@ public class InstanceActivity extends BaseActivity implements OnRetrieveInstance setTheme(R.style.AppThemeDark); } - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null ) { + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); assert inflater != null; View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); @@ -96,13 +99,13 @@ public class InstanceActivity extends BaseActivity implements OnRetrieveInstance } }); toolbar_title.setText(R.string.action_about_instance); - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Toolbar toolbar = actionBar.getCustomView().findViewById(R.id.toolbar); Helper.colorizeToolbar(toolbar, R.color.black, InstanceActivity.this); } } setContentView(R.layout.activity_instance); - Helper.changeDrawableColor(getApplicationContext(), R.drawable.ic_mail_outline,R.color.white); + Helper.changeDrawableColor(getApplicationContext(), R.drawable.ic_mail_outline, R.color.white); instance_container = findViewById(R.id.instance_container); loader = findViewById(R.id.loader); instance_container.setVisibility(View.GONE); @@ -128,12 +131,12 @@ public class InstanceActivity extends BaseActivity implements OnRetrieveInstance public void onRetrieveInstance(APIResponse apiResponse) { instance_container.setVisibility(View.VISIBLE); loader.setVisibility(View.GONE); - if( apiResponse.getError() != null){ + if (apiResponse.getError() != null) { Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); return; } final Instance instance = apiResponse.getInstance(); - if( instance == null){ + if (instance == null) { Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); return; } @@ -149,18 +152,18 @@ public class InstanceActivity extends BaseActivity implements OnRetrieveInstance else //noinspection deprecation instance_description.setText(Html.fromHtml(instance.getDescription())); - if( instance.getDescription() == null || instance.getDescription().trim().length() == 0 ) + if (instance.getDescription() == null || instance.getDescription().trim().length() == 0) instance_description.setText(getString(R.string.instance_no_description)); instance_version.setText(instance.getVersion()); instance_uri.setText(instance.getUri()); - if( instance.getEmail() == null){ + if (instance.getEmail() == null) { instance_contact.hide(); } instance_contact.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto",instance.getEmail(), null)); + Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", instance.getEmail(), null)); emailIntent.putExtra(Intent.EXTRA_SUBJECT, "[Mastodon] - " + instance.getUri()); startActivity(Intent.createChooser(emailIntent, getString(R.string.send_email))); } diff --git a/app/src/main/java/app/fedilab/android/activities/InstanceHealthActivity.java b/app/src/main/java/app/fedilab/android/activities/InstanceHealthActivity.java index 6e4274475..7056f5a62 100644 --- a/app/src/main/java/app/fedilab/android/activities/InstanceHealthActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/InstanceHealthActivity.java @@ -15,7 +15,6 @@ package app.fedilab.android.activities; - import android.annotation.SuppressLint; import android.content.Intent; import android.content.SharedPreferences; @@ -30,7 +29,9 @@ import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; + import androidx.core.content.ContextCompat; + import android.text.SpannableString; import android.text.style.UnderlineSpan; import android.view.MenuItem; @@ -77,7 +78,7 @@ public class InstanceHealthActivity extends BaseActivity { requestWindowFeature(Window.FEATURE_NO_TITLE); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme); break; @@ -93,10 +94,10 @@ public class InstanceHealthActivity extends BaseActivity { setContentView(R.layout.activity_instance_social); getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); Bundle b = getIntent().getExtras(); - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().hide(); - instance = Helper.getLiveInstance(getApplicationContext()); - if(b != null) + instance = Helper.getLiveInstance(getApplicationContext()); + if (b != null) instance = b.getString("instance", Helper.getLiveInstance(getApplicationContext())); Button close = findViewById(R.id.close); @@ -143,23 +144,23 @@ public class InstanceHealthActivity extends BaseActivity { } - private void checkInstance(){ + private void checkInstance() { - if( instance == null) + if (instance == null) return; - new Thread(new Runnable(){ + new Thread(new Runnable() { @Override public void run() { try { HashMap parameters = new HashMap<>(); parameters.put("name", instance.trim()); - final String response = new HttpsConnection(InstanceHealthActivity.this, instance).get("https://instances.social/api/1.0/instances/show", 30, parameters, Helper.THEKINRAR_SECRET_TOKEN ); - if( response != null) + final String response = new HttpsConnection(InstanceHealthActivity.this, instance).get("https://instances.social/api/1.0/instances/show", 30, parameters, Helper.THEKINRAR_SECRET_TOKEN); + if (response != null) instanceSocial = API.parseInstanceSocialResponse(getApplicationContext(), new JSONObject(response)); runOnUiThread(new Runnable() { @SuppressLint({"SetTextI18n", "DefaultLocale"}) public void run() { - if( instanceSocial.getThumbnail() != null && !instanceSocial.getThumbnail().equals("null")) + if (instanceSocial.getThumbnail() != null && !instanceSocial.getThumbnail().equals("null")) Glide.with(getApplicationContext()) .asBitmap() .load(instanceSocial.getThumbnail()) @@ -176,21 +177,21 @@ public class InstanceHealthActivity extends BaseActivity { BitmapDrawable background = new BitmapDrawable(getResources(), mutableBitmap); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { container.setBackground(background); - }else{ + } else { container.setBackgroundDrawable(background); } } }); name.setText(instanceSocial.getName()); - if( instanceSocial.isUp()) { + if (instanceSocial.isUp()) { up.setText("Is up!"); up.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.green)); - }else { + } else { up.setText("Is down!"); up.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.red)); } - uptime.setText(String.format("Uptime: %.2f %%", (instanceSocial.getUptime()*100))); - if( instanceSocial.getChecked_at() != null) + uptime.setText(String.format("Uptime: %.2f %%", (instanceSocial.getUptime() * 100))); + if (instanceSocial.getChecked_at() != null) checked_at.setText(String.format("Checked at: %s", Helper.dateToString(instanceSocial.getChecked_at()))); values.setText(String.format("version: %s \n %s users - %s statuses", instanceSocial.getVersion(), Helper.withSuffix(instanceSocial.getUsers()), Helper.withSuffix(instanceSocial.getStatuses()))); instance_container.setVisibility(View.VISIBLE); @@ -198,11 +199,11 @@ public class InstanceHealthActivity extends BaseActivity { } }); - } catch (Exception ignored) {} + } catch (Exception ignored) { + } } }).start(); } - } diff --git a/app/src/main/java/app/fedilab/android/activities/LanguageActivity.java b/app/src/main/java/app/fedilab/android/activities/LanguageActivity.java index 18935d767..4ee4e0da0 100644 --- a/app/src/main/java/app/fedilab/android/activities/LanguageActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/LanguageActivity.java @@ -22,8 +22,10 @@ import android.content.pm.PackageManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; + import androidx.appcompat.app.ActionBar; import androidx.appcompat.widget.Toolbar; + import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; @@ -73,7 +75,7 @@ public class LanguageActivity extends BaseActivity implements OnRetrieveRemoteAc super.onCreate(savedInstanceState); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme); break; @@ -87,10 +89,10 @@ public class LanguageActivity extends BaseActivity implements OnRetrieveRemoteAc setTheme(R.style.AppThemeDark); } - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null ) { + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); assert inflater != null; View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); @@ -105,7 +107,7 @@ public class LanguageActivity extends BaseActivity implements OnRetrieveRemoteAc } }); toolbar_title.setText(R.string.languages); - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Toolbar toolbar = actionBar.getCustomView().findViewById(R.id.toolbar); Helper.colorizeToolbar(toolbar, R.color.black, LanguageActivity.this); } @@ -113,16 +115,15 @@ public class LanguageActivity extends BaseActivity implements OnRetrieveRemoteAc setContentView(R.layout.activity_language); - Button about_translation = findViewById(R.id.about_translation); about_translation.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://crowdin.com/project/mastalab")); - startActivity(browserIntent); - } + @Override + public void onClick(View v) { + Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://crowdin.com/project/mastalab")); + startActivity(browserIntent); + } }); ExpandableHeightListView lv_translator_manager = findViewById(R.id.lv_translator_manager); @@ -137,7 +138,6 @@ public class LanguageActivity extends BaseActivity implements OnRetrieveRemoteAc new RetrieveRemoteDataAsyncTask(getApplicationContext(), "ButterflyOfFire", "mstdn.fr", LanguageActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - String currentLanguage = sharedpreferences.getString(Helper.SET_DEFAULT_LOCALE_NEW, Helper.localeToStringStorage(Locale.getDefault())); Locale currentLocale = Helper.restoreLocaleFromString(currentLanguage); final Spinner set_change_locale = findViewById(R.id.set_change_locale); @@ -151,7 +151,7 @@ public class LanguageActivity extends BaseActivity implements OnRetrieveRemoteAc set_change_locale.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { - if( count2 > 0 ) { + if (count2 > 0) { SharedPreferences.Editor editor = sharedpreferences.edit(); switch (position) { case 0: @@ -179,7 +179,7 @@ public class LanguageActivity extends BaseActivity implements OnRetrieveRemoteAc editor.commit(); break; case 6: - editor.putString(Helper.SET_DEFAULT_LOCALE_NEW,"zh-TW"); + editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "zh-TW"); editor.commit(); break; case 7: @@ -250,6 +250,7 @@ public class LanguageActivity extends BaseActivity implements OnRetrieveRemoteAc } count2++; } + @Override public void onNothingSelected(AdapterView parent) { @@ -274,13 +275,13 @@ public class LanguageActivity extends BaseActivity implements OnRetrieveRemoteAc @Override public void onRetrieveRemoteAccount(Results results) { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); - if( results == null){ - Toasty.error(getApplicationContext(), getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + if (results == null) { + Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); return; } List accounts = results.getAccounts(); Account account; - if( accounts != null && accounts.size() > 0){ + if (accounts != null && accounts.size() > 0) { account = accounts.get(0); account.setFollowing(true); switch (account.getUsername()) { @@ -289,17 +290,17 @@ public class LanguageActivity extends BaseActivity implements OnRetrieveRemoteAc translatorManager.notifyDataSetChanged(); break; } - new RetrieveRelationshipAsyncTask(getApplicationContext(), account.getId(),LanguageActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new RetrieveRelationshipAsyncTask(getApplicationContext(), account.getId(), LanguageActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } @Override - public void onResume(){ + public void onResume() { super.onResume(); - if( translators != null){ - for(Account account: translators){ - new RetrieveRelationshipAsyncTask(getApplicationContext(), account.getId(),LanguageActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + if (translators != null) { + for (Account account : translators) { + new RetrieveRelationshipAsyncTask(getApplicationContext(), account.getId(), LanguageActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } @@ -309,11 +310,11 @@ public class LanguageActivity extends BaseActivity implements OnRetrieveRemoteAc public void onRetrieveRelationship(Relationship relationship, Error error) { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, ""); - if( error != null){ + if (error != null) { return; } - for( int i = 0 ; i < translators.size() ; i++){ - if( translators.get(i).getId() != null && translators.get(i).getId().equals(relationship.getId())){ + for (int i = 0; i < translators.size(); i++) { + if (translators.get(i).getId() != null && translators.get(i).getId().equals(relationship.getId())) { translators.get(i).setFollowing(relationship.isFollowing() || userId.trim().equals(relationship.getId())); translatorManager.notifyDataSetChanged(); break; diff --git a/app/src/main/java/app/fedilab/android/activities/ListActivity.java b/app/src/main/java/app/fedilab/android/activities/ListActivity.java index 3dfa5c528..822d2a03a 100644 --- a/app/src/main/java/app/fedilab/android/activities/ListActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/ListActivity.java @@ -20,6 +20,7 @@ import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; + import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.localbroadcastmanager.content.LocalBroadcastManager; @@ -28,6 +29,7 @@ import androidx.appcompat.app.AlertDialog; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.appcompat.widget.Toolbar; + import android.text.InputFilter; import android.view.LayoutInflater; import android.view.Menu; @@ -79,7 +81,7 @@ public class ListActivity extends BaseActivity implements OnListActionInterface super.onCreate(savedInstanceState); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme_NoActionBar_Fedilab); break; @@ -94,17 +96,17 @@ public class ListActivity extends BaseActivity implements OnListActionInterface } setContentView(R.layout.activity_list); Toolbar toolbar = findViewById(R.id.toolbar); - if( theme == Helper.THEME_BLACK) + if (theme == Helper.THEME_BLACK) toolbar.setBackgroundColor(ContextCompat.getColor(ListActivity.this, R.color.black)); setSupportActionBar(toolbar); - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); statuses = new ArrayList<>(); RecyclerView lv_status = findViewById(R.id.lv_status); - mainLoader = findViewById(R.id.loader); + mainLoader = findViewById(R.id.loader); nextElementLoader = findViewById(R.id.loading_next_status); - textviewNoAction = findViewById(R.id.no_action); + textviewNoAction = findViewById(R.id.no_action); mainLoader.setVisibility(View.VISIBLE); swipeRefreshLayout = findViewById(R.id.swipeContainer); max_id = null; @@ -124,29 +126,28 @@ public class ListActivity extends BaseActivity implements OnListActionInterface lv_status.setLayoutManager(mLayoutManager); Bundle b = getIntent().getExtras(); - if(b != null){ + if (b != null) { title = b.getString("title"); listId = b.getString("id"); - }else{ - Toasty.error(getApplicationContext(),getString(R.string.toast_error_search),Toast.LENGTH_LONG).show(); + } else { + Toasty.error(getApplicationContext(), getString(R.string.toast_error_search), Toast.LENGTH_LONG).show(); } - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); setTitle(title); lv_status.addOnScrollListener(new RecyclerView.OnScrollListener() { - public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) - { + public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition(); - if(dy > 0){ + if (dy > 0) { int visibleItemCount = mLayoutManager.getChildCount(); int totalItemCount = mLayoutManager.getItemCount(); - if(firstVisibleItem + visibleItemCount == totalItemCount ) { - if(!flag_loading ) { + if (firstVisibleItem + visibleItemCount == totalItemCount) { + if (!flag_loading) { flag_loading = true; - new ManageListsAsyncTask(ListActivity.this,listId, max_id ,null, ListActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new ManageListsAsyncTask(ListActivity.this, listId, max_id, null, ListActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); nextElementLoader.setVisibility(View.VISIBLE); } } else { @@ -165,11 +166,11 @@ public class ListActivity extends BaseActivity implements OnListActionInterface flag_loading = true; swiped = true; MainActivity.countNewStatus = 0; - new ManageListsAsyncTask(ListActivity.this,listId, null ,null, ListActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new ManageListsAsyncTask(ListActivity.this, listId, null, null, ListActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } }); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: swipeRefreshLayout.setColorSchemeResources(R.color.mastodonC4, R.color.mastodonC2, @@ -190,7 +191,7 @@ public class ListActivity extends BaseActivity implements OnListActionInterface break; } - new ManageListsAsyncTask(ListActivity.this,listId, null ,null, ListActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new ManageListsAsyncTask(ListActivity.this, listId, null, null, ListActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } @@ -218,9 +219,9 @@ public class ListActivity extends BaseActivity implements OnListActionInterface int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(ListActivity.this, style); @@ -233,7 +234,7 @@ public class ListActivity extends BaseActivity implements OnListActionInterface dialogBuilder.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { - if( editText.getText() != null && editText.getText().toString().trim().length() > 0 ) + if (editText.getText() != null && editText.getText().toString().trim().length() > 0) new ManageListsAsyncTask(ListActivity.this, ManageListsAsyncTask.action.UPDATE_LIST, null, listId, editText.getText().toString(), editText.getText().toString().trim(), ListActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); dialog.dismiss(); } @@ -257,7 +258,7 @@ public class ListActivity extends BaseActivity implements OnListActionInterface imm.hideSoftInputFromWindow(editText.getWindowToken(), 0); } }); - if( alertDialog.getWindow() != null ) + if (alertDialog.getWindow() != null) alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); alertDialog.show(); return true; @@ -274,14 +275,14 @@ public class ListActivity extends BaseActivity implements OnListActionInterface nextElementLoader.setVisibility(View.GONE); //Discards 404 - error which can often happen due to toots which have been deleted if (apiResponse.getError() != null) { - if ( !apiResponse.getError().getError().startsWith("404 -")) + if (!apiResponse.getError().getError().startsWith("404 -")) Toasty.error(getApplicationContext(), apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); swipeRefreshLayout.setRefreshing(false); swiped = false; flag_loading = false; return; } - if( actionType == ManageListsAsyncTask.action.GET_LIST_TIMELINE) { + if (actionType == ManageListsAsyncTask.action.GET_LIST_TIMELINE) { int previousPosition = this.statuses.size(); List statuses = apiResponse.getStatuses(); @@ -307,7 +308,7 @@ public class ListActivity extends BaseActivity implements OnListActionInterface } swipeRefreshLayout.setRefreshing(false); firstLoad = false; - }else if(actionType == ManageListsAsyncTask.action.UPDATE_LIST) { + } else if (actionType == ManageListsAsyncTask.action.UPDATE_LIST) { Intent intentUP = new Intent(Helper.RECEIVE_UPDATE_TOPBAR); LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intentUP); } diff --git a/app/src/main/java/app/fedilab/android/activities/LoginActivity.java b/app/src/main/java/app/fedilab/android/activities/LoginActivity.java index ba3c6766a..48a807522 100644 --- a/app/src/main/java/app/fedilab/android/activities/LoginActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/LoginActivity.java @@ -27,12 +27,15 @@ import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; + import com.google.android.material.textfield.TextInputLayout; + import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.Toolbar; + import android.text.Editable; import android.text.SpannableString; import android.text.Spanned; @@ -122,11 +125,11 @@ public class LoginActivity extends BaseActivity { Bundle b = getIntent().getExtras(); socialNetwork = UpdateAccountInfoAsyncTask.SOCIAL.MASTODON; admin = false; - if(b != null) { + if (b != null) { autofilledInstance = b.getString("instance", null); social = b.getString("social", null); - if( social != null){ - switch (social){ + if (social != null) { + switch (social) { case "MASTODON": socialNetwork = UpdateAccountInfoAsyncTask.SOCIAL.MASTODON; break; @@ -141,7 +144,7 @@ public class LoginActivity extends BaseActivity { admin = b.getBoolean("admin", false); } - if( getIntent() != null && getIntent().getData() != null && getIntent().getData().toString().contains("mastalab://backtomastalab?code=")){ + if (getIntent() != null && getIntent().getData() != null && getIntent().getData().toString().contains("mastalab://backtomastalab?code=")) { String url = getIntent().getData().toString(); String val[] = url.split("code="); String code = val[1]; @@ -149,10 +152,10 @@ public class LoginActivity extends BaseActivity { final HashMap parameters = new HashMap<>(); parameters.put(Helper.CLIENT_ID, client_id); parameters.put(Helper.CLIENT_SECRET, client_secret); - parameters.put(Helper.REDIRECT_URI,Helper.REDIRECT_CONTENT_WEB); + parameters.put(Helper.REDIRECT_URI, Helper.REDIRECT_CONTENT_WEB); parameters.put("grant_type", "authorization_code"); - parameters.put("code",code); - new Thread(new Runnable(){ + parameters.put("code", code); + new Thread(new Runnable() { @Override public void run() { try { @@ -162,7 +165,7 @@ public class LoginActivity extends BaseActivity { resobj = new JSONObject(response); String token = resobj.get("access_token").toString(); String refresh_token = null; - if( resobj.has("refresh_token")) + if (resobj.has("refresh_token")) refresh_token = resobj.get("refresh_token").toString(); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); SharedPreferences.Editor editor = sharedpreferences.edit(); @@ -170,14 +173,19 @@ public class LoginActivity extends BaseActivity { editor.apply(); //Update the account with the token; new UpdateAccountInfoAsyncTask(LoginActivity.this, token, client_id, client_secret, refresh_token, instance, socialNetwork).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } catch (JSONException ignored) {ignored.printStackTrace();} - } catch (Exception ignored) {ignored.printStackTrace();} - }}).start(); - }else { + } catch (JSONException ignored) { + ignored.printStackTrace(); + } + } catch (Exception ignored) { + ignored.printStackTrace(); + } + } + }).start(); + } else { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme); break; @@ -193,7 +201,7 @@ public class LoginActivity extends BaseActivity { setContentView(R.layout.activity_login); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null ) { + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); assert inflater != null; View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); @@ -208,7 +216,7 @@ public class LoginActivity extends BaseActivity { } }); toolbar_title.setText(R.string.add_account); - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Toolbar toolbar = actionBar.getCustomView().findViewById(R.id.toolbar); Helper.colorizeToolbar(toolbar, R.color.black, LoginActivity.this); } @@ -220,15 +228,15 @@ public class LoginActivity extends BaseActivity { } TextView create_an_account_message = findViewById(R.id.create_an_account); - SpannableString content_create = new SpannableString(getString(R.string.join_mastodon)); + SpannableString content_create = new SpannableString(getString(R.string.join_mastodon)); content_create.setSpan(new UnderlineSpan(), 0, content_create.length(), 0); - if( theme == Helper.THEME_DARK) + if (theme == Helper.THEME_DARK) content_create.setSpan(new ForegroundColorSpan(ContextCompat.getColor(LoginActivity.this, R.color.dark_link_toot)), 0, content_create.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); - else if( theme == Helper.THEME_BLACK) + else if (theme == Helper.THEME_BLACK) content_create.setSpan(new ForegroundColorSpan(ContextCompat.getColor(LoginActivity.this, R.color.black_link_toot)), 0, content_create.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); - else if( theme == Helper.THEME_LIGHT) + else if (theme == Helper.THEME_LIGHT) content_create.setSpan(new ForegroundColorSpan(ContextCompat.getColor(LoginActivity.this, R.color.mastodonC4)), 0, content_create.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); create_an_account_message.setText(content_create); @@ -255,7 +263,7 @@ public class LoginActivity extends BaseActivity { set_instance_type.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener() { @Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) { - switch(position) { + switch (position) { case 0: case 1: case 2: @@ -299,7 +307,7 @@ public class LoginActivity extends BaseActivity { } instance = login_instance.getText().toString().trim().toLowerCase(); connect_button.setEnabled(false); - new Thread(new Runnable(){ + new Thread(new Runnable() { @Override public void run() { instanceNodeInfo = new API(LoginActivity.this).getNodeInfo(instance); @@ -307,8 +315,8 @@ public class LoginActivity extends BaseActivity { runOnUiThread(new Runnable() { public void run() { connect_button.setEnabled(true); - if(instanceNodeInfo != null && instanceNodeInfo.getName() != null){ - switch (instanceNodeInfo.getName()){ + if (instanceNodeInfo != null && instanceNodeInfo.getName() != null) { + switch (instanceNodeInfo.getName()) { case "MASTODON": socialNetwork = UpdateAccountInfoAsyncTask.SOCIAL.MASTODON; break; @@ -322,27 +330,28 @@ public class LoginActivity extends BaseActivity { socialNetwork = UpdateAccountInfoAsyncTask.SOCIAL.GNU; break; } - if( instanceNodeInfo.getName().equals("MASTODON") || instanceNodeInfo.getName().equals("PIXELFED")) { + if (instanceNodeInfo.getName().equals("MASTODON") || instanceNodeInfo.getName().equals("PIXELFED")) { client_id_for_webview = true; retrievesClientId(); - }else { - if( instanceNodeInfo.getName().equals("PEERTUBE")) { + } else { + if (instanceNodeInfo.getName().equals("PEERTUBE")) { step_login_credential.setVisibility(View.VISIBLE); step_instance.setVisibility(View.GONE); instance_chosen.setText(instance); retrievesClientId(); - }else if( instanceNodeInfo.getName().equals("GNU")){ + } else if (instanceNodeInfo.getName().equals("GNU")) { step_login_credential.setVisibility(View.VISIBLE); step_instance.setVisibility(View.GONE); instance_chosen.setText(instance); } } - }else if(instanceNodeInfo != null && instanceNodeInfo.isConnectionError()){ - Toasty.error(getApplicationContext(),getString(R.string.connect_error), Toast.LENGTH_LONG).show(); - }else{ - Toasty.error(getApplicationContext(),getString(R.string.client_error), Toast.LENGTH_LONG).show(); + } else if (instanceNodeInfo != null && instanceNodeInfo.isConnectionError()) { + Toasty.error(getApplicationContext(), getString(R.string.connect_error), Toast.LENGTH_LONG).show(); + } else { + Toasty.error(getApplicationContext(), getString(R.string.client_error), Toast.LENGTH_LONG).show(); } - }}); + } + }); } @@ -354,7 +363,7 @@ public class LoginActivity extends BaseActivity { login_instance.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override - public void onItemClick (AdapterView parent, View view, int position, long id) { + public void onItemClick(AdapterView parent, View view, int position, long id) { oldSearch = parent.getItemAtPosition(position).toString().trim(); } }); @@ -377,7 +386,7 @@ public class LoginActivity extends BaseActivity { parameters.put("count", String.valueOf(1000)); parameters.put("name", String.valueOf(true)); isLoadingInstance = true; - if( oldSearch == null || !oldSearch.equals(s.toString().trim())) + if (oldSearch == null || !oldSearch.equals(s.toString().trim())) new Thread(new Runnable() { @Override public void run() { @@ -393,13 +402,13 @@ public class LoginActivity extends BaseActivity { if (jsonArray != null) { int length = 0; for (int i = 0; i < jsonArray.length(); i++) { - if( !jsonArray.getJSONObject(i).get("name").toString().contains("@")) + if (!jsonArray.getJSONObject(i).get("name").toString().contains("@")) length++; } instances = new String[length]; int j = 0; for (int i = 0; i < jsonArray.length(); i++) { - if( !jsonArray.getJSONObject(i).get("name").toString().contains("@")) { + if (!jsonArray.getJSONObject(i).get("name").toString().contains("@")) { instances[j] = jsonArray.getJSONObject(i).get("name").toString(); j++; } @@ -432,12 +441,12 @@ public class LoginActivity extends BaseActivity { } }); - if( socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.GNU) + if (socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.GNU) connectionButton.setEnabled(false); login_instance.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { - if( socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.GNU) + if (socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.GNU) connectionButton.setEnabled(false); TextInputLayout login_instance_layout = findViewById(R.id.login_instance_layout); if (!hasFocus) { @@ -467,9 +476,9 @@ public class LoginActivity extends BaseActivity { int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this, style); @@ -490,13 +499,13 @@ public class LoginActivity extends BaseActivity { builder.setIcon(android.R.drawable.ic_dialog_alert).show(); } }); - if( autofilledInstance != null){ + if (autofilledInstance != null) { login_instance.setText(autofilledInstance.trim()); retrievesClientId(); login_uid.requestFocus(); } - if( social != null){ - switch (social){ + if (social != null) { + switch (social) { case "MASTODON": set_instance_type.setSelectedIndex(0); break; @@ -521,43 +530,44 @@ public class LoginActivity extends BaseActivity { } @Override - protected void onResume(){ + protected void onResume() { super.onResume(); - if (login_instance != null &&login_instance.getText() != null && login_instance.getText().toString().length() > 0 && client_id_for_webview) { + if (login_instance != null && login_instance.getText() != null && login_instance.getText().toString().length() > 0 && client_id_for_webview) { connectionButton.setEnabled(false); client_id_for_webview = false; retrievesClientId(); } } - private void retrievesClientId(){ - if( socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.GNU){ + private void retrievesClientId() { + if (socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.GNU) { String instanceFromField = login_instance.getText().toString().trim(); - String host = instanceFromField; + String host = instanceFromField; try { URL url = new URL(instanceFromField); host = url.getHost(); - } catch (MalformedURLException ignored) { } - try { - instance = URLEncoder.encode(host, "utf-8"); - } catch (UnsupportedEncodingException e) { - Toasty.error(getApplicationContext(),getString(R.string.client_error), Toast.LENGTH_LONG).show(); + } catch (MalformedURLException ignored) { } - if( socialNetwork == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) + try { + instance = URLEncoder.encode(host, "utf-8"); + } catch (UnsupportedEncodingException e) { + Toasty.error(getApplicationContext(), getString(R.string.client_error), Toast.LENGTH_LONG).show(); + } + if (socialNetwork == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) actionToken = "/api/v1/oauth-clients/local"; else actionToken = "/api/v1/apps"; final HashMap parameters = new HashMap<>(); parameters.put(Helper.CLIENT_NAME, Helper.CLIENT_NAME_VALUE); - parameters.put(Helper.REDIRECT_URIS, client_id_for_webview?Helper.REDIRECT_CONTENT_WEB:Helper.REDIRECT_CONTENT); - if( socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { - if( admin ) { + parameters.put(Helper.REDIRECT_URIS, client_id_for_webview ? Helper.REDIRECT_CONTENT_WEB : Helper.REDIRECT_CONTENT); + if (socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { + if (admin) { parameters.put(Helper.SCOPES, Helper.OAUTH_SCOPES_ADMIN); - }else{ + } else { parameters.put(Helper.SCOPES, Helper.OAUTH_SCOPES); } - }else { + } else { parameters.put(Helper.SCOPES, Helper.OAUTH_SCOPES_PEERTUBE); } /*if(socialNetwork == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED){ @@ -568,15 +578,15 @@ public class LoginActivity extends BaseActivity { }*/ parameters.put(Helper.WEBSITE, Helper.WEBSITE_VALUE); - new Thread(new Runnable(){ + new Thread(new Runnable() { @Override public void run() { try { String response; - if( socialNetwork == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) - response = new HttpsConnection(LoginActivity.this, instance).get(Helper.instanceWithProtocol(getApplicationContext(),instance) + actionToken, 30, parameters, null ); + if (socialNetwork == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) + response = new HttpsConnection(LoginActivity.this, instance).get(Helper.instanceWithProtocol(getApplicationContext(), instance) + actionToken, 30, parameters, null); else - response = new HttpsConnection(LoginActivity.this, instance).post(Helper.instanceWithProtocol(getApplicationContext(), instance) + actionToken, 30, parameters, null ); + response = new HttpsConnection(LoginActivity.this, instance).post(Helper.instanceWithProtocol(getApplicationContext(), instance) + actionToken, 30, parameters, null); runOnUiThread(new Runnable() { public void run() { JSONObject resobj; @@ -585,7 +595,7 @@ public class LoginActivity extends BaseActivity { client_id = resobj.get(Helper.CLIENT_ID).toString(); client_secret = resobj.get(Helper.CLIENT_SECRET).toString(); String id = null; - if( socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) + if (socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) id = resobj.get(Helper.ID).toString(); manageClient(client_id, client_secret, id); } catch (JSONException e) { @@ -601,27 +611,27 @@ public class LoginActivity extends BaseActivity { public void run() { String message; - if( e.getLocalizedMessage() != null && e.getLocalizedMessage().trim().length() > 0) + if (e.getLocalizedMessage() != null && e.getLocalizedMessage().trim().length() > 0) message = e.getLocalizedMessage(); else if (e.getMessage() != null && e.getMessage().trim().length() > 0) message = e.getMessage(); else message = getString(R.string.client_error); - Toasty.error(getApplicationContext(), message,Toast.LENGTH_LONG).show(); + Toasty.error(getApplicationContext(), message, Toast.LENGTH_LONG).show(); } }); } } }).start(); - }else{ + } else { connectionButton.setEnabled(true); } connectionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { connectionButton.setEnabled(false); - if( client_id_for_webview ){ + if (client_id_for_webview) { client_id_for_webview = false; retrievesClientId(); return; @@ -629,7 +639,7 @@ public class LoginActivity extends BaseActivity { final HashMap parameters = new HashMap<>(); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); - if( socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.GNU) { + if (socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.GNU) { parameters.put(Helper.CLIENT_ID, sharedpreferences.getString(Helper.CLIENT_ID, null)); parameters.put(Helper.CLIENT_SECRET, sharedpreferences.getString(Helper.CLIENT_SECRET, null)); } @@ -645,15 +655,15 @@ public class LoginActivity extends BaseActivity { parameters.put("password", login_passwd.getText().toString()); } String oauthUrl = null; - if( socialNetwork == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { + if (socialNetwork == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { parameters.put("scope", " read write follow"); oauthUrl = "/oauth/token"; - }else if( socialNetwork == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) { + } else if (socialNetwork == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) { oauthUrl = "/oauth/token"; - }else if( socialNetwork == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { + } else if (socialNetwork == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { parameters.put("scope", "user"); oauthUrl = "/api/v1/users/token"; - }else if( socialNetwork == UpdateAccountInfoAsyncTask.SOCIAL.GNU) { + } else if (socialNetwork == UpdateAccountInfoAsyncTask.SOCIAL.GNU) { String instanceFromField = login_instance.getText().toString().trim(); String host; try { @@ -663,7 +673,7 @@ public class LoginActivity extends BaseActivity { host = instanceFromField; } try { - instance = URLEncoder.encode(host, "utf-8"); + instance = URLEncoder.encode(host, "utf-8"); } catch (UnsupportedEncodingException e) { } String username = login_uid.getText().toString().trim().toLowerCase(); @@ -673,15 +683,15 @@ public class LoginActivity extends BaseActivity { basicAuth = "Basic " + new String(android.util.Base64.encode(userpass.getBytes(), android.util.Base64.NO_WRAP)); } String finalOauthUrl = oauthUrl; - new Thread(new Runnable(){ + new Thread(new Runnable() { @Override public void run() { try { String response; - if( socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.GNU) - response = new HttpsConnection(LoginActivity.this, instance).post(Helper.instanceWithProtocol(getApplicationContext(),instance) + finalOauthUrl, 30, parameters, null ); + if (socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.GNU) + response = new HttpsConnection(LoginActivity.this, instance).post(Helper.instanceWithProtocol(getApplicationContext(), instance) + finalOauthUrl, 30, parameters, null); else { - response = new HttpsConnection(LoginActivity.this, instance).get(Helper.instanceWithProtocol(getApplicationContext(),instance) + finalOauthUrl, 30, null, basicAuth); + response = new HttpsConnection(LoginActivity.this, instance).get(Helper.instanceWithProtocol(getApplicationContext(), instance) + finalOauthUrl, 30, null, basicAuth); } runOnUiThread(new Runnable() { public void run() { @@ -702,7 +712,7 @@ public class LoginActivity extends BaseActivity { } catch (JSONException ignored) { ignored.printStackTrace(); } - }else{ + } else { try { resobj = new JSONObject(response); Account account = GNUAPI.parseAccountResponse(LoginActivity.this, resobj); @@ -719,10 +729,10 @@ public class LoginActivity extends BaseActivity { editor.putBoolean(Helper.PREF_IS_ADMINISTRATOR, account.isAdmin()); editor.putString(Helper.PREF_INSTANCE, instance); editor.apply(); - if( userExists) + if (userExists) new AccountDAO(LoginActivity.this, db).updateAccount(account); else { - if( account.getUsername() != null && account.getCreated_at() != null) + if (account.getUsername() != null && account.getCreated_at() != null) new AccountDAO(LoginActivity.this, db).insertAccount(account); } editor.apply(); @@ -738,7 +748,7 @@ public class LoginActivity extends BaseActivity { } } }); - }catch (final Exception e) { + } catch (final Exception e) { e.printStackTrace(); runOnUiThread(new Runnable() { public void run() { @@ -746,13 +756,13 @@ public class LoginActivity extends BaseActivity { runOnUiThread(new Runnable() { public void run() { String message; - if( e.getLocalizedMessage() != null && e.getLocalizedMessage().trim().length() > 0) + if (e.getLocalizedMessage() != null && e.getLocalizedMessage().trim().length() > 0) message = e.getLocalizedMessage(); else if (e.getMessage() != null && e.getMessage().trim().length() > 0) message = e.getMessage(); else message = getString(R.string.client_error); - Toasty.error(getApplicationContext(), message,Toast.LENGTH_LONG).show(); + Toasty.error(getApplicationContext(), message, Toast.LENGTH_LONG).show(); } }); } @@ -765,30 +775,29 @@ public class LoginActivity extends BaseActivity { } + private void manageClient(String client_id, String client_secret, String id) { - private void manageClient(String client_id, String client_secret, String id){ - - SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putString(Helper.CLIENT_ID, client_id); - editor.putString(Helper.CLIENT_SECRET, client_secret); - editor.putString(Helper.ID, id); - editor.apply(); - connectionButton.setEnabled(true); - if( client_id_for_webview){ - boolean embedded_browser = sharedpreferences.getBoolean(Helper.SET_EMBEDDED_BROWSER, true); - if( embedded_browser) { - Intent i = new Intent(LoginActivity.this, WebviewConnectActivity.class); - i.putExtra("social", socialNetwork); - i.putExtra("instance", instance); - startActivity(i); - }else{ - String url = redirectUserToAuthorizeAndLogin(getApplicationContext(), socialNetwork, client_id, instance); + SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putString(Helper.CLIENT_ID, client_id); + editor.putString(Helper.CLIENT_SECRET, client_secret); + editor.putString(Helper.ID, id); + editor.apply(); + connectionButton.setEnabled(true); + if (client_id_for_webview) { + boolean embedded_browser = sharedpreferences.getBoolean(Helper.SET_EMBEDDED_BROWSER, true); + if (embedded_browser) { + Intent i = new Intent(LoginActivity.this, WebviewConnectActivity.class); + i.putExtra("social", socialNetwork); + i.putExtra("instance", instance); + startActivity(i); + } else { + String url = redirectUserToAuthorizeAndLogin(getApplicationContext(), socialNetwork, client_id, instance); - Helper.openBrowser(LoginActivity.this, url); - } + Helper.openBrowser(LoginActivity.this, url); } + } } @Override @@ -814,27 +823,27 @@ public class LoginActivity extends BaseActivity { if (id == R.id.action_about) { Intent intent = new Intent(getApplicationContext(), AboutActivity.class); startActivity(intent); - }else if(id == R.id.action_privacy){ + } else if (id == R.id.action_privacy) { Intent intent = new Intent(getApplicationContext(), PrivacyActivity.class); startActivity(intent); - }else if(id == R.id.action_proxy){ + } else if (id == R.id.action_proxy) { Intent intent = new Intent(getApplicationContext(), ProxyActivity.class); startActivity(intent); - }else if(id == R.id.action_custom_tabs){ + } else if (id == R.id.action_custom_tabs) { item.setChecked(!item.isChecked()); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putBoolean(Helper.SET_EMBEDDED_BROWSER, !item.isChecked()); editor.apply(); return false; - }else if(id == R.id.action_provider){ + } else if (id == R.id.action_provider) { item.setChecked(!item.isChecked()); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putBoolean(Helper.SET_SECURITY_PROVIDER, item.isChecked()); editor.apply(); return false; - }else if(id == R.id.action_import_data){ + } else if (id == R.id.action_import_data) { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { if (ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { @@ -851,11 +860,11 @@ public class LoginActivity extends BaseActivity { String[] mimetypes = {"*/*"}; intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes); startActivityForResult(intent, PICK_IMPORT); - }else { + } else { intent.setType("*/*"); Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); Intent chooserIntent = Intent.createChooser(intent, getString(R.string.toot_select_import)); - chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent}); + chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{pickIntent}); startActivityForResult(chooserIntent, PICK_IMPORT); } } @@ -869,26 +878,26 @@ public class LoginActivity extends BaseActivity { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_IMPORT && resultCode == RESULT_OK) { if (data == null || data.getData() == null) { - Toasty.error(getApplicationContext(),getString(R.string.toot_select_file_error),Toast.LENGTH_LONG).show(); + Toasty.error(getApplicationContext(), getString(R.string.toot_select_file_error), Toast.LENGTH_LONG).show(); return; } String filename = Helper.getFilePathFromURI(getApplicationContext(), data.getData()); Sqlite.importDB(LoginActivity.this, filename); - }else{ - Toasty.error(getApplicationContext(),getString(R.string.toot_select_file_error),Toast.LENGTH_LONG).show(); + } else { + Toasty.error(getApplicationContext(), getString(R.string.toot_select_file_error), Toast.LENGTH_LONG).show(); } } public static String redirectUserToAuthorizeAndLogin(Context context, UpdateAccountInfoAsyncTask.SOCIAL socialNetwork, String clientId, String instance) { - String queryString = Helper.CLIENT_ID + "="+ clientId; - queryString += "&" + Helper.REDIRECT_URI + "="+ Uri.encode(Helper.REDIRECT_CONTENT_WEB); - queryString += "&" + Helper.RESPONSE_TYPE +"=code"; - if( socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED ) { + String queryString = Helper.CLIENT_ID + "=" + clientId; + queryString += "&" + Helper.REDIRECT_URI + "=" + Uri.encode(Helper.REDIRECT_CONTENT_WEB); + queryString += "&" + Helper.RESPONSE_TYPE + "=code"; + if (socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) { - if( admin ) { + if (admin) { queryString += "&" + Helper.SCOPE + "=" + Helper.OAUTH_SCOPES_ADMIN; - }else{ + } else { queryString += "&" + Helper.SCOPE + "=" + Helper.OAUTH_SCOPES; } } @@ -896,8 +905,7 @@ public class LoginActivity extends BaseActivity { } - - private void showcaseInstance(final boolean loop){ + private void showcaseInstance(final boolean loop) { BubbleShowCaseBuilder showCaseBuilder = new BubbleShowCaseBuilder(LoginActivity.this) .title(getString(R.string.instance)) .description(getString(R.string.showcase_instance)) @@ -906,35 +914,36 @@ public class LoginActivity extends BaseActivity { .textColor(Color.WHITE) .titleTextSize(14) .descriptionTextSize(12); - if( loop) - showCaseBuilder.showOnce("BUBBLE_SHOW_CASE_INSTANCE_ID"); - showCaseBuilder.listener(new BubbleShowCaseListener (){ - @Override - public void onTargetClick(BubbleShowCase bubbleShowCase) { - if( loop) { - bubbleShowCase.finishSequence(); - } - } - @Override - public void onCloseActionImageClick(BubbleShowCase bubbleShowCase) { - if(loop) { - bubbleShowCase.finishSequence(); - } - } + if (loop) + showCaseBuilder.showOnce("BUBBLE_SHOW_CASE_INSTANCE_ID"); + showCaseBuilder.listener(new BubbleShowCaseListener() { + @Override + public void onTargetClick(BubbleShowCase bubbleShowCase) { + if (loop) { + bubbleShowCase.finishSequence(); + } + } - @Override - public void onBubbleClick(BubbleShowCase bubbleShowCase) { + @Override + public void onCloseActionImageClick(BubbleShowCase bubbleShowCase) { + if (loop) { + bubbleShowCase.finishSequence(); + } + } - } + @Override + public void onBubbleClick(BubbleShowCase bubbleShowCase) { - @Override - public void onBackgroundDimClick(BubbleShowCase bubbleShowCase) { + } - } + @Override + public void onBackgroundDimClick(BubbleShowCase bubbleShowCase) { - }) - .targetView(login_instance) - .show(); + } + + }) + .targetView(login_instance) + .show(); } } \ No newline at end of file diff --git a/app/src/main/java/app/fedilab/android/activities/MainApplication.java b/app/src/main/java/app/fedilab/android/activities/MainApplication.java index 500133795..e3a8d93f6 100644 --- a/app/src/main/java/app/fedilab/android/activities/MainApplication.java +++ b/app/src/main/java/app/fedilab/android/activities/MainApplication.java @@ -19,6 +19,7 @@ import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.StrictMode; + import androidx.multidex.MultiDex; import androidx.multidex.MultiDexApplication; import androidx.core.content.ContextCompat; @@ -56,7 +57,7 @@ import static app.fedilab.android.helper.Helper.initNetCipher; */ @AcraNotification( - resIcon = R.mipmap.ic_launcher, resTitle = R.string.crash_title, resChannelName = R.string.set_crash_reports, resText = R.string.crash_message) + resIcon = R.mipmap.ic_launcher, resTitle = R.string.crash_title, resChannelName = R.string.set_crash_reports, resText = R.string.crash_message) public class MainApplication extends MultiDexApplication { @@ -79,24 +80,25 @@ public class MainApplication extends MultiDexApplication { List SUPPORTED_LOCALES = new ArrayList<>(); String defaultLocaleString = sharedpreferences.getString(Helper.SET_DEFAULT_LOCALE_NEW, null); - if( defaultLocaleString != null){ + if (defaultLocaleString != null) { Locale defaultLocale; - if( defaultLocaleString.equals("zh-CN")) + if (defaultLocaleString.equals("zh-CN")) defaultLocale = Locale.SIMPLIFIED_CHINESE; - else if( defaultLocaleString.equals("zh-TW")) + else if (defaultLocaleString.equals("zh-TW")) defaultLocale = Locale.TRADITIONAL_CHINESE; else defaultLocale = new Locale(defaultLocaleString); SUPPORTED_LOCALES.add(defaultLocale); - }else { + } else { SUPPORTED_LOCALES.add(Locale.getDefault()); } LocaleChanger.initialize(getApplicationContext(), SUPPORTED_LOCALES); - }catch (Exception ignored){} + } catch (Exception ignored) { + } boolean send_crash_reports = sharedpreferences.getBoolean(Helper.SET_SEND_CRASH_REPORTS, false); - if( send_crash_reports) { + if (send_crash_reports) { CoreConfigurationBuilder ACRABuilder = new CoreConfigurationBuilder(this); ACRABuilder.setBuildConfigClass(BuildConfig.class).setReportFormat(StringFormat.KEY_VALUE_LIST); String version = ""; @@ -117,19 +119,17 @@ public class MainApplication extends MultiDexApplication { Toasty.Config.getInstance() .allowQueue(false) .apply(); - Toasty.Config.getInstance().apply(); - } - + Toasty.Config.getInstance().apply(); + } @Override - protected void attachBaseContext(Context base) - { + protected void attachBaseContext(Context base) { super.attachBaseContext(base); MultiDex.install(MainApplication.this); } - public static MainApplication getApp(){ + public static MainApplication getApp() { return app; } } diff --git a/app/src/main/java/app/fedilab/android/activities/ManageAccountsInListActivity.java b/app/src/main/java/app/fedilab/android/activities/ManageAccountsInListActivity.java index 4dcb0e95b..847ac1221 100644 --- a/app/src/main/java/app/fedilab/android/activities/ManageAccountsInListActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/ManageAccountsInListActivity.java @@ -17,9 +17,11 @@ package app.fedilab.android.activities; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; + import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; + import android.text.Editable; import android.text.TextWatcher; import android.view.MenuItem; @@ -45,7 +47,6 @@ import app.fedilab.android.asynctasks.ManageListsAsyncTask; import app.fedilab.android.interfaces.OnListActionInterface; - /** * Created by Thomas on 15/12/2017. * Manage accounts in Lists @@ -68,7 +69,7 @@ public class ManageAccountsInListActivity extends BaseActivity implements OnList requestWindowFeature(Window.FEATURE_NO_TITLE); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme_NoActionBar_Fedilab); getWindow().getDecorView().setBackgroundColor(ContextCompat.getColor(ManageAccountsInListActivity.this, R.color.mastodonC3__)); @@ -87,15 +88,15 @@ public class ManageAccountsInListActivity extends BaseActivity implements OnList } setContentView(R.layout.activity_manage_accounts_list); getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().hide(); Bundle b = getIntent().getExtras(); - if(b != null){ + if (b != null) { title = b.getString("title"); listId = b.getString("id"); - }else{ - Toasty.error(getApplicationContext(),getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + } else { + Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); } main_account_container = findViewById(R.id.main_account_container); @@ -113,7 +114,6 @@ public class ManageAccountsInListActivity extends BaseActivity implements OnList lv_accounts_current.setLayoutManager(mLayoutManager); - list_title.setText(title); loader.setVisibility(View.VISIBLE); new ManageListsAsyncTask(ManageAccountsInListActivity.this, ManageListsAsyncTask.action.GET_LIST_ACCOUNT, null, null, listId, null, ManageAccountsInListActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); @@ -121,20 +121,23 @@ public class ManageAccountsInListActivity extends BaseActivity implements OnList search_account.addTextChangedListener(new TextWatcher() { @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) {} + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } + @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (count > 0) { search_account.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_close, 0); - }else{ + } else { search_account.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_search, 0); } } + @Override public void afterTextChanged(Editable s) { - if( s != null && s.length() > 0){ - new ManageListsAsyncTask(ManageAccountsInListActivity.this, s.toString(), ManageAccountsInListActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else{ + if (s != null && s.length() > 0) { + new ManageListsAsyncTask(ManageAccountsInListActivity.this, s.toString(), ManageAccountsInListActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + } else { lv_accounts_search.setVisibility(View.GONE); lv_accounts_current.setVisibility(View.VISIBLE); } @@ -156,9 +159,9 @@ public class ManageAccountsInListActivity extends BaseActivity implements OnList }); } - public void addAccount(Account account){ + public void addAccount(Account account) { search_account.setText(""); - accounts.add(0,account); + accounts.add(0, account); accountsInAListAdapter.notifyItemInserted(0); } @@ -175,16 +178,15 @@ public class ManageAccountsInListActivity extends BaseActivity implements OnList } - @Override public void onActionDone(ManageListsAsyncTask.action actionType, APIResponse apiResponse, int statusCode) { loader.setVisibility(View.GONE); main_account_container.setVisibility(View.VISIBLE); - if( apiResponse.getError() != null){ - Toasty.error(getApplicationContext(), apiResponse.getError().getError(),Toast.LENGTH_LONG).show(); + if (apiResponse.getError() != null) { + Toasty.error(getApplicationContext(), apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); return; } - if( actionType == ManageListsAsyncTask.action.GET_LIST_ACCOUNT){ + if (actionType == ManageListsAsyncTask.action.GET_LIST_ACCOUNT) { if (apiResponse.getAccounts() != null && apiResponse.getAccounts().size() > 0) { this.accounts.addAll(apiResponse.getAccounts()); accountsInAListAdapter.notifyDataSetChanged(); @@ -192,7 +194,7 @@ public class ManageAccountsInListActivity extends BaseActivity implements OnList lv_accounts_current.setVisibility(View.VISIBLE); } - }else if( actionType == ManageListsAsyncTask.action.SEARCH_USER){ + } else if (actionType == ManageListsAsyncTask.action.SEARCH_USER) { if (apiResponse.getAccounts() != null && apiResponse.getAccounts().size() > 0) { java.util.List accountsSearch = new ArrayList<>(); accountsSearch.addAll(apiResponse.getAccounts()); diff --git a/app/src/main/java/app/fedilab/android/activities/MastodonRegisterActivity.java b/app/src/main/java/app/fedilab/android/activities/MastodonRegisterActivity.java index 105c0494e..dfb06285a 100644 --- a/app/src/main/java/app/fedilab/android/activities/MastodonRegisterActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/MastodonRegisterActivity.java @@ -40,13 +40,16 @@ import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; + import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.Toolbar; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; + import com.jaredrummler.materialspinner.MaterialSpinner; + import java.io.IOException; import java.lang.ref.WeakReference; import java.net.HttpURLConnection; @@ -85,7 +88,7 @@ public class MastodonRegisterActivity extends BaseActivity implements OnRetrieve SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme); break; @@ -101,7 +104,7 @@ public class MastodonRegisterActivity extends BaseActivity implements OnRetrieve setContentView(R.layout.activity_register); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null ) { + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); assert inflater != null; View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); @@ -116,14 +119,13 @@ public class MastodonRegisterActivity extends BaseActivity implements OnRetrieve } }); toolbar_title.setText(R.string.sign_up); - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Toolbar toolbar = actionBar.getCustomView().findViewById(R.id.toolbar); Helper.colorizeToolbar(toolbar, R.color.black, MastodonRegisterActivity.this); } } - MaterialSpinner reg_category = findViewById(R.id.reg_category); Helper.changeMaterialSpinnerColor(MastodonRegisterActivity.this, reg_category); String[] categoriesA = { @@ -178,26 +180,26 @@ public class MastodonRegisterActivity extends BaseActivity implements OnRetrieve CheckBox agreement = findViewById(R.id.agreement); error_message = findViewById(R.id.error_message); - signup.setOnClickListener(view->{ + signup.setOnClickListener(view -> { error_message.setVisibility(View.GONE); - if( username.getText().toString().trim().length() == 0 || email.getText().toString().trim().length() == 0 || - password.getText().toString().trim().length() == 0 || password_confirm.getText().toString().trim().length() == 0 || !agreement.isChecked()){ + if (username.getText().toString().trim().length() == 0 || email.getText().toString().trim().length() == 0 || + password.getText().toString().trim().length() == 0 || password_confirm.getText().toString().trim().length() == 0 || !agreement.isChecked()) { Toasty.error(getApplicationContext(), getString(R.string.all_field_filled)).show(); return; } - if(!password.getText().toString().trim().equals(password_confirm.getText().toString().trim())){ + if (!password.getText().toString().trim().equals(password_confirm.getText().toString().trim())) { Toasty.error(getApplicationContext(), getString(R.string.password_error)).show(); return; } - if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email.getText().toString().trim()).matches()){ + if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email.getText().toString().trim()).matches()) { Toasty.error(getApplicationContext(), getString(R.string.email_error)).show(); return; } - if(password.getText().toString().trim().length() < 8 ){ + if (password.getText().toString().trim().length() < 8) { Toasty.error(getApplicationContext(), getString(R.string.password_too_short)).show(); return; } - if(username.getText().toString().matches("[a-zA-Z0-9_]")){ + if (username.getText().toString().matches("[a-zA-Z0-9_]")) { Toasty.error(getApplicationContext(), getString(R.string.username_error)).show(); return; } @@ -214,13 +216,13 @@ public class MastodonRegisterActivity extends BaseActivity implements OnRetrieve } @Override - protected void onResume(){ + protected void onResume() { super.onResume(); } @Override public void onRetrieveInstance(APIResponse apiResponse) { - if( apiResponse.getError() != null ){ + if (apiResponse.getError() != null) { Toasty.error(getApplicationContext(), getString(R.string.toast_error_instance_reg), Toast.LENGTH_LONG).show(); return; } @@ -235,7 +237,7 @@ public class MastodonRegisterActivity extends BaseActivity implements OnRetrieve } - public void pickupInstance(String instance){ + public void pickupInstance(String instance) { checkInstance(MastodonRegisterActivity.this, instance); LinearLayout form_container = findViewById(R.id.form_container); @@ -262,13 +264,13 @@ public class MastodonRegisterActivity extends BaseActivity implements OnRetrieve change.setSpan(new UnderlineSpan(), 0, change.length(), 0); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if( theme == Helper.THEME_DARK) + if (theme == Helper.THEME_DARK) change.setSpan(new ForegroundColorSpan(ContextCompat.getColor(MastodonRegisterActivity.this, R.color.dark_link_toot)), 0, change.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); - else if( theme == Helper.THEME_BLACK) + else if (theme == Helper.THEME_BLACK) change.setSpan(new ForegroundColorSpan(ContextCompat.getColor(MastodonRegisterActivity.this, R.color.black_link_toot)), 0, change.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); - else if( theme == Helper.THEME_LIGHT) + else if (theme == Helper.THEME_LIGHT) change.setSpan(new ForegroundColorSpan(ContextCompat.getColor(MastodonRegisterActivity.this, R.color.mastodonC4)), 0, change.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); change_instance.setText(change); @@ -295,35 +297,35 @@ public class MastodonRegisterActivity extends BaseActivity implements OnRetrieve String tos = getString(R.string.tos); String serverrules = getString(R.string.server_rules); String content_agreement = getString(R.string.agreement_check, - ""+serverrules +"", - ""+tos +"" - ); + "" + serverrules + "", + "" + tos + "" + ); agreement_text.setMovementMethod(LinkMovementMethod.getInstance()); agreement_text.setText(Html.fromHtml(content_agreement)); } - private void checkInstance(Context context, String instance){ + private void checkInstance(Context context, String instance) { new checkRegistration(context, instance).executeOnExecutor(THREAD_POOL_EXECUTOR); } @Override public void onPostStatusAction(APIResponse apiResponse) { - if( apiResponse.getError() != null){ + if (apiResponse.getError() != null) { String errorMessage; - if( apiResponse.getError().getError() != null){ - try{ + if (apiResponse.getError().getError() != null) { + try { String[] resp = apiResponse.getError().getError().split(":"); - if( resp.length == 2) + if (resp.length == 2) errorMessage = apiResponse.getError().getError().split(":")[1]; - else if( resp.length == 3) + else if (resp.length == 3) errorMessage = apiResponse.getError().getError().split(":")[2]; else errorMessage = getString(R.string.toast_error); - }catch (Exception e){ + } catch (Exception e) { errorMessage = getString(R.string.toast_error); } - }else { + } else { errorMessage = getString(R.string.toast_error); } error_message.setText(errorMessage); @@ -336,16 +338,16 @@ public class MastodonRegisterActivity extends BaseActivity implements OnRetrieve int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MastodonRegisterActivity.this, style); dialogBuilder.setCancelable(false); dialogBuilder.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog,int which) { + public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); finish(); } @@ -363,7 +365,7 @@ public class MastodonRegisterActivity extends BaseActivity implements OnRetrieve private String instance; private WeakReference weakReference; - checkRegistration(Context context, String instance){ + checkRegistration(Context context, String instance) { this.instance = instance; this.weakReference = new WeakReference<>(context); } @@ -376,7 +378,7 @@ public class MastodonRegisterActivity extends BaseActivity implements OnRetrieve HttpURLConnection connection = (HttpURLConnection) url.openConnection(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { java.util.Scanner s = new java.util.Scanner(connection.getInputStream()).useDelimiter("\\A"); - response = s.hasNext() ? s.next() : ""; + response = s.hasNext() ? s.next() : ""; } } catch (IOException e) { e.printStackTrace(); @@ -388,9 +390,9 @@ public class MastodonRegisterActivity extends BaseActivity implements OnRetrieve protected void onPostExecute(String result) { - if( result != null && result.contains("invite_request_attributes")){ - TextView invitation = ((MastodonRegisterActivity)(weakReference.get())).findViewById(R.id.invitation); - if( invitation != null){ + if (result != null && result.contains("invite_request_attributes")) { + TextView invitation = ((MastodonRegisterActivity) (weakReference.get())).findViewById(R.id.invitation); + if (invitation != null) { invitation.setVisibility(View.VISIBLE); } } diff --git a/app/src/main/java/app/fedilab/android/activities/MastodonShareRegisterActivity.java b/app/src/main/java/app/fedilab/android/activities/MastodonShareRegisterActivity.java index 7c4acba4a..c9684134d 100644 --- a/app/src/main/java/app/fedilab/android/activities/MastodonShareRegisterActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/MastodonShareRegisterActivity.java @@ -80,7 +80,7 @@ public class MastodonShareRegisterActivity extends BaseActivity implements OnRet SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme); break; @@ -96,7 +96,7 @@ public class MastodonShareRegisterActivity extends BaseActivity implements OnRet setContentView(R.layout.activity_register); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null ) { + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); assert inflater != null; View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); @@ -111,12 +111,12 @@ public class MastodonShareRegisterActivity extends BaseActivity implements OnRet } }); toolbar_title.setText(R.string.sign_up); - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Toolbar toolbar = actionBar.getCustomView().findViewById(R.id.toolbar); Helper.colorizeToolbar(toolbar, R.color.black, MastodonShareRegisterActivity.this); } } - if( this.getIntent() == null || this.getIntent().getData() == null){ + if (this.getIntent() == null || this.getIntent().getData() == null) { Intent mainActivity = new Intent(MastodonShareRegisterActivity.this, MastodonRegisterActivity.class); startActivity(mainActivity); finish(); @@ -125,12 +125,12 @@ public class MastodonShareRegisterActivity extends BaseActivity implements OnRet assert data != null; String[] splitURL = data.toString().split("registration_helper"); - if( splitURL.length < 2 || splitURL[1] == null || splitURL[1].length() == 1){ + if (splitURL.length < 2 || splitURL[1] == null || splitURL[1].length() == 1) { Intent mainActivity = new Intent(MastodonShareRegisterActivity.this, MastodonRegisterActivity.class); startActivity(mainActivity); finish(); } - String instance = splitURL[1].replace("/",""); + String instance = splitURL[1].replace("/", ""); pickupInstance(instance); @@ -148,26 +148,26 @@ public class MastodonShareRegisterActivity extends BaseActivity implements OnRet CheckBox agreement = findViewById(R.id.agreement); error_message = findViewById(R.id.error_message); - signup.setOnClickListener(view->{ + signup.setOnClickListener(view -> { error_message.setVisibility(View.GONE); - if( username.getText().toString().trim().length() == 0 || email.getText().toString().trim().length() == 0 || - password.getText().toString().trim().length() == 0 || password_confirm.getText().toString().trim().length() == 0 || !agreement.isChecked()){ + if (username.getText().toString().trim().length() == 0 || email.getText().toString().trim().length() == 0 || + password.getText().toString().trim().length() == 0 || password_confirm.getText().toString().trim().length() == 0 || !agreement.isChecked()) { Toasty.error(getApplicationContext(), getString(R.string.all_field_filled)).show(); return; } - if(!password.getText().toString().trim().equals(password_confirm.getText().toString().trim())){ + if (!password.getText().toString().trim().equals(password_confirm.getText().toString().trim())) { Toasty.error(getApplicationContext(), getString(R.string.password_error)).show(); return; } - if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email.getText().toString().trim()).matches()){ + if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email.getText().toString().trim()).matches()) { Toasty.error(getApplicationContext(), getString(R.string.email_error)).show(); return; } - if(password.getText().toString().trim().length() < 8 ){ + if (password.getText().toString().trim().length() < 8) { Toasty.error(getApplicationContext(), getString(R.string.password_too_short)).show(); return; } - if(username.getText().toString().matches("[a-zA-Z0-9_]")){ + if (username.getText().toString().matches("[a-zA-Z0-9_]")) { Toasty.error(getApplicationContext(), getString(R.string.username_error)).show(); return; } @@ -184,13 +184,13 @@ public class MastodonShareRegisterActivity extends BaseActivity implements OnRet } @Override - protected void onResume(){ + protected void onResume() { super.onResume(); } @Override public void onRetrieveInstance(APIResponse apiResponse) { - if( apiResponse.getError() != null ){ + if (apiResponse.getError() != null) { Toasty.error(getApplicationContext(), getString(R.string.toast_error_instance_reg), Toast.LENGTH_LONG).show(); return; } @@ -205,7 +205,7 @@ public class MastodonShareRegisterActivity extends BaseActivity implements OnRet } - public void pickupInstance(String instance){ + public void pickupInstance(String instance) { checkInstance(MastodonShareRegisterActivity.this, instance); @@ -223,35 +223,35 @@ public class MastodonShareRegisterActivity extends BaseActivity implements OnRet String tos = getString(R.string.tos); String serverrules = getString(R.string.server_rules); String content_agreement = getString(R.string.agreement_check, - ""+serverrules +"", - ""+tos +"" - ); + "" + serverrules + "", + "" + tos + "" + ); agreement_text.setMovementMethod(LinkMovementMethod.getInstance()); agreement_text.setText(Html.fromHtml(content_agreement)); } - private void checkInstance(Context context, String instance){ + private void checkInstance(Context context, String instance) { new checkRegistration(context, instance).executeOnExecutor(THREAD_POOL_EXECUTOR); } @Override public void onPostStatusAction(APIResponse apiResponse) { - if( apiResponse.getError() != null){ + if (apiResponse.getError() != null) { String errorMessage; - if( apiResponse.getError().getError() != null){ - try{ + if (apiResponse.getError().getError() != null) { + try { String[] resp = apiResponse.getError().getError().split(":"); - if( resp.length == 2) + if (resp.length == 2) errorMessage = apiResponse.getError().getError().split(":")[1]; - else if( resp.length == 3) + else if (resp.length == 3) errorMessage = apiResponse.getError().getError().split(":")[2]; else errorMessage = getString(R.string.toast_error); - }catch (Exception e){ + } catch (Exception e) { errorMessage = getString(R.string.toast_error); } - }else { + } else { errorMessage = getString(R.string.toast_error); } error_message.setText(errorMessage); @@ -264,16 +264,16 @@ public class MastodonShareRegisterActivity extends BaseActivity implements OnRet int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MastodonShareRegisterActivity.this, style); dialogBuilder.setCancelable(false); dialogBuilder.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog,int which) { + public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); finish(); } @@ -291,7 +291,7 @@ public class MastodonShareRegisterActivity extends BaseActivity implements OnRet private String instance; private WeakReference weakReference; - checkRegistration(Context context, String instance){ + checkRegistration(Context context, String instance) { this.instance = instance; this.weakReference = new WeakReference<>(context); } @@ -304,7 +304,7 @@ public class MastodonShareRegisterActivity extends BaseActivity implements OnRet HttpURLConnection connection = (HttpURLConnection) url.openConnection(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { java.util.Scanner s = new java.util.Scanner(connection.getInputStream()).useDelimiter("\\A"); - response = s.hasNext() ? s.next() : ""; + response = s.hasNext() ? s.next() : ""; } } catch (IOException e) { e.printStackTrace(); @@ -316,9 +316,9 @@ public class MastodonShareRegisterActivity extends BaseActivity implements OnRet protected void onPostExecute(String result) { - if( result != null && result.contains("invite_request_attributes")){ - TextView invitation = ((MastodonShareRegisterActivity)(weakReference.get())).findViewById(R.id.invitation); - if( invitation != null){ + if (result != null && result.contains("invite_request_attributes")) { + TextView invitation = ((MastodonShareRegisterActivity) (weakReference.get())).findViewById(R.id.invitation); + if (invitation != null) { invitation.setVisibility(View.VISIBLE); } } diff --git a/app/src/main/java/app/fedilab/android/activities/MediaActivity.java b/app/src/main/java/app/fedilab/android/activities/MediaActivity.java index dd9cfcf1d..6f8f793f2 100644 --- a/app/src/main/java/app/fedilab/android/activities/MediaActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/MediaActivity.java @@ -25,6 +25,7 @@ import android.media.MediaPlayer; import android.net.Uri; import android.os.Build; import android.os.Bundle; + import androidx.annotation.NonNull; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; @@ -97,7 +98,7 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, private RelativeLayout loader; - private ArrayList attachments; + private ArrayList attachments; private PhotoView imageView; private SimpleExoPlayerView videoView; private float downX; @@ -126,13 +127,14 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, private ImageButton playView; private GLAudioVisualizationView visualizerView; - private enum actionSwipe{ + private enum actionSwipe { RIGHT_TO_LEFT, LEFT_TO_RIGHT, POP } + private WebView webview_video; - private ImageButton media_save,media_share, media_close; + private ImageButton media_save, media_share, media_close; private boolean scheduleHidden, scheduleHiddenDescription; private SimpleExoPlayer player; private boolean isSHaring; @@ -148,7 +150,7 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, protected void onCreate(Bundle savedInstanceState) { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if( theme == Helper.THEME_BLACK) + if (theme == Helper.THEME_BLACK) setTheme(R.style.TransparentBlack); super.onCreate(savedInstanceState); hideSystemUI(); @@ -161,12 +163,12 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, mSwipeBackLayout.setSwipeBackListener(new SwipeBackLayout.OnSwipeBackListener() { @Override public void onViewPositionChanged(View mView, float swipeBackFraction, float SWIPE_BACK_FACTOR) { - canSwipe = swipeBackFraction<0.1; + canSwipe = swipeBackFraction < 0.1; } @Override public void onViewSwipeFinished(View mView, boolean isEnd) { - if(!isEnd) + if (!isEnd) canSwipe = true; else { finish(); @@ -178,17 +180,17 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, instance = Helper.getLiveInstance(MediaActivity.this); mSwipeBackLayout.attachToActivity(this); attachments = getIntent().getParcelableArrayListExtra("mediaArray"); - if( getIntent().getExtras() != null) + if (getIntent().getExtras() != null) mediaPosition = getIntent().getExtras().getInt("position", 1); - if( attachments == null || attachments.size() == 0) + if (attachments == null || attachments.size() == 0) finish(); RelativeLayout main_container_media = findViewById(R.id.main_container_media); - if( theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { main_container_media.setBackgroundResource(R.color.mastodonC2); - }else if( theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { main_container_media.setBackgroundResource(R.color.black); - }else if( theme == Helper.THEME_DARK){ + } else if (theme == Helper.THEME_DARK) { main_container_media.setBackgroundResource(R.color.mastodonC1_); } media_description = findViewById(R.id.media_description); @@ -203,13 +205,13 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, @Override public void onClick(View view) { isSHaring = false; - if(attachment.getType().toLowerCase().equals("video") || attachment.getType().toLowerCase().equals("audio") || attachment.getType().toLowerCase().equals("gifv") || attachment.getType().toLowerCase().equals("web")) { - if( attachment != null ) { + if (attachment.getType().toLowerCase().equals("video") || attachment.getType().toLowerCase().equals("audio") || attachment.getType().toLowerCase().equals("gifv") || attachment.getType().toLowerCase().equals("web")) { + if (attachment != null) { progress.setText("0 %"); progress.setVisibility(View.VISIBLE); new HttpsConnection(MediaActivity.this, instance).download(attachment.getUrl(), MediaActivity.this); } - }else { + } else { if (Build.VERSION.SDK_INT >= 23) { if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MediaActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, Helper.EXTERNAL_STORAGE_REQUEST_CODE); @@ -226,13 +228,13 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, @Override public void onClick(View view) { isSHaring = true; - if(attachment.getType().toLowerCase().equals("video") || attachment.getType().toLowerCase().equals("audio") ||attachment.getType().toLowerCase().equals("gifv")) { - if( attachment != null ) { + if (attachment.getType().toLowerCase().equals("video") || attachment.getType().toLowerCase().equals("audio") || attachment.getType().toLowerCase().equals("gifv")) { + if (attachment != null) { progress.setText("0 %"); progress.setVisibility(View.VISIBLE); new HttpsConnection(MediaActivity.this, instance).download(attachment.getUrl(), MediaActivity.this); } - }else { + } else { if (Build.VERSION.SDK_INT >= 23) { if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MediaActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, Helper.EXTERNAL_STORAGE_REQUEST_CODE); @@ -257,13 +259,13 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, videoView = findViewById(R.id.media_video); prev = findViewById(R.id.media_prev); next = findViewById(R.id.media_next); - if( theme == Helper.THEME_BLACK){ + if (theme == Helper.THEME_BLACK) { changeDrawableColor(getApplicationContext(), prev, R.color.dark_icon); changeDrawableColor(getApplicationContext(), next, R.color.dark_icon); - }else if(theme == Helper.THEME_LIGHT) { + } else if (theme == Helper.THEME_LIGHT) { changeDrawableColor(getApplicationContext(), prev, R.color.mastodonC4); changeDrawableColor(getApplicationContext(), next, R.color.mastodonC4); - }else{ + } else { changeDrawableColor(getApplicationContext(), prev, R.color.white); changeDrawableColor(getApplicationContext(), next, R.color.white); } @@ -287,11 +289,11 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, @Override public void onMatrixChanged(RectF rect) { imageScale = imageView.getScale(); - canSwipe = (imageView.getScale() == 1 ); - mSwipeBackLayout.isDisabled(imageView.getScale() != 1 ); + canSwipe = (imageView.getScale() == 1); + mSwipeBackLayout.isDisabled(imageView.getScale() != 1); } }); - if( attachments != null && attachments.size() > 1){ + if (attachments != null && attachments.size() > 1) { prev.setVisibility(View.VISIBLE); next.setVisibility(View.VISIBLE); } @@ -313,25 +315,27 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, public void onCompletion(MediaPlayer mp) { stopPlaying(); } + /** * Manage touch event * Allows to swipe from timelines + * * @param event MotionEvent * @return boolean */ @Override public boolean dispatchTouchEvent(MotionEvent event) { Boolean thisControllShown = isControlElementShown; - switch(event.getAction()){ + switch (event.getAction()) { case MotionEvent.ACTION_DOWN: { downX = event.getX(); downY = event.getY(); //Displays navigation left/right buttons - if( attachments != null && attachments.size() > 1){ - if(thisControllShown){ + if (attachments != null && attachments.size() > 1) { + if (thisControllShown) { prev.setVisibility(View.GONE); next.setVisibility(View.GONE); - }else{ + } else { prev.setVisibility(View.VISIBLE); next.setVisibility(View.VISIBLE); } @@ -344,19 +348,31 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, float upY = event.getY(); float deltaY = downY - upY; // swipe horizontal - if( downX > MIN_DISTANCE & (Math.abs(deltaX) > MIN_DISTANCE ) ){ - if( !canSwipe || mediaPosition > attachments.size() || mediaPosition < 1 || attachments.size() <= 1) + if (downX > MIN_DISTANCE & (Math.abs(deltaX) > MIN_DISTANCE)) { + if (!canSwipe || mediaPosition > attachments.size() || mediaPosition < 1 || attachments.size() <= 1) return super.dispatchTouchEvent(event); - if(deltaX < 0) { switchOnSwipe(MediaActivity.actionSwipe.LEFT_TO_RIGHT); return true; } - if(deltaX > 0) { switchOnSwipe(MediaActivity.actionSwipe.RIGHT_TO_LEFT); return true; } - }else if(downY > MIN_DISTANCE & (Math.abs(deltaY) > MIN_DISTANCE ) ){ - if(deltaY > 0 && canSwipe) { finish(); return true; } - if(deltaY < 0 && canSwipe) { finish(); return true; } + if (deltaX < 0) { + switchOnSwipe(MediaActivity.actionSwipe.LEFT_TO_RIGHT); + return true; + } + if (deltaX > 0) { + switchOnSwipe(MediaActivity.actionSwipe.RIGHT_TO_LEFT); + return true; + } + } else if (downY > MIN_DISTANCE & (Math.abs(deltaY) > MIN_DISTANCE)) { + if (deltaY > 0 && canSwipe) { + finish(); + return true; + } + if (deltaY < 0 && canSwipe) { + finish(); + return true; + } } else { currentAction = MediaActivity.actionSwipe.POP; isControlElementShown = !isControlElementShown; if (thisControllShown) { - if(event.getY() > action_bar_container.getHeight()) { + if (event.getY() > action_bar_container.getHeight()) { hideSystemUI(); action_bar_container.setVisibility(View.GONE); if (media_description.getVisibility() == View.VISIBLE) { @@ -389,19 +405,19 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, } - private void switchOnSwipe(actionSwipe action){ + private void switchOnSwipe(actionSwipe action) { loader.setVisibility(View.VISIBLE); - mediaPosition = (action == actionSwipe.LEFT_TO_RIGHT)?mediaPosition-1:mediaPosition+1; + mediaPosition = (action == actionSwipe.LEFT_TO_RIGHT) ? mediaPosition - 1 : mediaPosition + 1; displayMediaAtPosition(action); } - private void displayMediaAtPosition(actionSwipe action){ - if( mediaPosition > attachments.size() ) + private void displayMediaAtPosition(actionSwipe action) { + if (mediaPosition > attachments.size()) mediaPosition = 1; - if( mediaPosition < 1) + if (mediaPosition < 1) mediaPosition = attachments.size(); currentAction = action; - attachment = attachments.get(mediaPosition-1); + attachment = attachments.get(mediaPosition - 1); String type = attachment.getType(); String url = attachment.getUrl(); finalUrlDownload = url; @@ -409,26 +425,26 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, imageView.setVisibility(View.GONE); - if( attachment.getDescription() != null && !attachment.getDescription().equals("null")){ + if (attachment.getDescription() != null && !attachment.getDescription().equals("null")) { media_description.setText(attachment.getDescription()); media_description.setVisibility(View.VISIBLE); - }else{ + } else { media_description.setText(""); media_description.setVisibility(View.GONE); } preview_url = attachment.getPreview_url(); - if( type.equals("unknown")){ + if (type.equals("unknown")) { preview_url = attachment.getRemote_url(); - if( preview_url.endsWith(".png") || preview_url.endsWith(".jpg")|| preview_url.endsWith(".jpeg") || preview_url.endsWith(".gif")) { + if (preview_url.endsWith(".png") || preview_url.endsWith(".jpg") || preview_url.endsWith(".jpeg") || preview_url.endsWith(".gif")) { type = "image"; - }else if( preview_url.endsWith(".mp4") || preview_url.endsWith(".mp3") ) { + } else if (preview_url.endsWith(".mp4") || preview_url.endsWith(".mp3")) { type = "video"; } url = attachment.getRemote_url(); attachment.setType(type); } final String finalUrl = url; - switch (type.toLowerCase()){ + switch (type.toLowerCase()) { case "image": pbar_inf.setScaleY(1f); imageView.setVisibility(View.VISIBLE); @@ -436,7 +452,7 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, pbar_inf.setIndeterminate(true); loader.setVisibility(View.VISIBLE); fileVideo = null; - if( !finalUrl.endsWith(".gif")) { + if (!finalUrl.endsWith(".gif")) { Glide.with(getApplicationContext()) .asBitmap() .load(preview_url).into( @@ -473,7 +489,7 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, } } ); - }else { + } else { loader.setVisibility(View.GONE); Glide.with(getApplicationContext()) .load(finalUrl).into(imageView); @@ -497,7 +513,7 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, ExtractorMediaSource videoSource = new ExtractorMediaSource.Factory(dataSourceFactory) .createMediaSource(uri); player = ExoPlayerFactory.newSimpleInstance(MediaActivity.this); - if( type.toLowerCase().equals("gifv")) + if (type.toLowerCase().equals("gifv")) player.setRepeatMode(Player.REPEAT_MODE_ONE); videoView.setPlayer(player); loader.setVisibility(View.GONE); @@ -559,9 +575,9 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, .setLayerColors(new int[]{color}) .build(); - statusView = findViewById(R.id.status); - timerView = findViewById(R.id.timer); - playView = findViewById(R.id.play); + statusView = findViewById(R.id.status); + timerView = findViewById(R.id.timer); + playView = findViewById(R.id.play); content_audio.setBackgroundColor(getDarkerColor(color)); content_audio.addView(visualizerView, 0); playView.setVisibility(View.INVISIBLE); @@ -573,12 +589,12 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, } - public void togglePlaying(View v){ + public void togglePlaying(View v) { HANDLER.postDelayed(new Runnable() { @Override public void run() { - if(isPlaying()){ + if (isPlaying()) { stopPlaying(); } else { startPlaying(); @@ -587,7 +603,7 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, }, 100); } - private void startPlaying(){ + private void startPlaying() { try { playeraudio = new MediaPlayer(); @@ -617,31 +633,33 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, playerSecondsElapsed = 0; startTimer(); - } catch (Exception e){ + } catch (Exception e) { e.printStackTrace(); } } - private void stopPlaying(){ + private void stopPlaying() { statusView.setText(""); statusView.setVisibility(View.INVISIBLE); playView.setImageResource(R.drawable.aar_ic_play); visualizerView.release(); - if(visualizerHandler != null) { + if (visualizerHandler != null) { visualizerHandler.stop(); } - if(playeraudio != null){ + if (playeraudio != null) { try { playeraudio.pause(); - } catch (Exception ignored){ } + } catch (Exception ignored) { + } } stopTimer(); } - private void startTimer(){ + + private void startTimer() { stopTimer(); timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @@ -662,7 +680,7 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, }); } - private void stopTimer(){ + private void stopTimer() { if (timer != null) { timer.cancel(); timer.purge(); @@ -670,10 +688,10 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, } } - private boolean isPlaying(){ + private boolean isPlaying() { try { return playeraudio != null && playeraudio.isPlaying(); - } catch (Exception e){ + } catch (Exception e) { return false; } } @@ -682,7 +700,7 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, @Override public void onDownloaded(String path, String originUrl, Error error) { - if( path != null) { + if (path != null) { File response = new File(path); File dir = getCacheDir(); File from = new File(dir, response.getName()); @@ -702,54 +720,57 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, } else { Helper.manageMoveFileDownload(MediaActivity.this, preview_url, finalUrlDownload, downloadedImage, fileVideo, isSHaring); } - if( progress != null) + if (progress != null) progress.setVisibility(View.GONE); - if( loader != null) + if (loader != null) loader.setVisibility(View.GONE); } @Override - public void onPause(){ + public void onPause() { super.onPause(); - if( player != null) { + if (player != null) { player.setPlayWhenReady(false); } - if( playeraudio != null) { + if (playeraudio != null) { playeraudio.pause(); } try { visualizerView.onPause(); - } catch (Exception ignored){ } + } catch (Exception ignored) { + } } @Override public void onDestroy() { try { - if( visualizerView != null) { + if (visualizerView != null) { visualizerView.release(); } - if( player != null) { + if (player != null) { player.release(); } - if( playeraudio != null) { + if (playeraudio != null) { playeraudio.release(); } - } catch (Exception ignored){ } + } catch (Exception ignored) { + } super.onDestroy(); } @Override - public void onResume(){ + public void onResume() { super.onResume(); - if( player != null) { + if (player != null) { player.setPlayWhenReady(true); } - if( playeraudio != null) { + if (playeraudio != null) { playeraudio.start(); } try { visualizerView.onResume(); - } catch (Exception e){ } + } catch (Exception e) { + } } @Override @@ -759,16 +780,16 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, } public void FullScreencall(Boolean shouldFullscreen) { - if(Build.VERSION.SDK_INT < 19) { + if (Build.VERSION.SDK_INT < 19) { View v = this.getWindow().getDecorView(); - if(shouldFullscreen){ + if (shouldFullscreen) { v.setSystemUiVisibility(View.GONE); - }else { + } else { v.setSystemUiVisibility(View.VISIBLE); } } else { View decorView = getWindow().getDecorView(); - if(shouldFullscreen){ + if (shouldFullscreen) { decorView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_IMMERSIVE // Set the content to appear under the system bars so that the @@ -780,7 +801,7 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); - }else{ + } else { decorView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION @@ -791,7 +812,7 @@ public class MediaActivity extends BaseActivity implements OnDownloadInterface, @Override public void onUpdateProgress(int progressPercentage) { - progress.setText(String.format("%s%%",String.valueOf(progressPercentage))); + progress.setText(String.format("%s%%", String.valueOf(progressPercentage))); pbar_inf.setProgress(progressPercentage); } diff --git a/app/src/main/java/app/fedilab/android/activities/MutedInstanceActivity.java b/app/src/main/java/app/fedilab/android/activities/MutedInstanceActivity.java index 7fe34e05d..7bfa40908 100644 --- a/app/src/main/java/app/fedilab/android/activities/MutedInstanceActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/MutedInstanceActivity.java @@ -97,13 +97,14 @@ public class MutedInstanceActivity extends BaseActivity implements OnRetrieveDom private boolean swiped; private RecyclerView lv_domains; private final int PICK_IMPORT_INSTANCE = 5326; + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme); break; @@ -116,13 +117,13 @@ public class MutedInstanceActivity extends BaseActivity implements OnRetrieveDom default: setTheme(R.style.AppThemeDark); } - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null ) { + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); assert inflater != null; - View view = inflater.inflate(R.layout.simple_bar_muted_instance, new LinearLayout(getApplicationContext()),false); + View view = inflater.inflate(R.layout.simple_bar_muted_instance, new LinearLayout(getApplicationContext()), false); actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close); @@ -142,9 +143,9 @@ public class MutedInstanceActivity extends BaseActivity implements OnRetrieveDom int style; if (theme1 == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme1 == Helper.THEME_BLACK){ + } else if (theme1 == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MutedInstanceActivity.this, style); @@ -156,10 +157,10 @@ public class MutedInstanceActivity extends BaseActivity implements OnRetrieveDom dialogBuilder.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { - if(add_domain.getText() != null && add_domain.getText().toString().trim().matches("^[\\da-zA-Z.-]+\\.[a-zA-Z.]{2,10}$")){ + if (add_domain.getText() != null && add_domain.getText().toString().trim().matches("^[\\da-zA-Z.-]+\\.[a-zA-Z.]{2,10}$")) { new PostActionAsyncTask(MutedInstanceActivity.this, API.StatusAction.BLOCK_DOMAIN, add_domain.getText().toString().trim(), MutedInstanceActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); dialog.dismiss(); - }else{ + } else { Toasty.error(getApplicationContext(), getString(R.string.toast_empty_content)).show(); } } @@ -172,7 +173,7 @@ public class MutedInstanceActivity extends BaseActivity implements OnRetrieveDom }); AlertDialog alertDialog = dialogBuilder.create(); alertDialog.setTitle(getString(R.string.block_domain)); - if( alertDialog.getWindow() != null ) + if (alertDialog.getWindow() != null) alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); alertDialog.show(); break; @@ -181,7 +182,7 @@ public class MutedInstanceActivity extends BaseActivity implements OnRetrieveDom String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(getApplicationContext())); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); Account account = new AccountDAO(getApplicationContext(), db).getUniqAccount(userId, instance); - Helper.exportInstanceBlock(MutedInstanceActivity.this,account.getAcct()+"_"+account.getInstance()); + Helper.exportInstanceBlock(MutedInstanceActivity.this, account.getAcct() + "_" + account.getInstance()); break; case R.id.action_import_instances: if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { @@ -200,21 +201,22 @@ public class MutedInstanceActivity extends BaseActivity implements OnRetrieveDom String[] mimetypes = {"*/*"}; intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes); startActivityForResult(intent, PICK_IMPORT_INSTANCE); - }else { + } else { intent.setType("*/*"); Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); Intent chooserIntent = Intent.createChooser(intent, getString(R.string.toot_select_import)); - chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent}); + chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{pickIntent}); startActivityForResult(chooserIntent, PICK_IMPORT_INSTANCE); } break; } return true; - }}); + } + }); popup.show(); }); toolbar_title.setText(R.string.blocked_domains); - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Toolbar toolbar = actionBar.getCustomView().findViewById(R.id.toolbar); Helper.colorizeToolbar(toolbar, R.color.black, MutedInstanceActivity.this); } @@ -242,16 +244,16 @@ public class MutedInstanceActivity extends BaseActivity implements OnRetrieveDom mLayoutManager = new LinearLayoutManager(MutedInstanceActivity.this); lv_domains.setLayoutManager(mLayoutManager); lv_domains.addOnScrollListener(new RecyclerView.OnScrollListener() { - public void onScrolled(@NotNull RecyclerView recyclerView, int dx, int dy) - { - if(dy > 0) { + public void onScrolled(@NotNull RecyclerView recyclerView, int dx, int dy) { + if (dy > 0) { int visibleItemCount = mLayoutManager.getChildCount(); int totalItemCount = mLayoutManager.getItemCount(); int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition(); if (firstVisibleItem + visibleItemCount == totalItemCount) { if (!flag_loading) { flag_loading = true; - asyncTask = new RetrieveDomainsAsyncTask(MutedInstanceActivity.this, max_id, MutedInstanceActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); nextElementLoader.setVisibility(View.VISIBLE); + asyncTask = new RetrieveDomainsAsyncTask(MutedInstanceActivity.this, max_id, MutedInstanceActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + nextElementLoader.setVisibility(View.VISIBLE); } } else { nextElementLoader.setVisibility(View.GONE); @@ -267,9 +269,10 @@ public class MutedInstanceActivity extends BaseActivity implements OnRetrieveDom firstLoad = true; flag_loading = true; swiped = true; - asyncTask = new RetrieveDomainsAsyncTask(MutedInstanceActivity.this, max_id, MutedInstanceActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } + asyncTask = new RetrieveDomainsAsyncTask(MutedInstanceActivity.this, max_id, MutedInstanceActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + } }); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: swipeRefreshLayout.setColorSchemeResources(R.color.mastodonC4, R.color.mastodonC2, @@ -298,7 +301,7 @@ public class MutedInstanceActivity extends BaseActivity implements OnRetrieveDom @Override public void onDestroy() { super.onDestroy(); - if(asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) + if (asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) asyncTask.cancel(true); } @@ -315,26 +318,26 @@ public class MutedInstanceActivity extends BaseActivity implements OnRetrieveDom public void onRetrieveDomains(APIResponse apiResponse) { mainLoader.setVisibility(View.GONE); nextElementLoader.setVisibility(View.GONE); - if( apiResponse.getError() != null){ - Toasty.error(getApplicationContext(), apiResponse.getError().getError(),Toast.LENGTH_LONG).show(); + if (apiResponse.getError() != null) { + Toasty.error(getApplicationContext(), apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); swipeRefreshLayout.setRefreshing(false); swiped = false; flag_loading = false; return; } - flag_loading = (apiResponse.getMax_id() == null ); + flag_loading = (apiResponse.getMax_id() == null); List domains = apiResponse.getDomains(); - if( !swiped && firstLoad && (domains == null || domains.size() == 0)) + if (!swiped && firstLoad && (domains == null || domains.size() == 0)) textviewNoAction.setVisibility(View.VISIBLE); else textviewNoAction.setVisibility(View.GONE); max_id = apiResponse.getMax_id(); - if( swiped ){ + if (swiped) { domainsListAdapter = new DomainsListAdapter(this.domains, textviewNoAction); lv_domains.setAdapter(domainsListAdapter); swiped = false; } - if( domains != null && domains.size() > 0) { + if (domains != null && domains.size() > 0) { this.domains.addAll(domains); domainsListAdapter.notifyDataSetChanged(); } @@ -354,25 +357,25 @@ public class MutedInstanceActivity extends BaseActivity implements OnRetrieveDom super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_IMPORT_INSTANCE && resultCode == RESULT_OK) { if (data == null || data.getData() == null) { - Toasty.error(getApplicationContext(),getString(R.string.toot_select_file_error),Toast.LENGTH_LONG).show(); + Toasty.error(getApplicationContext(), getString(R.string.toot_select_file_error), Toast.LENGTH_LONG).show(); return; } try { - InputStream is = getContentResolver().openInputStream(data.getData()); + InputStream is = getContentResolver().openInputStream(data.getData()); HashMap resultList = new HashMap<>(); - BufferedReader reader = new BufferedReader(new InputStreamReader( is)); + BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String csvLine; while ((csvLine = reader.readLine()) != null) { String[] row = csvLine.split(","); - if( row.length > 1) { - if( !row[0].equals("INSTANCE")) + if (row.length > 1) { + if (!row[0].equals("INSTANCE")) resultList.put(row[0], row[1]); - }else if(row.length == 1){ - if( !row[0].equals("INSTANCE")) + } else if (row.length == 1) { + if (!row[0].equals("INSTANCE")) resultList.put(row[0], ""); } } - Helper.importInstanceBlock(MutedInstanceActivity.this,resultList); + Helper.importInstanceBlock(MutedInstanceActivity.this, resultList); } catch (Exception e) { Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_SHORT).show(); } @@ -383,14 +386,14 @@ public class MutedInstanceActivity extends BaseActivity implements OnRetrieveDom @Override public void onPostAction(int statusCode, API.StatusAction statusAction, String userId, Error error) { - if( error != null){ - Toasty.error(getApplicationContext(), error.getError(),Toast.LENGTH_LONG).show(); + if (error != null) { + Toasty.error(getApplicationContext(), error.getError(), Toast.LENGTH_LONG).show(); return; } Helper.manageMessageStatusCode(MutedInstanceActivity.this, statusCode, statusAction); - this.domains.add(0,userId); + this.domains.add(0, userId); domainsListAdapter.notifyItemInserted(0); - if( this.domains.size() > 0){ + if (this.domains.size() > 0) { textviewNoAction.setVisibility(View.GONE); } } diff --git a/app/src/main/java/app/fedilab/android/activities/OpencollectiveActivity.java b/app/src/main/java/app/fedilab/android/activities/OpencollectiveActivity.java index 2d36d1ded..5c8aa129c 100644 --- a/app/src/main/java/app/fedilab/android/activities/OpencollectiveActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/OpencollectiveActivity.java @@ -20,8 +20,10 @@ import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; + import androidx.appcompat.app.ActionBar; import androidx.appcompat.widget.Toolbar; + import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; @@ -65,7 +67,7 @@ public class OpencollectiveActivity extends BaseActivity implements OnRetrieveRe super.onCreate(savedInstanceState); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme); break; @@ -79,10 +81,10 @@ public class OpencollectiveActivity extends BaseActivity implements OnRetrieveRe setTheme(R.style.AppThemeDark); } - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null ) { + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); assert inflater != null; View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); @@ -97,7 +99,7 @@ public class OpencollectiveActivity extends BaseActivity implements OnRetrieveRe } }); toolbar_title.setText("Open Collective"); - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Toolbar toolbar = actionBar.getCustomView().findViewById(R.id.toolbar); Helper.colorizeToolbar(toolbar, R.color.black, OpencollectiveActivity.this); } @@ -112,11 +114,11 @@ public class OpencollectiveActivity extends BaseActivity implements OnRetrieveRe Button about_opencollective = findViewById(R.id.about_opencollective); about_opencollective.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://opencollective.com/mastalab")); - startActivity(browserIntent); - } + @Override + public void onClick(View v) { + Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://opencollective.com/mastalab")); + startActivity(browserIntent); + } }); setTitle("Open Collective"); @@ -130,8 +132,8 @@ public class OpencollectiveActivity extends BaseActivity implements OnRetrieveRe lv_sponsors.setAdapter(sponsorsAdapter); new RetrieveOpenCollectiveAsyncTask(getApplicationContext(), RetrieveOpenCollectiveAsyncTask.Type.BACKERS, OpencollectiveActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - new RetrieveOpenCollectiveAsyncTask(getApplicationContext(), RetrieveOpenCollectiveAsyncTask.Type.SPONSORS, OpencollectiveActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } + new RetrieveOpenCollectiveAsyncTask(getApplicationContext(), RetrieveOpenCollectiveAsyncTask.Type.SPONSORS, OpencollectiveActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + } @Override @@ -149,16 +151,16 @@ public class OpencollectiveActivity extends BaseActivity implements OnRetrieveRe @Override public void onRetrieveRemoteAccount(Results results) { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); - if( results == null){ - Toasty.error(getApplicationContext(), getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + if (results == null) { + Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); return; } List accounts = results.getAccounts(); - if( accounts != null && accounts.size() > 0){ - if( accounts.get(0).getSocial().equals("OPENCOLLECTIVE_BACKER")){ + if (accounts != null && accounts.size() > 0) { + if (accounts.get(0).getSocial().equals("OPENCOLLECTIVE_BACKER")) { bakers.addAll(accounts); backersAdapter.notifyDataSetChanged(); - }else if( accounts.get(0).getSocial().equals("OPENCOLLECTIVE_SPONSOR")){ + } else if (accounts.get(0).getSocial().equals("OPENCOLLECTIVE_SPONSOR")) { sponsors.addAll(accounts); sponsorsAdapter.notifyDataSetChanged(); } diff --git a/app/src/main/java/app/fedilab/android/activities/OwnerChartsActivity.java b/app/src/main/java/app/fedilab/android/activities/OwnerChartsActivity.java index 81e3b0c94..f26260e8c 100644 --- a/app/src/main/java/app/fedilab/android/activities/OwnerChartsActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/OwnerChartsActivity.java @@ -40,6 +40,7 @@ import androidx.appcompat.app.ActionBar; import androidx.appcompat.widget.Toolbar; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.LinearLayoutManager; + import com.github.mikephil.charting.charts.LineChart; import com.github.mikephil.charting.components.Description; import com.github.mikephil.charting.components.IMarker; @@ -99,7 +100,7 @@ public class OwnerChartsActivity extends BaseActivity implements OnRetrieveChart SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme); break; @@ -112,10 +113,10 @@ public class OwnerChartsActivity extends BaseActivity implements OnRetrieveChart default: setTheme(R.style.AppThemeDark); } - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null ) { + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); assert inflater != null; View view = inflater.inflate(R.layout.simple_action_bar, new LinearLayout(getApplicationContext()), false); @@ -129,8 +130,8 @@ public class OwnerChartsActivity extends BaseActivity implements OnRetrieveChart SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, null); - Account account = new AccountDAO(getApplicationContext(),db).getUniqAccount(userId, instance); - if( account != null) { + Account account = new AccountDAO(getApplicationContext(), db).getUniqAccount(userId, instance); + if (account != null) { Helper.loadGiF(getApplicationContext(), account.getAvatar(), pp_actionBar); } @@ -140,12 +141,12 @@ public class OwnerChartsActivity extends BaseActivity implements OnRetrieveChart finish(); } }); - if( account != null) { + if (account != null) { toolbar_title.setText(getString(R.string.owner_charts) + " - " + account.getUsername() + "@" + account.getInstance()); - }else{ + } else { toolbar_title.setText(R.string.owner_charts); } - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Toolbar toolbar = actionBar.getCustomView().findViewById(R.id.toolbar); Helper.colorizeToolbar(toolbar, R.color.black, OwnerChartsActivity.this); } @@ -156,7 +157,7 @@ public class OwnerChartsActivity extends BaseActivity implements OnRetrieveChart chart = findViewById(R.id.chart); settings_time_from = findViewById(R.id.settings_time_from); settings_time_to = findViewById(R.id.settings_time_to); - loader = findViewById(R.id.loader); + loader = findViewById(R.id.loader); validate = findViewById(R.id.validate); SQLiteDatabase db = Sqlite.getInstance(OwnerChartsActivity.this, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); @@ -165,11 +166,11 @@ public class OwnerChartsActivity extends BaseActivity implements OnRetrieveChart int style; - if( theme == Helper.THEME_DARK){ + if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - }else if( theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } Calendar c = Calendar.getInstance(); @@ -226,7 +227,7 @@ public class OwnerChartsActivity extends BaseActivity implements OnRetrieveChart CustomMarkerView mv = new CustomMarkerView(getApplicationContext(), R.layout.markerview); chart.setMarkerView(mv); - validate.setOnClickListener(v->{ + validate.setOnClickListener(v -> { loadGraph(dateIni, dateEnd); }); @@ -241,24 +242,27 @@ public class OwnerChartsActivity extends BaseActivity implements OnRetrieveChart public CustomMarkerView(Context context, int layoutResource) { super(context, layoutResource); tvContent = findViewById(R.id.tvContent); - if( theme == Helper.THEME_DARK){ + if (theme == Helper.THEME_DARK) { tvContent.setTextColor(ContextCompat.getColor(context, R.color.dark_text)); - }else if( theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { tvContent.setTextColor(ContextCompat.getColor(context, R.color.dark_text)); - }else { + } else { tvContent.setTextColor(ContextCompat.getColor(context, R.color.black)); } } + @Override public void refreshContent(Entry e, Highlight highlight) { Date date = new Date(((long) e.getX())); - tvContent.setText(String.valueOf(Helper.shortDateToString(date) + " - " +(int)e.getY())); + tvContent.setText(String.valueOf(Helper.shortDateToString(date) + " - " + (int) e.getY())); super.refreshContent(e, highlight); } + private MPPointF mOffset; + @Override public MPPointF getOffset() { - if(mOffset == null) { + if (mOffset == null) { mOffset = new MPPointF(-(getWidth() / 2), -getHeight()); } return mOffset; @@ -303,7 +307,7 @@ public class OwnerChartsActivity extends BaseActivity implements OnRetrieveChart } } - private void loadGraph(Date dateIni, Date dateEnd){ + private void loadGraph(Date dateIni, Date dateEnd) { String dateInitString = Helper.shortDateToString(dateIni); String dateEndString = Helper.shortDateToString(dateEnd); @@ -329,24 +333,24 @@ public class OwnerChartsActivity extends BaseActivity implements OnRetrieveChart int i = 0; Iterator it = charts.getBoosts().entrySet().iterator(); while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - boostsEntry.add(new Entry((long)pair.getKey(), (int)pair.getValue())); + Map.Entry pair = (Map.Entry) it.next(); + boostsEntry.add(new Entry((long) pair.getKey(), (int) pair.getValue())); it.remove(); } List repliesEntry = new ArrayList<>(); it = charts.getReplies().entrySet().iterator(); while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - repliesEntry.add(new Entry((long)pair.getKey(), (int)pair.getValue())); + Map.Entry pair = (Map.Entry) it.next(); + repliesEntry.add(new Entry((long) pair.getKey(), (int) pair.getValue())); it.remove(); } List statusesEntry = new ArrayList<>(); it = charts.getStatuses().entrySet().iterator(); while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - statusesEntry.add(new Entry((long)pair.getKey(), (int)pair.getValue())); + Map.Entry pair = (Map.Entry) it.next(); + statusesEntry.add(new Entry((long) pair.getKey(), (int) pair.getValue())); it.remove(); } @@ -419,7 +423,7 @@ public class OwnerChartsActivity extends BaseActivity implements OnRetrieveChart description.setEnabled(false); //Update colors - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: xAxis.setTextColor(Color.BLACK); dataSetBoosts.setValueTextColor(Color.BLACK); @@ -461,6 +465,7 @@ public class OwnerChartsActivity extends BaseActivity implements OnRetrieveChart this.mDataFormat = new SimpleDateFormat("dd.MM", Locale.getDefault()); this.mDate = new Date(); } + @Override public String getFormattedValue(float value) { return getDateString((long) value); @@ -470,7 +475,7 @@ public class OwnerChartsActivity extends BaseActivity implements OnRetrieveChart try { mDate.setTime(timestamp); return mDataFormat.format(mDate); - } catch(Exception ex) { + } catch (Exception ex) { return "xx"; } } diff --git a/app/src/main/java/app/fedilab/android/activities/OwnerNotificationActivity.java b/app/src/main/java/app/fedilab/android/activities/OwnerNotificationActivity.java index bbf45a4b8..32cebdcc9 100644 --- a/app/src/main/java/app/fedilab/android/activities/OwnerNotificationActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/OwnerNotificationActivity.java @@ -114,7 +114,7 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme_NoActionBar_Fedilab); break; @@ -136,12 +136,12 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev new IntentFilter(Helper.INTENT_BACKUP_FINISH)); Toolbar toolbar = findViewById(R.id.toolbar); - if( theme == Helper.THEME_BLACK) + if (theme == Helper.THEME_BLACK) toolbar.setBackgroundColor(ContextCompat.getColor(OwnerNotificationActivity.this, R.color.black)); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null ){ + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); assert inflater != null; View view = inflater.inflate(R.layout.toot_action_bar, new LinearLayout(getApplicationContext()), false); @@ -157,16 +157,16 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev }); TextView toolbarTitle = actionBar.getCustomView().findViewById(R.id.toolbar_title); pp_actionBar = actionBar.getCustomView().findViewById(R.id.pp_actionBar); - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Helper.colorizeToolbar(actionBar.getCustomView().findViewById(R.id.toolbar), R.color.black, OwnerNotificationActivity.this); } toolbarTitle.setText(getString(R.string.owner_cached_notifications)); } notifications = new ArrayList<>(); RecyclerView lv_notifications = findViewById(R.id.lv_notifications); - mainLoader = findViewById(R.id.loader); + mainLoader = findViewById(R.id.loader); nextElementLoader = findViewById(R.id.loading_next_status); - textviewNoAction = findViewById(R.id.no_action); + textviewNoAction = findViewById(R.id.no_action); mainLoader.setVisibility(View.VISIBLE); nextElementLoader.setVisibility(View.GONE); max_id = null; @@ -177,28 +177,28 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, null); int behaviorWithAttachments = sharedpreferences.getInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ALWAYS); - notificationsListAdapter = new NotificationsListAdapter(isOnWifi, behaviorWithAttachments,this.notifications); + notificationsListAdapter = new NotificationsListAdapter(isOnWifi, behaviorWithAttachments, this.notifications); lv_notifications.setAdapter(notificationsListAdapter); mLayoutManager = new LinearLayoutManager(OwnerNotificationActivity.this); lv_notifications.setLayoutManager(mLayoutManager); - if( theme == Helper.THEME_DARK){ + if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - }else if( theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } SQLiteDatabase db = Sqlite.getInstance(OwnerNotificationActivity.this, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - Account account = new AccountDAO(OwnerNotificationActivity.this,db).getUniqAccount(userId, instance); + Account account = new AccountDAO(OwnerNotificationActivity.this, db).getUniqAccount(userId, instance); Helper.loadGiF(getApplicationContext(), account.getAvatar(), pp_actionBar); swipeRefreshLayout = findViewById(R.id.swipeContainer); new RetrieveNotificationsCacheAsyncTask(OwnerNotificationActivity.this, filterNotifications, null, OwnerNotificationActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: swipeRefreshLayout.setColorSchemeResources(R.color.mastodonC4, R.color.mastodonC2, @@ -230,14 +230,13 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev }); lv_notifications.addOnScrollListener(new RecyclerView.OnScrollListener() { - public void onScrolled(@NotNull RecyclerView recyclerView, int dx, int dy) - { + public void onScrolled(@NotNull RecyclerView recyclerView, int dx, int dy) { int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition(); - if(dy > 0){ + if (dy > 0) { int visibleItemCount = mLayoutManager.getChildCount(); int totalItemCount = mLayoutManager.getItemCount(); - if(firstVisibleItem + visibleItemCount == totalItemCount ) { - if(!flag_loading ) { + if (firstVisibleItem + visibleItemCount == totalItemCount) { + if (!flag_loading) { flag_loading = true; new RetrieveNotificationsCacheAsyncTask(OwnerNotificationActivity.this, filterNotifications, max_id, OwnerNotificationActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); nextElementLoader.setVisibility(View.VISIBLE); @@ -257,7 +256,7 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev getMenuInflater().inflate(R.menu.option_owner_cache, menu); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if( theme == Helper.THEME_LIGHT) + if (theme == Helper.THEME_LIGHT) Helper.colorizeIconMenu(menu, R.color.black); return true; } @@ -287,6 +286,7 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev } }; + @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { @@ -303,9 +303,9 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(OwnerNotificationActivity.this, style); @@ -321,9 +321,9 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev } }); dialogBuilder.create().show(); - if( statistics == null) { - new RetrieveNotificationStatsAsyncTask(getApplicationContext(), OwnerNotificationActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else{ + if (statistics == null) { + new RetrieveNotificationStatsAsyncTask(getApplicationContext(), OwnerNotificationActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + } else { displayStats(); } return true; @@ -332,9 +332,9 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } dialogBuilder = new AlertDialog.Builder(OwnerNotificationActivity.this, style); @@ -344,11 +344,11 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev SQLiteDatabase db = Sqlite.getInstance(OwnerNotificationActivity.this, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - if( dateIni == null) + if (dateIni == null) dateIni = new NotificationCacheDAO(OwnerNotificationActivity.this, db).getSmallerDate(); - if( dateEnd == null) + if (dateEnd == null) dateEnd = new NotificationCacheDAO(OwnerNotificationActivity.this, db).getGreaterDate(); - if( dateIni == null || dateEnd == null) + if (dateIni == null || dateEnd == null) return true; String dateInitString = Helper.shortDateToString(dateIni); String dateEndString = Helper.shortDateToString(dateEnd); @@ -374,7 +374,6 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev filter_poll.setChecked(filterNotifications.isPoll()); - Calendar c = Calendar.getInstance(); c.setTime(dateIni); int yearIni = c.get(Calendar.YEAR); @@ -440,7 +439,6 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev } - private BroadcastReceiver backupFinishedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { @@ -459,8 +457,8 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev .unregisterReceiver(backupFinishedReceiver); } - private void displayStats(){ - if( statsDialogView != null){ + private void displayStats() { + if (statsDialogView != null) { ScrollView stats_container = statsDialogView.findViewById(R.id.stats_container); RelativeLayout loader = statsDialogView.findViewById(R.id.loader); @@ -478,7 +476,7 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev ImageButton charts = statsDialogView.findViewById(R.id.charts); - charts.setOnClickListener(w ->{ + charts.setOnClickListener(w -> { Intent intent = new Intent(OwnerNotificationActivity.this, OwnerNotificationChartsActivity.class); startActivity(intent); }); @@ -500,8 +498,8 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev stats_container.setVisibility(View.VISIBLE); loader.setVisibility(View.GONE); - }else{ - Toasty.error(getApplicationContext(),getString(R.string.toast_error),Toast.LENGTH_SHORT).show(); + } else { + Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_SHORT).show(); } } @@ -510,8 +508,8 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev mainLoader.setVisibility(View.GONE); nextElementLoader.setVisibility(View.GONE); //Discards 404 - error which can often happen due to toots which have been deleted - if( apiResponse.getError() != null && apiResponse.getError().getStatusCode() != 404 ){ - Toasty.error(getApplicationContext(), apiResponse.getError().getError(),Toast.LENGTH_LONG).show(); + if (apiResponse.getError() != null && apiResponse.getError().getStatusCode() != 404) { + Toasty.error(getApplicationContext(), apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); swipeRefreshLayout.setRefreshing(false); swiped = false; flag_loading = false; @@ -520,13 +518,13 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev int previousPosition = this.notifications.size(); List notifications = apiResponse.getNotifications(); max_id = apiResponse.getMax_id(); - flag_loading = (max_id == null ); - if( !swiped && firstLoad && (notifications == null || notifications.size() == 0)) + flag_loading = (max_id == null); + if (!swiped && firstLoad && (notifications == null || notifications.size() == 0)) textviewNoAction.setVisibility(View.VISIBLE); else textviewNoAction.setVisibility(View.GONE); - if( swiped ){ + if (swiped) { if (previousPosition > 0) { for (int i = 0; i < previousPosition; i++) { this.notifications.remove(0); @@ -535,11 +533,11 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev } swiped = false; } - if( notifications != null && notifications.size() > 0) { + if (notifications != null && notifications.size() > 0) { this.notifications.addAll(notifications); notificationsListAdapter.notifyItemRangeInserted(previousPosition, notifications.size()); - }else { - if( textviewNoAction.getVisibility() != View.VISIBLE && firstLoad) { + } else { + if (textviewNoAction.getVisibility() != View.VISIBLE && firstLoad) { RelativeLayout no_result = findViewById(R.id.no_result); no_result.setVisibility(View.VISIBLE); } diff --git a/app/src/main/java/app/fedilab/android/activities/OwnerNotificationChartsActivity.java b/app/src/main/java/app/fedilab/android/activities/OwnerNotificationChartsActivity.java index ed4d4b1c7..7d0fa2b89 100644 --- a/app/src/main/java/app/fedilab/android/activities/OwnerNotificationChartsActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/OwnerNotificationChartsActivity.java @@ -101,7 +101,7 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme); break; @@ -116,12 +116,12 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR } Bundle b = getIntent().getExtras(); status_id = null; - if(b != null) + if (b != null) status_id = b.getString("status_id"); - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null ) { + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); assert inflater != null; View view = inflater.inflate(R.layout.simple_action_bar, new LinearLayout(getApplicationContext()), false); @@ -135,8 +135,8 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, null); - Account account = new AccountDAO(getApplicationContext(),db).getUniqAccount(userId, instance); - if( account != null) { + Account account = new AccountDAO(getApplicationContext(), db).getUniqAccount(userId, instance); + if (account != null) { Helper.loadGiF(getApplicationContext(), account.getAvatar(), pp_actionBar); } @@ -146,12 +146,12 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR finish(); } }); - if( account != null) { + if (account != null) { toolbar_title.setText(getString(R.string.owner_charts) + " - " + account.getUsername() + "@" + account.getInstance()); - }else{ + } else { toolbar_title.setText(R.string.owner_charts); } - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Toolbar toolbar = actionBar.getCustomView().findViewById(R.id.toolbar); Helper.colorizeToolbar(toolbar, R.color.black, OwnerNotificationChartsActivity.this); } @@ -162,19 +162,19 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR chart = findViewById(R.id.chart); settings_time_from = findViewById(R.id.settings_time_from); settings_time_to = findViewById(R.id.settings_time_to); - loader = findViewById(R.id.loader); + loader = findViewById(R.id.loader); validate = findViewById(R.id.validate); LinearLayout date_container = findViewById(R.id.date_container); SQLiteDatabase db = Sqlite.getInstance(OwnerNotificationChartsActivity.this, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - if( status_id == null) { + if (status_id == null) { dateIni = new NotificationCacheDAO(OwnerNotificationChartsActivity.this, db).getSmallerDate(); dateEnd = new NotificationCacheDAO(OwnerNotificationChartsActivity.this, db).getGreaterDate(); - }else{ + } else { Status status = new StatusCacheDAO(getApplicationContext(), db).getStatus(status_id); - if( status == null){ + if (status == null) { finish(); return; - }else{ + } else { dateIni = status.getCreated_at(); dateEnd = dateIni; date_container.setVisibility(View.GONE); @@ -183,15 +183,15 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR int style; - if( theme == Helper.THEME_DARK){ + if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - }else if( theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } Calendar c = Calendar.getInstance(); - if(dateIni != null) { + if (dateIni != null) { c.setTime(dateIni); } int yearIni = c.get(Calendar.YEAR); @@ -207,7 +207,7 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR } }); - if( dateIni != null) { + if (dateIni != null) { Calendar ce = Calendar.getInstance(); c.setTime(dateEnd); int yearEnd = ce.get(Calendar.YEAR); @@ -264,24 +264,24 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR Iterator it = charts.getReblogs().entrySet().iterator(); while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - boostsEntry.add(new Entry((long)pair.getKey(), (int)pair.getValue())); + Map.Entry pair = (Map.Entry) it.next(); + boostsEntry.add(new Entry((long) pair.getKey(), (int) pair.getValue())); it.remove(); } List favEntry = new ArrayList<>(); it = charts.getFavourites().entrySet().iterator(); while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - favEntry.add(new Entry((long)pair.getKey(), (int)pair.getValue())); + Map.Entry pair = (Map.Entry) it.next(); + favEntry.add(new Entry((long) pair.getKey(), (int) pair.getValue())); it.remove(); } List mentionEntry = new ArrayList<>(); it = charts.getMentions().entrySet().iterator(); while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - mentionEntry.add(new Entry((long)pair.getKey(), (int)pair.getValue())); + Map.Entry pair = (Map.Entry) it.next(); + mentionEntry.add(new Entry((long) pair.getKey(), (int) pair.getValue())); it.remove(); } @@ -289,8 +289,8 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR List followEntry = new ArrayList<>(); it = charts.getFollows().entrySet().iterator(); while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - followEntry.add(new Entry((long)pair.getKey(), (int)pair.getValue())); + Map.Entry pair = (Map.Entry) it.next(); + followEntry.add(new Entry((long) pair.getKey(), (int) pair.getValue())); it.remove(); } @@ -303,7 +303,6 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR }*/ - LineDataSet dataSetBoosts = new LineDataSet(boostsEntry, getString(R.string.reblog)); dataSetBoosts.setColor(ContextCompat.getColor(OwnerNotificationChartsActivity.this, R.color.chart_notif_boost)); dataSetBoosts.setValueTextSize(10f); @@ -314,9 +313,9 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR dataSetBoosts.setDrawCircles(false); dataSetBoosts.setDrawCircleHole(false); dataSetBoosts.setLineWidth(2f); - if( status_id == null) { + if (status_id == null) { dataSetBoosts.setMode(LineDataSet.Mode.CUBIC_BEZIER); - }else{ + } else { dataSetBoosts.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER); } @@ -330,9 +329,9 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR dateSetFavorites.setDrawCircles(false); dateSetFavorites.setDrawCircleHole(false); dateSetFavorites.setLineWidth(2f); - if( status_id == null) { + if (status_id == null) { dateSetFavorites.setMode(LineDataSet.Mode.CUBIC_BEZIER); - }else{ + } else { dateSetFavorites.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER); } @@ -346,9 +345,9 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR dataSetMention.setDrawCircles(false); dataSetMention.setDrawCircleHole(false); dataSetMention.setLineWidth(2f); - if( status_id == null) { + if (status_id == null) { dataSetMention.setMode(LineDataSet.Mode.CUBIC_BEZIER); - }else{ + } else { dataSetMention.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER); } @@ -363,9 +362,9 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR dataSetFollow.setDrawCircles(false); dataSetFollow.setDrawCircleHole(false); dataSetFollow.setLineWidth(2f); - if( status_id == null) { + if (status_id == null) { dataSetFollow.setMode(LineDataSet.Mode.CUBIC_BEZIER); - }else{ + } else { dataSetFollow.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER); } @@ -420,14 +419,14 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR description.setEnabled(false); //Update colors - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: xAxis.setTextColor(Color.BLACK); dataSetBoosts.setValueTextColor(Color.BLACK); dateSetFavorites.setValueTextColor(Color.BLACK); dataSetFollow.setValueTextColor(Color.BLACK); dataSetMention.setValueTextColor(Color.BLACK); - // dataSetPolls.setValueTextColor(Color.BLACK); + // dataSetPolls.setValueTextColor(Color.BLACK); legend.setTextColor(Color.BLACK); leftAxis.setTextColor(Color.BLACK); @@ -440,7 +439,7 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR dateSetFavorites.setValueTextColor(color); dataSetFollow.setValueTextColor(color); dataSetMention.setValueTextColor(color); - // dataSetPolls.setValueTextColor(color); + // dataSetPolls.setValueTextColor(color); legend.setTextColor(color); leftAxis.setTextColor(color); } @@ -463,24 +462,27 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR public CustomMarkerView(Context context, int layoutResource) { super(context, layoutResource); tvContent = findViewById(R.id.tvContent); - if( theme == Helper.THEME_DARK){ + if (theme == Helper.THEME_DARK) { tvContent.setTextColor(ContextCompat.getColor(context, R.color.dark_text)); - }else if( theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { tvContent.setTextColor(ContextCompat.getColor(context, R.color.dark_text)); - }else { + } else { tvContent.setTextColor(ContextCompat.getColor(context, R.color.black)); } } + @Override public void refreshContent(Entry e, Highlight highlight) { Date date = new Date(((long) e.getX())); - tvContent.setText(String.valueOf(Helper.shortDateToString(date) + " - " +(int)e.getY())); + tvContent.setText(String.valueOf(Helper.shortDateToString(date) + " - " + (int) e.getY())); super.refreshContent(e, highlight); } + private MPPointF mOffset; + @Override public MPPointF getOffset() { - if(mOffset == null) { + if (mOffset == null) { mOffset = new MPPointF(-(getWidth() / 2), -getHeight()); } return mOffset; @@ -525,7 +527,7 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR } } - private void loadGraph(Date dateIni, Date dateEnd){ + private void loadGraph(Date dateIni, Date dateEnd) { String dateInitString = Helper.shortDateToString(dateIni); String dateEndString = Helper.shortDateToString(dateEnd); @@ -544,19 +546,19 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR } - public class MyXAxisValueFormatter extends ValueFormatter { private DateFormat mDataFormat; private Date mDate; MyXAxisValueFormatter() { - if( status_id == null) { + if (status_id == null) { this.mDataFormat = new SimpleDateFormat("dd.MM", Locale.getDefault()); - }else{ + } else { this.mDataFormat = new SimpleDateFormat("hh'h'", Locale.getDefault()); } this.mDate = new Date(); } + @Override public String getFormattedValue(float value) { return getDateString((long) value); @@ -566,7 +568,7 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR try { mDate.setTime(timestamp); return mDataFormat.format(mDate); - } catch(Exception ex) { + } catch (Exception ex) { return "xx"; } } diff --git a/app/src/main/java/app/fedilab/android/activities/OwnerStatusActivity.java b/app/src/main/java/app/fedilab/android/activities/OwnerStatusActivity.java index 38451e599..9bfcecb72 100644 --- a/app/src/main/java/app/fedilab/android/activities/OwnerStatusActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/OwnerStatusActivity.java @@ -26,6 +26,7 @@ import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.os.Bundle; + import androidx.core.content.ContextCompat; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; @@ -34,6 +35,7 @@ import androidx.appcompat.app.AlertDialog; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.appcompat.widget.Toolbar; + import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; @@ -111,7 +113,7 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme_NoActionBar_Fedilab); break; @@ -133,12 +135,12 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds new IntentFilter(Helper.INTENT_BACKUP_FINISH)); Toolbar toolbar = findViewById(R.id.toolbar); - if( theme == Helper.THEME_BLACK) + if (theme == Helper.THEME_BLACK) toolbar.setBackgroundColor(ContextCompat.getColor(OwnerStatusActivity.this, R.color.black)); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null ){ + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(android.content.Context.LAYOUT_INFLATER_SERVICE); assert inflater != null; View view = inflater.inflate(R.layout.toot_action_bar, new LinearLayout(getApplicationContext()), false); @@ -154,16 +156,16 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds }); TextView toolbarTitle = actionBar.getCustomView().findViewById(R.id.toolbar_title); pp_actionBar = actionBar.getCustomView().findViewById(R.id.pp_actionBar); - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Helper.colorizeToolbar(actionBar.getCustomView().findViewById(R.id.toolbar), R.color.black, OwnerStatusActivity.this); } toolbarTitle.setText(getString(R.string.owner_cached_toots)); } statuses = new ArrayList<>(); RecyclerView lv_status = findViewById(R.id.lv_status); - mainLoader = findViewById(R.id.loader); + mainLoader = findViewById(R.id.loader); nextElementLoader = findViewById(R.id.loading_next_status); - textviewNoAction = findViewById(R.id.no_action); + textviewNoAction = findViewById(R.id.no_action); mainLoader.setVisibility(View.VISIBLE); nextElementLoader.setVisibility(View.GONE); max_id = null; @@ -179,22 +181,22 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds lv_status.setLayoutManager(mLayoutManager); - if( theme == Helper.THEME_DARK){ + if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - }else if( theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } SQLiteDatabase db = Sqlite.getInstance(OwnerStatusActivity.this, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - Account account = new AccountDAO(OwnerStatusActivity.this,db).getUniqAccount(userId, instance); + Account account = new AccountDAO(OwnerStatusActivity.this, db).getUniqAccount(userId, instance); Helper.loadGiF(getApplicationContext(), account.getAvatar(), pp_actionBar); swipeRefreshLayout = findViewById(R.id.swipeContainer); new RetrieveFeedsAsyncTask(OwnerStatusActivity.this, filterToots, null, OwnerStatusActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: swipeRefreshLayout.setColorSchemeResources(R.color.mastodonC4, R.color.mastodonC2, @@ -226,14 +228,13 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds }); lv_status.addOnScrollListener(new RecyclerView.OnScrollListener() { - public void onScrolled(RecyclerView recyclerView, int dx, int dy) - { + public void onScrolled(RecyclerView recyclerView, int dx, int dy) { int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition(); - if(dy > 0){ + if (dy > 0) { int visibleItemCount = mLayoutManager.getChildCount(); int totalItemCount = mLayoutManager.getItemCount(); - if(firstVisibleItem + visibleItemCount == totalItemCount ) { - if(!flag_loading ) { + if (firstVisibleItem + visibleItemCount == totalItemCount) { + if (!flag_loading) { flag_loading = true; new RetrieveFeedsAsyncTask(OwnerStatusActivity.this, filterToots, max_id, OwnerStatusActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); nextElementLoader.setVisibility(View.VISIBLE); @@ -253,7 +254,7 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds getMenuInflater().inflate(R.menu.option_owner_cache, menu); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if( theme == Helper.THEME_LIGHT) + if (theme == Helper.THEME_LIGHT) Helper.colorizeIconMenu(menu, R.color.black); return true; } @@ -283,6 +284,7 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds } }; + @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { @@ -299,9 +301,9 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(OwnerStatusActivity.this, style); @@ -317,9 +319,9 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds } }); dialogBuilder.create().show(); - if( statistics == null) { + if (statistics == null) { new RetrieveStatsAsyncTask(getApplicationContext(), OwnerStatusActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else{ + } else { displayStats(); } return true; @@ -328,9 +330,9 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } dialogBuilder = new AlertDialog.Builder(OwnerStatusActivity.this, style); @@ -340,11 +342,11 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds SQLiteDatabase db = Sqlite.getInstance(OwnerStatusActivity.this, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - if( dateIni == null) + if (dateIni == null) dateIni = new StatusCacheDAO(OwnerStatusActivity.this, db).getSmallerDate(StatusCacheDAO.ARCHIVE_CACHE); - if( dateEnd == null) + if (dateEnd == null) dateEnd = new StatusCacheDAO(OwnerStatusActivity.this, db).getGreaterDate(StatusCacheDAO.ARCHIVE_CACHE); - if( dateIni == null || dateEnd == null) + if (dateIni == null || dateEnd == null) return true; String dateInitString = Helper.shortDateToString(dateIni); String dateEndString = Helper.shortDateToString(dateEnd); @@ -378,7 +380,7 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds settings_time_from.setText(dateInitString); settings_time_to.setText(dateEndString); - if( filterToots.getFilter() != null) + if (filterToots.getFilter() != null) filter_keywords.setText(filterToots.getFilter()); Calendar c = Calendar.getInstance(); @@ -429,7 +431,7 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds filterToots.setDateIni(Helper.dateToString(dateIni)); filterToots.setDateEnd(Helper.dateToString(dateEnd)); - if( filter_keywords.getText() != null && filter_keywords.getText().toString().trim().length() > 0) + if (filter_keywords.getText() != null && filter_keywords.getText().toString().trim().length() > 0) filterToots.setFilter(filter_keywords.getText().toString()); else filterToots.setFilter(null); @@ -460,8 +462,8 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds mainLoader.setVisibility(View.GONE); nextElementLoader.setVisibility(View.GONE); //Discards 404 - error which can often happen due to toots which have been deleted - if( apiResponse.getError() != null && apiResponse.getError().getStatusCode() != 404 ){ - Toasty.error(getApplicationContext(), apiResponse.getError().getError(),Toast.LENGTH_LONG).show(); + if (apiResponse.getError() != null && apiResponse.getError().getStatusCode() != 404) { + Toasty.error(getApplicationContext(), apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); swipeRefreshLayout.setRefreshing(false); swiped = false; flag_loading = false; @@ -470,13 +472,13 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds int previousPosition = this.statuses.size(); List statuses = apiResponse.getStatuses(); max_id = apiResponse.getMax_id(); - flag_loading = (max_id == null ); - if( !swiped && firstLoad && (statuses == null || statuses.size() == 0)) + flag_loading = (max_id == null); + if (!swiped && firstLoad && (statuses == null || statuses.size() == 0)) textviewNoAction.setVisibility(View.VISIBLE); else textviewNoAction.setVisibility(View.GONE); - if( swiped ){ + if (swiped) { if (previousPosition > 0) { for (int i = 0; i < previousPosition; i++) { this.statuses.remove(0); @@ -485,11 +487,11 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds } swiped = false; } - if( statuses != null && statuses.size() > 0) { + if (statuses != null && statuses.size() > 0) { this.statuses.addAll(statuses); statusListAdapter.notifyItemRangeInserted(previousPosition, statuses.size()); - }else { - if( textviewNoAction.getVisibility() != View.VISIBLE && firstLoad) { + } else { + if (textviewNoAction.getVisibility() != View.VISIBLE && firstLoad) { RelativeLayout no_result = findViewById(R.id.no_result); no_result.setVisibility(View.VISIBLE); } @@ -524,8 +526,8 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds displayStats(); } - private void displayStats(){ - if( statsDialogView != null){ + private void displayStats() { + if (statsDialogView != null) { ScrollView stats_container = statsDialogView.findViewById(R.id.stats_container); RelativeLayout loader = statsDialogView.findViewById(R.id.loader); @@ -547,7 +549,7 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds TextView tags = statsDialogView.findViewById(R.id.tags); ImageButton charts = statsDialogView.findViewById(R.id.charts); - charts.setOnClickListener(w ->{ + charts.setOnClickListener(w -> { Intent intent = new Intent(OwnerStatusActivity.this, OwnerChartsActivity.class); startActivity(intent); }); @@ -570,26 +572,26 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds DecimalFormat df = new DecimalFormat("#.##"); frequency.setText(getString(R.string.toot_per_day, df.format(statistics.getFrequency()))); - if( statistics.getTagsTrend() != null && statistics.getTagsTrend().size() > 0 ){ - Iterator it = statistics.getTagsTrend() .entrySet().iterator(); + if (statistics.getTagsTrend() != null && statistics.getTagsTrend().size() > 0) { + Iterator it = statistics.getTagsTrend().entrySet().iterator(); StringBuilder text = new StringBuilder(); int i = 1; while (it.hasNext() && i <= 10) { - Map.Entry pair = (Map.Entry)it.next(); + Map.Entry pair = (Map.Entry) it.next(); System.out.println(pair.getKey() + " = " + pair.getValue()); text.append(i).append(" - ").append(pair.getKey()).append(" → ").append(pair.getValue()).append("\r\n"); i++; } tags.setText(text.toString()); - }else{ + } else { tags.setText(getString(R.string.no_tags)); } stats_container.setVisibility(View.VISIBLE); loader.setVisibility(View.GONE); - }else{ - Toasty.error(getApplicationContext(),getString(R.string.toast_error),Toast.LENGTH_SHORT).show(); + } else { + Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_SHORT).show(); } } } diff --git a/app/src/main/java/app/fedilab/android/activities/PartnerShipActivity.java b/app/src/main/java/app/fedilab/android/activities/PartnerShipActivity.java index 7edc1fea2..37a00149c 100644 --- a/app/src/main/java/app/fedilab/android/activities/PartnerShipActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/PartnerShipActivity.java @@ -20,8 +20,10 @@ import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; + import androidx.appcompat.app.ActionBar; import androidx.appcompat.widget.Toolbar; + import android.text.method.LinkMovementMethod; import android.view.LayoutInflater; import android.view.MenuItem; @@ -66,7 +68,7 @@ public class PartnerShipActivity extends BaseActivity implements OnRetrieveRemot super.onCreate(savedInstanceState); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme); break; @@ -80,14 +82,14 @@ public class PartnerShipActivity extends BaseActivity implements OnRetrieveRemot setTheme(R.style.AppThemeDark); } - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); setContentView(R.layout.activity_partnership); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null ) { + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); assert inflater != null; - View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); + View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close); @@ -99,7 +101,7 @@ public class PartnerShipActivity extends BaseActivity implements OnRetrieveRemot } }); toolbar_title.setText(R.string.action_partnership); - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Toolbar toolbar = actionBar.getCustomView().findViewById(R.id.toolbar); Helper.colorizeToolbar(toolbar, R.color.black, PartnerShipActivity.this); } @@ -113,11 +115,11 @@ public class PartnerShipActivity extends BaseActivity implements OnRetrieveRemot ImageView mastohost = findViewById(R.id.mastohost_logo); mastohost.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://masto.host")); - startActivity(browserIntent); - } + @Override + public void onClick(View v) { + Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://masto.host")); + startActivity(browserIntent); + } }); setTitle(R.string.action_partnership); @@ -129,7 +131,7 @@ public class PartnerShipActivity extends BaseActivity implements OnRetrieveRemot new RetrieveRemoteDataAsyncTask(getApplicationContext(), "mastohost", "mastodon.social", PartnerShipActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } + } @Override public boolean onOptionsItemSelected(MenuItem item) { @@ -146,13 +148,13 @@ public class PartnerShipActivity extends BaseActivity implements OnRetrieveRemot @Override public void onRetrieveRemoteAccount(Results results) { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); - if( results == null){ - Toasty.error(getApplicationContext(), getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + if (results == null) { + Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); return; } List accounts = results.getAccounts(); Account account; - if( accounts != null && accounts.size() > 0){ + if (accounts != null && accounts.size() > 0) { account = accounts.get(0); account.setFollowing(true); switch (account.getUsername()) { @@ -161,17 +163,17 @@ public class PartnerShipActivity extends BaseActivity implements OnRetrieveRemot mastohostAdapter.notifyDataSetChanged(); break; } - new RetrieveRelationshipAsyncTask(getApplicationContext(), account.getId(),PartnerShipActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new RetrieveRelationshipAsyncTask(getApplicationContext(), account.getId(), PartnerShipActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } @Override - public void onResume(){ + public void onResume() { super.onResume(); - if( mastohostAcct != null){ - for(Account account: mastohostAcct){ - new RetrieveRelationshipAsyncTask(getApplicationContext(), account.getId(),PartnerShipActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + if (mastohostAcct != null) { + for (Account account : mastohostAcct) { + new RetrieveRelationshipAsyncTask(getApplicationContext(), account.getId(), PartnerShipActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } } @@ -180,11 +182,11 @@ public class PartnerShipActivity extends BaseActivity implements OnRetrieveRemot public void onRetrieveRelationship(Relationship relationship, Error error) { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, ""); - if( error != null){ + if (error != null) { return; } - for( int i = 0 ; i < mastohostAcct.size() ; i++){ - if( mastohostAcct.get(i).getId() != null && mastohostAcct.get(i).getId().equals(relationship.getId())){ + for (int i = 0; i < mastohostAcct.size(); i++) { + if (mastohostAcct.get(i).getId() != null && mastohostAcct.get(i).getId().equals(relationship.getId())) { mastohostAcct.get(i).setFollowing(relationship.isFollowing() || userId.trim().equals(relationship.getId())); mastohostAdapter.notifyDataSetChanged(); break; diff --git a/app/src/main/java/app/fedilab/android/activities/PeertubeActivity.java b/app/src/main/java/app/fedilab/android/activities/PeertubeActivity.java index c3533bef1..faab456b0 100644 --- a/app/src/main/java/app/fedilab/android/activities/PeertubeActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/PeertubeActivity.java @@ -41,6 +41,7 @@ import androidx.recyclerview.widget.LinearLayoutManager; import androidx.appcompat.widget.PopupMenu; import androidx.recyclerview.widget.RecyclerView; import androidx.appcompat.widget.Toolbar; + import android.text.Html; import android.view.LayoutInflater; import android.view.Menu; @@ -143,16 +144,17 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube private ImageView my_pp, send; private TextView add_comment_read; private EditText add_comment_write; - private String instance; + private String instance; private List playlistForVideo; private List playlists; + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); fullscreen = FullScreenMediaController.fullscreen.OFF; int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme); break; @@ -185,7 +187,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube add_comment_read = findViewById(R.id.add_comment_read); add_comment_write = findViewById(R.id.add_comment_write); peertube_playlist = findViewById(R.id.peertube_playlist); - send = findViewById(R.id.send); + send = findViewById(R.id.send); add_comment_read.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -198,10 +200,10 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube } }); Helper.changeDrawableColor(getApplicationContext(), send, R.color.mastodonC4); - if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE){ + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { write_comment_container.setVisibility(View.GONE); } - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE){ + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { peertube_playlist.setVisibility(View.VISIBLE); peertube_bookmark.setVisibility(View.GONE); } @@ -210,7 +212,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube @Override public void onClick(View v) { String comment = add_comment_write.getText().toString(); - if( comment.trim().length() > 0 ) { + if (comment.trim().length() > 0) { new PostActionAsyncTask(getApplicationContext(), API.StatusAction.PEERTUBECOMMENT, peertube.getId(), null, comment, PeertubeActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); add_comment_write.setText(""); add_comment_read.setVisibility(View.VISIBLE); @@ -227,17 +229,17 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube Account account = new AccountDAO(getApplicationContext(), db).getUniqAccount(userId, instance); Helper.loadGiF(getApplicationContext(), account.getAvatar(), my_pp); Bundle b = getIntent().getExtras(); - if(b != null) { + if (b != null) { peertubeInstance = b.getString("peertube_instance", null); videoId = b.getString("video_id", null); } - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null ) { + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); assert inflater != null; - View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); + View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close); @@ -248,7 +250,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube finish(); } }); - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Toolbar toolbar = actionBar.getCustomView().findViewById(R.id.toolbar); Helper.colorizeToolbar(toolbar, R.color.black, PeertubeActivity.this); } @@ -256,9 +258,9 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube mode = sharedpreferences.getInt(Helper.SET_VIDEO_MODE, Helper.VIDEO_MODE_DIRECT); - if( mode != Helper.VIDEO_MODE_WEBVIEW && mode != Helper.VIDEO_MODE_DIRECT) + if (mode != Helper.VIDEO_MODE_WEBVIEW && mode != Helper.VIDEO_MODE_DIRECT) mode = Helper.VIDEO_MODE_DIRECT; - if( mode == Helper.VIDEO_MODE_WEBVIEW){ + if (mode == Helper.VIDEO_MODE_WEBVIEW) { webview_video.setVisibility(View.VISIBLE); playerView.setVisibility(View.GONE); @@ -299,34 +301,34 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube } webview_video.setWebViewClient(new MastalabWebViewClient(PeertubeActivity.this)); webview_video.loadUrl("https://" + peertubeInstance + "/videos/embed/" + videoId); - }else { + } else { webview_video.setVisibility(View.GONE); playerView.setVisibility(View.VISIBLE); loader.setVisibility(View.VISIBLE); } - if( mode != Helper.VIDEO_MODE_WEBVIEW){ + if (mode != Helper.VIDEO_MODE_WEBVIEW) { playerView.setControllerShowTimeoutMs(1000); playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIT); initFullscreenDialog(); initFullscreenButton(); } - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE){ - new ManagePlaylistsAsyncTask(PeertubeActivity.this,GET_PLAYLIST, null, null, null , PeertubeActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { + new ManagePlaylistsAsyncTask(PeertubeActivity.this, GET_PLAYLIST, null, null, null, PeertubeActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } new RetrievePeertubeSingleAsyncTask(PeertubeActivity.this, peertubeInstance, videoId, PeertubeActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } - public void change(){ - if(fullscreen == FullScreenMediaController.fullscreen.ON){ + public void change() { + if (fullscreen == FullScreenMediaController.fullscreen.ON) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); Objects.requireNonNull(getSupportActionBar()).hide(); peertube_information_container.setVisibility(View.GONE); - }else{ + } else { getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN, WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN); Objects.requireNonNull(getSupportActionBar()).show(); @@ -358,7 +360,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube public static void hideKeyboard(Activity activity) { if (activity != null && activity.getWindow() != null && activity.getWindow().getDecorView() != null) { - InputMethodManager imm = (InputMethodManager)activity.getSystemService(INPUT_METHOD_SERVICE); + InputMethodManager imm = (InputMethodManager) activity.getSystemService(INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0); } } @@ -371,15 +373,16 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube menu.findItem(R.id.action_comment).setVisible(true); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if( theme == Helper.THEME_LIGHT) + if (theme == Helper.THEME_LIGHT) Helper.colorizeIconMenu(menu, R.color.black); - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE){ + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { MenuItem item = menu.findItem(R.id.action_comment); - if( item != null) + if (item != null) item.setVisible(false); } return true; } + @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { @@ -387,7 +390,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube finish(); return true; case R.id.action_comment: - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { Toasty.info(getApplicationContext(), getString(R.string.retrieve_remote_status), Toast.LENGTH_LONG).show(); new AsyncTask() { @@ -423,9 +426,9 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube contextReference.get().startActivity(intent); } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE){ - if(! peertube.isCommentsEnabled()) { - Toasty.info(getApplicationContext(), getString(R.string.comment_no_allowed_peertube),Toast.LENGTH_LONG).show(); + } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { + if (!peertube.isCommentsEnabled()) { + Toasty.info(getApplicationContext(), getString(R.string.comment_no_allowed_peertube), Toast.LENGTH_LONG).show(); return true; } int style; @@ -433,9 +436,9 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } AlertDialog.Builder builderInner; @@ -449,15 +452,15 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube builderInner.setView(input); builderInner.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog,int which) { + public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builderInner.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog,int which) { + public void onClick(DialogInterface dialog, int which) { String comment = input.getText().toString(); - if( comment.trim().length() > 0 ) { + if (comment.trim().length() > 0) { new PostActionAsyncTask(getApplicationContext(), API.StatusAction.PEERTUBECOMMENT, peertube.getId(), null, comment, PeertubeActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); dialog.dismiss(); } @@ -482,31 +485,31 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube @Override public void onRetrievePeertube(APIResponse apiResponse) { - if( apiResponse == null || (apiResponse.getError() != null) || apiResponse.getPeertubes() == null || apiResponse.getPeertubes().size() == 0){ - Toasty.error(getApplicationContext(), getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + if (apiResponse == null || (apiResponse.getError() != null) || apiResponse.getPeertubes() == null || apiResponse.getPeertubes().size() == 0) { + Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); loader.setVisibility(View.GONE); return; } - if( apiResponse.getPeertubes() == null || apiResponse.getPeertubes().get(0) == null || apiResponse.getPeertubes().get(0).getFileUrl(null) == null){ - Toasty.error(getApplicationContext(), getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + if (apiResponse.getPeertubes() == null || apiResponse.getPeertubes().get(0) == null || apiResponse.getPeertubes().get(0).getFileUrl(null) == null) { + Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); loader.setVisibility(View.GONE); return; } peertube = apiResponse.getPeertubes().get(0); - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE){ - new ManagePlaylistsAsyncTask(PeertubeActivity.this,GET_PLAYLIST_FOR_VIDEO, null, peertube.getId(), null , PeertubeActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { + new ManagePlaylistsAsyncTask(PeertubeActivity.this, GET_PLAYLIST_FOR_VIDEO, null, peertube.getId(), null, PeertubeActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } peertube_playlist.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - if( playlists != null && peertube.getId() != null) { + if (playlists != null && peertube.getId() != null) { PopupMenu popup = new PopupMenu(PeertubeActivity.this, peertube_playlist); - for(Playlist playlist: playlists){ + for (Playlist playlist : playlists) { String title = null; for (String id : playlistForVideo) { if (playlist.getId().equals(id)) { @@ -514,7 +517,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube break; } } - if( title == null){ + if (title == null) { title = playlist.getDisplayName(); } MenuItem item = popup.getMenu().add(0, 0, Menu.NONE, title); @@ -534,13 +537,13 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube return false; } }); - if(playlistForVideo.contains(playlist.getId())){ + if (playlistForVideo.contains(playlist.getId())) { item.setTitle(playlist.getDisplayName()); - new ManagePlaylistsAsyncTask(PeertubeActivity.this,ManagePlaylistsAsyncTask.action.DELETE_VIDEOS, playlist, peertube.getId(), null , PeertubeActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new ManagePlaylistsAsyncTask(PeertubeActivity.this, ManagePlaylistsAsyncTask.action.DELETE_VIDEOS, playlist, peertube.getId(), null, PeertubeActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); playlistForVideo.remove(playlist.getId()); - }else{ - item.setTitle( "✔ " + playlist.getDisplayName()); - new ManagePlaylistsAsyncTask(PeertubeActivity.this,ManagePlaylistsAsyncTask.action.ADD_VIDEOS, playlist, peertube.getId(), null , PeertubeActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + } else { + item.setTitle("✔ " + playlist.getDisplayName()); + new ManagePlaylistsAsyncTask(PeertubeActivity.this, ManagePlaylistsAsyncTask.action.ADD_VIDEOS, playlist, peertube.getId(), null, PeertubeActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); playlistForVideo.add(playlist.getId()); } return false; @@ -553,12 +556,11 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube }); - - if( peertube.isCommentsEnabled()) { + if (peertube.isCommentsEnabled()) { new RetrievePeertubeSingleCommentsAsyncTask(PeertubeActivity.this, peertubeInstance, videoId, PeertubeActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) write_comment_container.setVisibility(View.VISIBLE); - }else { + } else { RelativeLayout no_action = findViewById(R.id.no_action); TextView no_action_text = findViewById(R.id.no_action_text); no_action_text.setText(getString(R.string.comment_no_allowed_peertube)); @@ -578,11 +580,11 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube changeColor(); initResolution(); - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE){ + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { peertube_like_count.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - String newState = peertube.getMyRating().equals("like")?"none":"like"; + String newState = peertube.getMyRating().equals("like") ? "none" : "like"; new PostActionAsyncTask(getApplicationContext(), API.StatusAction.RATEVIDEO, peertube.getId(), null, newState, PeertubeActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); peertube.setMyRating(newState); changeColor(); @@ -591,20 +593,20 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube peertube_dislike_count.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - String newState = peertube.getMyRating().equals("dislike")?"none":"dislike"; + String newState = peertube.getMyRating().equals("dislike") ? "none" : "dislike"; new PostActionAsyncTask(getApplicationContext(), API.StatusAction.RATEVIDEO, peertube.getId(), null, newState, PeertubeActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); peertube.setMyRating(newState); changeColor(); } }); - }else{ + } else { peertube_like_count.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - String newState = peertube.getMyRating().equals("like")?"none":"like"; + String newState = peertube.getMyRating().equals("like") ? "none" : "like"; Status status = new Status(); status.setUri("https://" + peertube.getAccount().getHost() + "/videos/watch/" + peertube.getUuid()); - CrossActions.doCrossAction(getApplicationContext(), RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE, status, null, API.StatusAction.FAVOURITE, null, PeertubeActivity.this, true); + CrossActions.doCrossAction(getApplicationContext(), RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE, status, null, API.StatusAction.FAVOURITE, null, PeertubeActivity.this, true); peertube.setMyRating(newState); changeColor(); } @@ -612,10 +614,10 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube peertube_dislike_count.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - String newState = peertube.getMyRating().equals("dislike")?"none":"dislike"; + String newState = peertube.getMyRating().equals("dislike") ? "none" : "dislike"; Status status = new Status(); status.setUri("https://" + peertube.getAccount().getHost() + "/videos/watch/" + peertube.getUuid()); - CrossActions.doCrossAction(getApplicationContext(), RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE, status, null, API.StatusAction.UNFAVOURITE, null, PeertubeActivity.this, true); + CrossActions.doCrossAction(getApplicationContext(), RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE, status, null, API.StatusAction.UNFAVOURITE, null, PeertubeActivity.this, true); peertube.setMyRating(newState); changeColor(); } @@ -630,7 +632,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube e.printStackTrace(); } - if( mode == Helper.VIDEO_MODE_DIRECT){ + if (mode == Helper.VIDEO_MODE_DIRECT) { DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(getApplicationContext(), Util.getUserAgent(getApplicationContext(), "Mastalab"), null); @@ -647,17 +649,16 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube } - peertube_download.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - if(Build.VERSION.SDK_INT >= 23 ){ + if (Build.VERSION.SDK_INT >= 23) { if (ContextCompat.checkSelfPermission(PeertubeActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(PeertubeActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(PeertubeActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, Helper.EXTERNAL_STORAGE_REQUEST_CODE); } else { Helper.manageDownloads(PeertubeActivity.this, peertube.getFileDownloadUrl(null)); } - }else{ + } else { Helper.manageDownloads(PeertubeActivity.this, peertube.getFileDownloadUrl(null)); } } @@ -667,7 +668,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube Drawable img; - if( peertubes == null || peertubes.size() == 0) + if (peertubes == null || peertubes.size() == 0) img = ContextCompat.getDrawable(PeertubeActivity.this, R.drawable.ic_bookmark_peertube_border); else img = ContextCompat.getDrawable(PeertubeActivity.this, R.drawable.ic_bookmark_peertube); @@ -677,17 +678,17 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube @Override public void onClick(View v) { List peertubes = new PeertubeFavoritesDAO(PeertubeActivity.this, db).getSinglePeertube(peertube); - if( peertubes == null || peertubes.size() == 0){ + if (peertubes == null || peertubes.size() == 0) { new PeertubeFavoritesDAO(PeertubeActivity.this, db).insert(peertube); - Toasty.success(getApplicationContext(),getString(R.string.bookmark_add_peertube), Toast.LENGTH_SHORT).show(); - }else{ + Toasty.success(getApplicationContext(), getString(R.string.bookmark_add_peertube), Toast.LENGTH_SHORT).show(); + } else { new PeertubeFavoritesDAO(PeertubeActivity.this, db).remove(peertube); - Toasty.success(getApplicationContext(),getString(R.string.bookmark_remove_peertube), Toast.LENGTH_SHORT).show(); + Toasty.success(getApplicationContext(), getString(R.string.bookmark_remove_peertube), Toast.LENGTH_SHORT).show(); } - if( peertubes != null && peertubes.size() > 0) //Was initially in cache - peertube_bookmark.setCompoundDrawablesWithIntrinsicBounds( null, ContextCompat.getDrawable(PeertubeActivity.this, R.drawable.ic_bookmark_peertube_border), null ,null); + if (peertubes != null && peertubes.size() > 0) //Was initially in cache + peertube_bookmark.setCompoundDrawablesWithIntrinsicBounds(null, ContextCompat.getDrawable(PeertubeActivity.this, R.drawable.ic_bookmark_peertube_border), null, null); else - peertube_bookmark.setCompoundDrawablesWithIntrinsicBounds( null, ContextCompat.getDrawable(PeertubeActivity.this, R.drawable.ic_bookmark_peertube), null ,null); + peertube_bookmark.setCompoundDrawablesWithIntrinsicBounds(null, ContextCompat.getDrawable(PeertubeActivity.this, R.drawable.ic_bookmark_peertube), null, null); } }); @@ -698,11 +699,11 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube sendIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.shared_via)); String url; - url = "https://" +peertube.getInstance() + "/videos/watch/"+ peertube.getUuid(); + url = "https://" + peertube.getInstance() + "/videos/watch/" + peertube.getUuid(); boolean share_details = sharedpreferences.getBoolean(Helper.SET_SHARE_DETAILS, true); String extra_text; - if( share_details) { - extra_text = "@" +peertube.getAccount().getAcct(); + if (share_details) { + extra_text = "@" + peertube.getAccount().getAcct(); extra_text += "\r\n\r\n" + peertube.getName(); extra_text += "\n\n" + Helper.shortnameToUnicode(":link:", true) + " " + url + "\r\n-\n"; final String contentToot; @@ -712,7 +713,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube //noinspection deprecation contentToot = Html.fromHtml(peertube.getDescription()).toString(); extra_text += contentToot; - }else { + } else { extra_text = url; } sendIntent.putExtra(Intent.EXTRA_TEXT, extra_text); @@ -727,7 +728,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); - if( mode != Helper.VIDEO_MODE_WEBVIEW) { + if (mode != Helper.VIDEO_MODE_WEBVIEW) { if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { openFullscreenDialog(); setFullscreen(FullScreenMediaController.fullscreen.ON); @@ -736,8 +737,8 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube setFullscreen(FullScreenMediaController.fullscreen.OFF); } change(); - }else { - final ViewGroup videoLayout = findViewById(R.id.videoLayout); + } else { + final ViewGroup videoLayout = findViewById(R.id.videoLayout); if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { setFullscreen(FullScreenMediaController.fullscreen.ON); } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { @@ -752,22 +753,22 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube @Override public void onRetrievePeertubeComments(APIResponse apiResponse) { - if( apiResponse == null || (apiResponse.getError() != null && apiResponse.getError().getStatusCode() != 404) ){ - if( apiResponse == null) - Toasty.error(getApplicationContext(), getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + if (apiResponse == null || (apiResponse.getError() != null && apiResponse.getError().getStatusCode() != 404)) { + if (apiResponse == null) + Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); else - Toasty.error(getApplicationContext(), apiResponse.getError().getError(),Toast.LENGTH_LONG).show(); + Toasty.error(getApplicationContext(), apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); return; } List statuses = apiResponse.getStatuses(); RecyclerView lv_comments = findViewById(R.id.peertube_comments); - if( statuses == null || statuses.size() == 0){ - if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { + if (statuses == null || statuses.size() == 0) { + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { RelativeLayout no_action = findViewById(R.id.no_action); no_action.setVisibility(View.VISIBLE); lv_comments.setVisibility(View.GONE); } - }else { + } else { lv_comments.setVisibility(View.VISIBLE); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); boolean isOnWifi = Helper.isOnWIFI(PeertubeActivity.this); @@ -789,43 +790,43 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube @Override public void onDestroy() { super.onDestroy(); - if( player != null) + if (player != null) player.release(); } @Override protected void onPause() { super.onPause(); - if( player != null) { + if (player != null) { player.setPlayWhenReady(false); } } @Override - public void onResume(){ + public void onResume() { super.onResume(); - if( player != null) { + if (player != null) { player.setPlayWhenReady(true); } } - public void displayResolution(){ + public void displayResolution() { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } AlertDialog.Builder builderSingle = new AlertDialog.Builder(PeertubeActivity.this, style); builderSingle.setTitle(R.string.pickup_resolution); final ArrayAdapter arrayAdapter = new ArrayAdapter(PeertubeActivity.this, android.R.layout.select_dialog_item); - for(String resolution: peertube.getResolution()) - arrayAdapter.add(resolution+"p"); + for (String resolution : peertube.getResolution()) + arrayAdapter.add(resolution + "p"); builderSingle.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { @@ -837,14 +838,14 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube public void onClick(DialogInterface dialog, int which) { String res = arrayAdapter.getItem(which).substring(0, arrayAdapter.getItem(which).length() - 1); - if( playerView != null) { + if (playerView != null) { loader.setVisibility(View.VISIBLE); long position = player.getCurrentPosition(); PlaybackControlView controlView = playerView.findViewById(R.id.exo_controller); resolution = controlView.findViewById(R.id.resolution); - resolution.setText(String.format("%sp",res)); - if( mode == Helper.VIDEO_MODE_DIRECT){ - if( player != null) + resolution.setText(String.format("%sp", res)); + if (mode == Helper.VIDEO_MODE_DIRECT) { + if (player != null) player.release(); player = ExoPlayerFactory.newSimpleInstance(PeertubeActivity.this); playerView.setPlayer(player); @@ -868,7 +869,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube @Override public void onPostAction(int statusCode, API.StatusAction statusAction, String userId, Error error) { - if( peertube.isCommentsEnabled() && statusAction == API.StatusAction.PEERTUBECOMMENT) + if (peertube.isCommentsEnabled() && statusAction == API.StatusAction.PEERTUBECOMMENT) new RetrievePeertubeSingleCommentsAsyncTask(PeertubeActivity.this, peertubeInstance, videoId, PeertubeActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } @@ -923,7 +924,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube private void initResolution() { PlaybackControlView controlView = playerView.findViewById(R.id.exo_controller); resolution = controlView.findViewById(R.id.resolution); - resolution.setText(String.format("%sp",peertube.getResolution().get(0))); + resolution.setText(String.format("%sp", peertube.getResolution().get(0))); resolution.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -933,30 +934,29 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube } - - private void changeColor(){ - if( peertube.getMyRating() != null && peertube.getMyRating().equals("like")){ - changeDrawableColor(getApplicationContext(), R.drawable.ic_thumb_up_peertube,R.color.positive_thumbs); - changeDrawableColor(getApplicationContext(), R.drawable.ic_thumb_down_peertube,R.color.neutral_thumbs); - }else if( peertube.getMyRating() != null && peertube.getMyRating().equals("dislike")){ - changeDrawableColor(getApplicationContext(), R.drawable.ic_thumb_up_peertube,R.color.neutral_thumbs); - changeDrawableColor(getApplicationContext(), R.drawable.ic_thumb_down_peertube,R.color.negative_thumbs); - }else { - changeDrawableColor(getApplicationContext(), R.drawable.ic_thumb_up_peertube,R.color.neutral_thumbs); - changeDrawableColor(getApplicationContext(), R.drawable.ic_thumb_down_peertube,R.color.neutral_thumbs); + private void changeColor() { + if (peertube.getMyRating() != null && peertube.getMyRating().equals("like")) { + changeDrawableColor(getApplicationContext(), R.drawable.ic_thumb_up_peertube, R.color.positive_thumbs); + changeDrawableColor(getApplicationContext(), R.drawable.ic_thumb_down_peertube, R.color.neutral_thumbs); + } else if (peertube.getMyRating() != null && peertube.getMyRating().equals("dislike")) { + changeDrawableColor(getApplicationContext(), R.drawable.ic_thumb_up_peertube, R.color.neutral_thumbs); + changeDrawableColor(getApplicationContext(), R.drawable.ic_thumb_down_peertube, R.color.negative_thumbs); + } else { + changeDrawableColor(getApplicationContext(), R.drawable.ic_thumb_up_peertube, R.color.neutral_thumbs); + changeDrawableColor(getApplicationContext(), R.drawable.ic_thumb_down_peertube, R.color.neutral_thumbs); } Drawable thumbUp = ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_thumb_up_peertube); Drawable thumbDown = ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_thumb_down_peertube); - peertube_like_count.setCompoundDrawablesWithIntrinsicBounds( null, thumbUp, null, null); - peertube_dislike_count.setCompoundDrawablesWithIntrinsicBounds( null, thumbDown, null, null); + peertube_like_count.setCompoundDrawablesWithIntrinsicBounds(null, thumbUp, null, null); + peertube_dislike_count.setCompoundDrawablesWithIntrinsicBounds(null, thumbDown, null, null); } @Override public void onActionDone(ManagePlaylistsAsyncTask.action actionType, APIResponse apiResponse, int statusCode) { - if( actionType == GET_PLAYLIST_FOR_VIDEO && apiResponse != null) { + if (actionType == GET_PLAYLIST_FOR_VIDEO && apiResponse != null) { playlistForVideo = apiResponse.getPlaylistForVideos(); - }else if( actionType == GET_PLAYLIST && apiResponse != null){ + } else if (actionType == GET_PLAYLIST && apiResponse != null) { playlists = apiResponse.getPlaylists(); } } diff --git a/app/src/main/java/app/fedilab/android/activities/PeertubeEditUploadActivity.java b/app/src/main/java/app/fedilab/android/activities/PeertubeEditUploadActivity.java index 79d660566..b79cbb070 100644 --- a/app/src/main/java/app/fedilab/android/activities/PeertubeEditUploadActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/PeertubeEditUploadActivity.java @@ -21,9 +21,11 @@ import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; + import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.Toolbar; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -86,7 +88,7 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme); break; @@ -101,19 +103,19 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie } Bundle b = getIntent().getExtras(); - if(b != null) { + if (b != null) { videoId = b.getString("video_id", null); } - if( videoId == null){ + if (videoId == null) { videoId = sharedpreferences.getString(Helper.VIDEO_ID, null); } - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null ) { + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); assert inflater != null; - View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); + View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close); @@ -125,7 +127,7 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie } }); toolbar_title.setText(R.string.update_video); - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Toolbar toolbar = actionBar.getCustomView().findViewById(R.id.toolbar); Helper.colorizeToolbar(toolbar, R.color.black, PeertubeEditUploadActivity.this); } @@ -147,7 +149,6 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie set_upload_enable_comments = findViewById(R.id.set_upload_enable_comments); - //Change spinner colors Helper.changeMaterialSpinnerColor(PeertubeEditUploadActivity.this, set_upload_channel); Helper.changeMaterialSpinnerColor(PeertubeEditUploadActivity.this, set_upload_categories); @@ -165,22 +166,22 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } builderInner = new AlertDialog.Builder(PeertubeEditUploadActivity.this, style); builderInner.setMessage(getString(R.string.delete_video_confirmation)); builderInner.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog,int which) { + public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builderInner.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog,int which) { + public void onClick(DialogInterface dialog, int which) { new PostActionAsyncTask(getApplicationContext(), API.StatusAction.PEERTUBEDELETEVIDEO, videoId, PeertubeEditUploadActivity.this).executeOnExecutor(THREAD_POOL_EXECUTOR); dialog.dismiss(); } @@ -189,23 +190,23 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie } }); //Get params from the API - LinkedHashMap categories = new LinkedHashMap<>(peertubeInformation.getCategories()); + LinkedHashMap categories = new LinkedHashMap<>(peertubeInformation.getCategories()); LinkedHashMap licences = new LinkedHashMap<>(peertubeInformation.getLicences()); LinkedHashMap privacies = new LinkedHashMap<>(peertubeInformation.getPrivacies()); LinkedHashMap languages = new LinkedHashMap<>(peertubeInformation.getLanguages()); LinkedHashMap translations = null; - if( peertubeInformation.getTranslations() != null) + if (peertubeInformation.getTranslations() != null) translations = new LinkedHashMap<>(peertubeInformation.getTranslations()); //Populate catgories String[] categoriesA = new String[categories.size()]; Iterator it = categories.entrySet().iterator(); int i = 0; while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - if( translations == null ||translations.size() == 0 || !translations.containsKey((String)pair.getValue())) - categoriesA[i] = (String)pair.getValue(); + Map.Entry pair = (Map.Entry) it.next(); + if (translations == null || translations.size() == 0 || !translations.containsKey((String) pair.getValue())) + categoriesA[i] = (String) pair.getValue(); else - categoriesA[i] = translations.get((String)pair.getValue()); + categoriesA[i] = translations.get((String) pair.getValue()); it.remove(); i++; } @@ -214,17 +215,16 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie set_upload_categories.setAdapter(adapterCatgories); - //Populate licenses String[] licensesA = new String[licences.size()]; it = licences.entrySet().iterator(); i = 0; while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - if( translations == null || translations.size() == 0 || !translations.containsKey((String)pair.getValue())) - licensesA[i] = (String)pair.getValue(); + Map.Entry pair = (Map.Entry) it.next(); + if (translations == null || translations.size() == 0 || !translations.containsKey((String) pair.getValue())) + licensesA[i] = (String) pair.getValue(); else - licensesA[i] = translations.get((String)pair.getValue()); + licensesA[i] = translations.get((String) pair.getValue()); it.remove(); i++; } @@ -238,11 +238,11 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie it = languages.entrySet().iterator(); i = 0; while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - if( translations == null || translations.size() == 0 || !translations.containsKey((String)pair.getValue())) - languagesA[i] = (String)pair.getValue(); + Map.Entry pair = (Map.Entry) it.next(); + if (translations == null || translations.size() == 0 || !translations.containsKey((String) pair.getValue())) + languagesA[i] = (String) pair.getValue(); else - languagesA[i] = translations.get((String)pair.getValue()); + languagesA[i] = translations.get((String) pair.getValue()); it.remove(); i++; } @@ -256,11 +256,11 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie it = privacies.entrySet().iterator(); i = 0; while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - if( translations == null || translations.size() == 0 || !translations.containsKey((String)pair.getValue())) - privaciesA[i] = (String)pair.getValue(); + Map.Entry pair = (Map.Entry) it.next(); + if (translations == null || translations.size() == 0 || !translations.containsKey((String) pair.getValue())) + privaciesA[i] = (String) pair.getValue(); else - privaciesA[i] = translations.get((String)pair.getValue()); + privaciesA[i] = translations.get((String) pair.getValue()); it.remove(); i++; } @@ -278,12 +278,10 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie } - - @Override public void onRetrievePeertube(APIResponse apiResponse) { - if( apiResponse.getError() != null || apiResponse.getPeertubes() == null || apiResponse.getPeertubes().size() == 0){ - if ( apiResponse.getError() != null && apiResponse.getError().getError() != null) + if (apiResponse.getError() != null || apiResponse.getPeertubes() == null || apiResponse.getPeertubes().size() == 0) { + if (apiResponse.getError() != null && apiResponse.getError().getError() != null) Toasty.error(getApplicationContext(), apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); else Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); @@ -294,11 +292,11 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie //Peertube video Peertube peertube = apiResponse.getPeertubes().get(0); - if( peertube.isUpdate()){ + if (peertube.isUpdate()) { Toasty.success(getApplicationContext(), getString(R.string.toast_peertube_video_updated), Toast.LENGTH_LONG).show(); peertube.setUpdate(false); set_upload_submit.setEnabled(true); - }else { + } else { new RetrievePeertubeChannelsAsyncTask(PeertubeEditUploadActivity.this, PeertubeEditUploadActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } @@ -308,54 +306,54 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie categoryToSend = peertube.getCategory(); - if( languageToSend == null){ + if (languageToSend == null) { LinkedHashMap languages = new LinkedHashMap<>(peertubeInformation.getLanguages()); - Map.Entry entryString = languages.entrySet().iterator().next(); + Map.Entry entryString = languages.entrySet().iterator().next(); languageToSend = new HashMap<>(); languageToSend.put(entryString.getKey(), entryString.getValue()); } - if( licenseToSend == null){ + if (licenseToSend == null) { LinkedHashMap licences = new LinkedHashMap<>(peertubeInformation.getLicences()); - Map.Entry entryInt = licences.entrySet().iterator().next(); + Map.Entry entryInt = licences.entrySet().iterator().next(); licenseToSend = new HashMap<>(); licenseToSend.put(entryInt.getKey(), entryInt.getValue()); } - if( categoryToSend == null){ + if (categoryToSend == null) { LinkedHashMap categories = new LinkedHashMap<>(peertubeInformation.getCategories()); - Map.Entry entryInt = categories.entrySet().iterator().next(); + Map.Entry entryInt = categories.entrySet().iterator().next(); categoryToSend = new HashMap<>(); categoryToSend.put(entryInt.getKey(), entryInt.getValue()); } - if( privacyToSend == null){ + if (privacyToSend == null) { LinkedHashMap privacies = new LinkedHashMap<>(peertubeInformation.getPrivacies()); - Map.Entry entryInt = privacies.entrySet().iterator().next(); + Map.Entry entryInt = privacies.entrySet().iterator().next(); privacyToSend = new HashMap<>(); privacyToSend.put(entryInt.getKey(), entryInt.getValue()); } String language = null; - if( languageToSend != null) { + if (languageToSend != null) { Map.Entry entryString = languageToSend.entrySet().iterator().next(); language = entryString.getValue(); } String license = null; - if( licenseToSend != null) { + if (licenseToSend != null) { Map.Entry entryInt = licenseToSend.entrySet().iterator().next(); license = entryInt.getValue(); } String privacy = null; - if( privacyToSend != null) { + if (privacyToSend != null) { Map.Entry entryInt = privacyToSend.entrySet().iterator().next(); privacy = entryInt.getValue(); } String category = null; - if( categoryToSend != null) { + if (categoryToSend != null) { Map.Entry entryInt = categoryToSend.entrySet().iterator().next(); category = entryInt.getValue(); } @@ -377,49 +375,49 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie LinkedHashMap privacies = new LinkedHashMap<>(peertubeInformation.getPrivacies()); LinkedHashMap languages = new LinkedHashMap<>(peertubeInformation.getLanguages()); LinkedHashMap translations = null; - if( peertubeInformation.getTranslations() != null) + if (peertubeInformation.getTranslations() != null) translations = new LinkedHashMap<>(peertubeInformation.getTranslations()); int languagePosition = 0; - if( languages.containsValue(language)){ + if (languages.containsValue(language)) { Iterator it = languages.entrySet().iterator(); while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - if(pair.getValue().equals(language)) + Map.Entry pair = (Map.Entry) it.next(); + if (pair.getValue().equals(language)) break; it.remove(); languagePosition++; } } int privacyPosition = 0; - if( privacy != null && privacies.containsValue(privacy)){ + if (privacy != null && privacies.containsValue(privacy)) { Iterator it = privacies.entrySet().iterator(); while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - if(pair.getValue().equals(privacy)) + Map.Entry pair = (Map.Entry) it.next(); + if (pair.getValue().equals(privacy)) break; it.remove(); privacyPosition++; } } int licensePosition = 0; - if( license != null && licences.containsValue(license)){ + if (license != null && licences.containsValue(license)) { Iterator it = licences.entrySet().iterator(); while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - if(pair.getValue().equals(license)) + Map.Entry pair = (Map.Entry) it.next(); + if (pair.getValue().equals(license)) break; it.remove(); licensePosition++; } } int categoryPosition = 0; - if(category != null && categories.containsValue(category)){ + if (category != null && categories.containsValue(category)) { Iterator it = categories.entrySet().iterator(); while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - if(pair.getValue().equals(category)) + Map.Entry pair = (Map.Entry) it.next(); + if (pair.getValue().equals(category)) break; it.remove(); categoryPosition++; @@ -434,10 +432,10 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie Iterator it = privaciesCheck.entrySet().iterator(); int i = 0; while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - if( i == position){ + Map.Entry pair = (Map.Entry) it.next(); + if (i == position) { privacyToSend = new HashMap<>(); - privacyToSend.put((Integer)pair.getKey(), (String)pair.getValue()); + privacyToSend.put((Integer) pair.getKey(), (String) pair.getValue()); break; } it.remove(); @@ -453,10 +451,10 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie Iterator it = licensesCheck.entrySet().iterator(); int i = 0; while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - if( i == position){ + Map.Entry pair = (Map.Entry) it.next(); + if (i == position) { licenseToSend = new HashMap<>(); - licenseToSend.put((Integer)pair.getKey(), (String)pair.getValue()); + licenseToSend.put((Integer) pair.getKey(), (String) pair.getValue()); break; } it.remove(); @@ -472,10 +470,10 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie Iterator it = categoriesCheck.entrySet().iterator(); int i = 0; while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - if( i == position){ + Map.Entry pair = (Map.Entry) it.next(); + if (i == position) { categoryToSend = new HashMap<>(); - categoryToSend.put((Integer)pair.getKey(), (String)pair.getValue()); + categoryToSend.put((Integer) pair.getKey(), (String) pair.getValue()); break; } it.remove(); @@ -491,10 +489,10 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie Iterator it = languagesCheck.entrySet().iterator(); int i = 0; while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - if( i == position){ + Map.Entry pair = (Map.Entry) it.next(); + if (i == position) { languageToSend = new HashMap<>(); - languageToSend.put((String)pair.getKey(), (String)pair.getValue()); + languageToSend.put((String) pair.getKey(), (String) pair.getValue()); break; } it.remove(); @@ -512,10 +510,10 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie Iterator it = channelsCheck.entrySet().iterator(); int i = 0; while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - if( i == position){ + Map.Entry pair = (Map.Entry) it.next(); + if (i == position) { channelToSend = new HashMap<>(); - channelToSend.put((String)pair.getKey(), (String)pair.getValue()); + channelToSend.put((String) pair.getKey(), (String) pair.getValue()); break; } @@ -555,7 +553,7 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie set_upload_categories.setSelectedIndex(categoryPosition); List tags = peertube.getTags(); - if( tags != null && tags.size() > 0) { + if (tags != null && tags.size() > 0) { String[] tagsA = tags.toArray(new String[tags.size()]); p_video_tags.setTags(tagsA); } @@ -569,8 +567,8 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie @Override public void onRetrievePeertubeChannels(APIResponse apiResponse) { - if( apiResponse.getError() != null || apiResponse.getAccounts() == null || apiResponse.getAccounts().size() == 0){ - if ( apiResponse.getError().getError() != null) + if (apiResponse.getError() != null || apiResponse.getAccounts() == null || apiResponse.getAccounts().size() == 0) { + if (apiResponse.getError().getError() != null) Toasty.error(getApplicationContext(), apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); else Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); @@ -581,8 +579,8 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie List accounts = apiResponse.getAccounts(); String[] channelName = new String[accounts.size()]; int i = 0; - for(Account account: accounts){ - channels.put(account.getUsername(),account.getId()); + for (Account account : accounts) { + channels.put(account.getUsername(), account.getId()); channelName[i] = account.getUsername(); i++; } @@ -591,14 +589,14 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie set_upload_channel.setAdapter(adapterChannel); int channelPosition = 0; - if( channels.containsKey(channel.getUsername())){ + if (channels.containsKey(channel.getUsername())) { LinkedHashMap channelsIterator = new LinkedHashMap<>(channels); Iterator it = channelsIterator.entrySet().iterator(); while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - if(pair.getKey().equals(channel.getUsername())) { + Map.Entry pair = (Map.Entry) it.next(); + if (pair.getKey().equals(channel.getUsername())) { channelToSend = new HashMap<>(); - channelToSend.put((String)pair.getKey(), (String)pair.getValue()); + channelToSend.put((String) pair.getKey(), (String) pair.getValue()); break; } it.remove(); diff --git a/app/src/main/java/app/fedilab/android/activities/PeertubeUploadActivity.java b/app/src/main/java/app/fedilab/android/activities/PeertubeUploadActivity.java index a36411685..8efdae64e 100644 --- a/app/src/main/java/app/fedilab/android/activities/PeertubeUploadActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/PeertubeUploadActivity.java @@ -29,10 +29,12 @@ import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.provider.OpenableColumns; + import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.appcompat.app.ActionBar; import androidx.appcompat.widget.Toolbar; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -95,7 +97,7 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme); break; @@ -108,13 +110,13 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe default: setTheme(R.style.AppThemeDark); } - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null ) { + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); assert inflater != null; - View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); + View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close); @@ -126,7 +128,7 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe } }); toolbar_title.setText(R.string.upload_video); - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Toolbar toolbar = actionBar.getCustomView().findViewById(R.id.toolbar); Helper.colorizeToolbar(toolbar, R.color.black, PeertubeUploadActivity.this); } @@ -151,13 +153,12 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe } - @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_IVDEO && resultCode == Activity.RESULT_OK) { if (data == null || data.getData() == null) { - Toasty.error(getApplicationContext(),getString(R.string.toot_select_image_error),Toast.LENGTH_LONG).show(); + Toasty.error(getApplicationContext(), getString(R.string.toot_select_image_error), Toast.LENGTH_LONG).show(); return; } set_upload_submit.setEnabled(true); @@ -180,7 +181,7 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe } else if (uriString.startsWith("file://")) { filename = myFile.getName(); } - if( filename != null) { + if (filename != null) { set_upload_file_name.setVisibility(View.VISIBLE); set_upload_file_name.setText(filename); } @@ -206,8 +207,8 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe @Override public void onRetrievePeertubeChannels(APIResponse apiResponse) { - if( apiResponse.getError() != null || apiResponse.getAccounts() == null || apiResponse.getAccounts().size() == 0){ - if ( apiResponse.getError() != null && apiResponse.getError().getError() != null) + if (apiResponse.getError() != null || apiResponse.getAccounts() == null || apiResponse.getAccounts().size() == 0) { + if (apiResponse.getError() != null && apiResponse.getError().getError() != null) Toasty.error(getApplicationContext(), apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); else Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); @@ -217,10 +218,10 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe //Populate channels List accounts = apiResponse.getAccounts(); String[] channelName = new String[accounts.size()]; - String[] channelId= new String[accounts.size()]; + String[] channelId = new String[accounts.size()]; int i = 0; - for(Account account: accounts){ - channels.put(account.getUsername(),account.getId()); + for (Account account : accounts) { + channels.put(account.getUsername(), account.getId()); channelName[i] = account.getUsername(); channelId[i] = account.getId(); i++; @@ -233,11 +234,11 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe set_upload_channel.setAdapter(adapterChannel); LinkedHashMap translations = null; - if( peertubeInformation.getTranslations() != null) + if (peertubeInformation.getTranslations() != null) translations = new LinkedHashMap<>(peertubeInformation.getTranslations()); LinkedHashMap privaciesInit = new LinkedHashMap<>(peertubeInformation.getPrivacies()); - Map.Entry entryInt = privaciesInit.entrySet().iterator().next(); + Map.Entry entryInt = privaciesInit.entrySet().iterator().next(); privacyToSend = new HashMap<>(); privacyToSend.put(entryInt.getKey(), entryInt.getValue()); LinkedHashMap privacies = new LinkedHashMap<>(peertubeInformation.getPrivacies()); @@ -246,11 +247,11 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe Iterator it = privacies.entrySet().iterator(); i = 0; while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - if( translations == null || translations.size() == 0 || !translations.containsKey((String)pair.getValue())) - privaciesA[i] = (String)pair.getValue(); + Map.Entry pair = (Map.Entry) it.next(); + if (translations == null || translations.size() == 0 || !translations.containsKey((String) pair.getValue())) + privaciesA[i] = (String) pair.getValue(); else - privaciesA[i] = translations.get((String)pair.getValue()); + privaciesA[i] = translations.get((String) pair.getValue()); it.remove(); i++; } @@ -267,10 +268,10 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe Iterator it = privaciesCheck.entrySet().iterator(); int i = 0; while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - if( i == position){ + Map.Entry pair = (Map.Entry) it.next(); + if (i == position) { privacyToSend = new HashMap<>(); - privacyToSend.put((Integer)pair.getKey(), (String)pair.getValue()); + privacyToSend.put((Integer) pair.getKey(), (String) pair.getValue()); break; } it.remove(); @@ -300,11 +301,11 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe String[] mimetypes = {"video/*"}; intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes); startActivityForResult(intent, PICK_IVDEO); - }else { + } else { intent.setType("video/*"); Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); Intent chooserIntent = Intent.createChooser(intent, getString(R.string.toot_select_image)); - chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent}); + chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{pickIntent}); startActivityForResult(chooserIntent, PICK_IVDEO); } @@ -319,10 +320,10 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe Iterator it = channelsCheck.entrySet().iterator(); int i = 0; while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - if( i == position){ + Map.Entry pair = (Map.Entry) it.next(); + if (i == position) { channelToSend = new HashMap<>(); - channelToSend.put((String)pair.getKey(), (String)pair.getValue()); + channelToSend.put((String) pair.getKey(), (String) pair.getValue()); break; } @@ -334,7 +335,7 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe set_upload_submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - if( uri != null) { + if (uri != null) { Map.Entry channelM = channelToSend.entrySet().iterator().next(); String idChannel = channelM.getValue(); Map.Entry privacyM = privacyToSend.entrySet().iterator().next(); @@ -344,7 +345,7 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); String token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); UploadNotificationConfig uploadConfig = new UploadNotificationConfig(); - Intent in = new Intent(getApplicationContext(), PeertubeEditUploadActivity.class ); + Intent in = new Intent(getApplicationContext(), PeertubeEditUploadActivity.class); PendingIntent clickIntent = PendingIntent.getActivity(getApplicationContext(), 1, in, PendingIntent.FLAG_UPDATE_CURRENT); uploadConfig .setClearOnActionForAllStatuses(true); @@ -359,7 +360,7 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe String uploadId = UUID.randomUUID().toString(); uploadReceiver.setUploadID(uploadId); new MultipartUploadRequest(PeertubeUploadActivity.this, uploadId, "https://" + Helper.getLiveInstance(PeertubeUploadActivity.this) + "/api/v1/videos/upload") - .addFileToUpload(uri.toString().replace("file://",""), "videofile") + .addFileToUpload(uri.toString().replace("file://", ""), "videofile") .addHeader("Authorization", "Bearer " + token) .setNotificationConfig(uploadConfig) .addParameter("name", filename) @@ -370,7 +371,7 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe .addParameter("waitTranscoding", "true") .setMaxRetries(2) .startUpload(); - finish(); + finish(); } catch (Exception exc) { exc.printStackTrace(); } @@ -380,7 +381,6 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe } - @Override public void onProgress(Context context, UploadInfo uploadInfo) { // your code here diff --git a/app/src/main/java/app/fedilab/android/activities/PhotoEditorActivity.java b/app/src/main/java/app/fedilab/android/activities/PhotoEditorActivity.java index 6829af629..76588895d 100644 --- a/app/src/main/java/app/fedilab/android/activities/PhotoEditorActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/PhotoEditorActivity.java @@ -18,6 +18,7 @@ import android.annotation.SuppressLint; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; + import androidx.annotation.NonNull; import androidx.exifinterface.media.ExifInterface; import androidx.localbroadcastmanager.content.LocalBroadcastManager; @@ -46,6 +47,7 @@ import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Typeface; import android.provider.MediaStore; + import androidx.constraintlayout.widget.ConstraintLayout; import androidx.constraintlayout.widget.ConstraintSet; import androidx.transition.ChangeBounds; @@ -53,6 +55,7 @@ import androidx.transition.TransitionManager; import androidx.appcompat.app.AlertDialog; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; + import android.view.View; import android.view.animation.AnticipateOvershootInterpolator; import android.widget.Button; @@ -74,7 +77,7 @@ import ja.burhanrashid52.photoeditor.SaveSettings; import ja.burhanrashid52.photoeditor.ViewType; -public class PhotoEditorActivity extends BaseActivity implements OnPhotoEditorListener, +public class PhotoEditorActivity extends BaseActivity implements OnPhotoEditorListener, View.OnClickListener, PropertiesBSFragment.Properties, EmojiBSFragment.EmojiListener, @@ -107,7 +110,7 @@ public class PhotoEditorActivity extends BaseActivity implements OnPhotoEditorL requestWindowFeature(Window.FEATURE_NO_TITLE); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme); break; @@ -122,12 +125,12 @@ public class PhotoEditorActivity extends BaseActivity implements OnPhotoEditorL } Bundle b = getIntent().getExtras(); - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().hide(); String path = null; - if(b != null) + if (b != null) path = b.getString("imageUri", null); - if( path == null) { + if (path == null) { finish(); } uri = Uri.parse(path); @@ -156,7 +159,6 @@ public class PhotoEditorActivity extends BaseActivity implements OnPhotoEditorL mRvFilters.setAdapter(mFilterViewAdapter); - Typeface mEmojiTypeFace = Typeface.createFromAsset(getAssets(), "emojione-android.ttf"); mPhotoEditor = new PhotoEditor.Builder(this, mPhotoEditorView) @@ -165,14 +167,13 @@ public class PhotoEditorActivity extends BaseActivity implements OnPhotoEditorL .build(); // build photo editor sdk - mPhotoEditor.setOnPhotoEditorListener(this); //Set Image Dynamically mPhotoEditorView.getSource().setImageURI(uri); - if( uri != null ) { + if (uri != null) { try (InputStream inputStream = getContentResolver().openInputStream(uri)) { assert inputStream != null; ExifInterface exif = new ExifInterface(inputStream); @@ -196,9 +197,13 @@ public class PhotoEditorActivity extends BaseActivity implements OnPhotoEditorL } private static int exifToDegrees(int exifOrientation) { - if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) { return 90; } - else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) { return 180; } - else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) { return 270; } + if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) { + return 90; + } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) { + return 180; + } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) { + return 270; + } return 0; } @@ -306,9 +311,9 @@ public class PhotoEditorActivity extends BaseActivity implements OnPhotoEditorL showLoading(getString(R.string.saving)); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); String myDir = sharedpreferences.getString(Helper.SET_FOLDER_RECORD, getCacheDir().getAbsolutePath()); - String filename = System.currentTimeMillis()+"_"+Helper.getFileName(PhotoEditorActivity.this, uri); + String filename = System.currentTimeMillis() + "_" + Helper.getFileName(PhotoEditorActivity.this, uri); - File file = new File(myDir+"/"+filename); + File file = new File(myDir + "/" + filename); try { file.createNewFile(); @@ -323,7 +328,7 @@ public class PhotoEditorActivity extends BaseActivity implements OnPhotoEditorL hideLoading(); showSnackbar(getString(R.string.image_saved)); mPhotoEditorView.getSource().setImageURI(Uri.fromFile(new File(imagePath))); - if( exit ){ + if (exit) { Intent intentImage = new Intent(Helper.INTENT_SEND_MODIFIED_IMAGE); intentImage.putExtra("imgpath", imagePath); LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intentImage); @@ -352,7 +357,7 @@ public class PhotoEditorActivity extends BaseActivity implements OnPhotoEditorL ExifInterface exif = null; int rotation = 0; int rotationInDegrees = 0; - if( data != null && data.getData() != null) { + if (data != null && data.getData() != null) { try (InputStream inputStream = getContentResolver().openInputStream(data.getData())) { assert inputStream != null; exif = new androidx.exifinterface.media.ExifInterface(inputStream); @@ -383,15 +388,15 @@ public class PhotoEditorActivity extends BaseActivity implements OnPhotoEditorL case CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE: CropImage.ActivityResult result = CropImage.getActivityResult(data); Uri resultUri = result.getUri(); - if( resultUri != null) { + if (resultUri != null) { mPhotoEditorView.getSource().setImageURI(resultUri); mPhotoEditorView.getSource().setRotation(rotationInDegrees); File fdelete = new File(uri.getPath()); if (fdelete.exists()) { - fdelete.delete(); + fdelete.delete(); } uri = resultUri; - String filename = System.currentTimeMillis()+"_"+Helper.getFileName(PhotoEditorActivity.this, uri); + String filename = System.currentTimeMillis() + "_" + Helper.getFileName(PhotoEditorActivity.this, uri); tempname = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(new Date()) + filename; } @@ -444,13 +449,13 @@ public class PhotoEditorActivity extends BaseActivity implements OnPhotoEditorL int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } AlertDialog.Builder builder = new AlertDialog.Builder(this, style); - builder.setMessage( getString(R.string.confirm_exit_editing)); + builder.setMessage(getString(R.string.confirm_exit_editing)); builder.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { @@ -519,8 +524,6 @@ public class PhotoEditorActivity extends BaseActivity implements OnPhotoEditorL } - - void showFilter(boolean isVisible) { mIsFilterVisible = isVisible; mConstraintSet.clone(mRootView); diff --git a/app/src/main/java/app/fedilab/android/activities/PlaylistsActivity.java b/app/src/main/java/app/fedilab/android/activities/PlaylistsActivity.java index 1b4b774e5..b022b7386 100644 --- a/app/src/main/java/app/fedilab/android/activities/PlaylistsActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/PlaylistsActivity.java @@ -19,6 +19,7 @@ import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; + import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; @@ -26,6 +27,7 @@ import androidx.appcompat.app.ActionBar; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.appcompat.widget.Toolbar; + import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; @@ -77,7 +79,7 @@ public class PlaylistsActivity extends BaseActivity implements OnPlaylistActionI super.onCreate(savedInstanceState); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme_NoActionBar_Fedilab); break; @@ -90,13 +92,13 @@ public class PlaylistsActivity extends BaseActivity implements OnPlaylistActionI default: setTheme(R.style.AppThemeDark_NoActionBar); } - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null ) { + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); assert inflater != null; - View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); + View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close); @@ -108,24 +110,24 @@ public class PlaylistsActivity extends BaseActivity implements OnPlaylistActionI } }); toolbar_title.setText(R.string.upload_video); - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Toolbar toolbar = actionBar.getCustomView().findViewById(R.id.toolbar); Helper.colorizeToolbar(toolbar, R.color.black, PlaylistsActivity.this); } } setContentView(R.layout.activity_playlists); Toolbar toolbar = findViewById(R.id.toolbar); - if( theme == Helper.THEME_BLACK) + if (theme == Helper.THEME_BLACK) toolbar.setBackgroundColor(ContextCompat.getColor(PlaylistsActivity.this, R.color.black)); setSupportActionBar(toolbar); - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); peertubes = new ArrayList<>(); RecyclerView lv_playlist = findViewById(R.id.lv_playlist); - mainLoader = findViewById(R.id.loader); + mainLoader = findViewById(R.id.loader); nextElementLoader = findViewById(R.id.loading_next_status); - textviewNoAction = findViewById(R.id.no_action); + textviewNoAction = findViewById(R.id.no_action); mainLoader.setVisibility(View.VISIBLE); swipeRefreshLayout = findViewById(R.id.swipeContainer); max_id = null; @@ -145,29 +147,28 @@ public class PlaylistsActivity extends BaseActivity implements OnPlaylistActionI lv_playlist.setLayoutManager(mLayoutManager); Bundle b = getIntent().getExtras(); - if(b != null){ + if (b != null) { playlist = b.getParcelable("playlist"); - }else{ - Toasty.error(getApplicationContext(),getString(R.string.toast_error_search),Toast.LENGTH_LONG).show(); + } else { + Toasty.error(getApplicationContext(), getString(R.string.toast_error_search), Toast.LENGTH_LONG).show(); return; } - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); setTitle(playlist.getDisplayName()); lv_playlist.addOnScrollListener(new RecyclerView.OnScrollListener() { - public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) - { + public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition(); - if(dy > 0){ + if (dy > 0) { int visibleItemCount = mLayoutManager.getChildCount(); int totalItemCount = mLayoutManager.getItemCount(); - if(firstVisibleItem + visibleItemCount == totalItemCount ) { - if(!flag_loading ) { + if (firstVisibleItem + visibleItemCount == totalItemCount) { + if (!flag_loading) { flag_loading = true; - new ManagePlaylistsAsyncTask(PlaylistsActivity.this,GET_LIST_VIDEOS, playlist, null, max_id , PlaylistsActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new ManagePlaylistsAsyncTask(PlaylistsActivity.this, GET_LIST_VIDEOS, playlist, null, max_id, PlaylistsActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); nextElementLoader.setVisibility(View.VISIBLE); } } else { @@ -186,11 +187,11 @@ public class PlaylistsActivity extends BaseActivity implements OnPlaylistActionI flag_loading = true; swiped = true; MainActivity.countNewStatus = 0; - new ManagePlaylistsAsyncTask(PlaylistsActivity.this,GET_LIST_VIDEOS, playlist, null, null , PlaylistsActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new ManagePlaylistsAsyncTask(PlaylistsActivity.this, GET_LIST_VIDEOS, playlist, null, null, PlaylistsActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } }); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: swipeRefreshLayout.setColorSchemeResources(R.color.mastodonC4, R.color.mastodonC2, @@ -211,11 +212,10 @@ public class PlaylistsActivity extends BaseActivity implements OnPlaylistActionI break; } - new ManagePlaylistsAsyncTask(PlaylistsActivity.this,GET_LIST_VIDEOS, playlist, null, null , PlaylistsActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new ManagePlaylistsAsyncTask(PlaylistsActivity.this, GET_LIST_VIDEOS, playlist, null, null, PlaylistsActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } - @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { @@ -235,14 +235,14 @@ public class PlaylistsActivity extends BaseActivity implements OnPlaylistActionI nextElementLoader.setVisibility(View.GONE); //Discards 404 - error which can often happen due to toots which have been deleted if (apiResponse.getError() != null) { - if ( !apiResponse.getError().getError().startsWith("404 -")) + if (!apiResponse.getError().getError().startsWith("404 -")) Toasty.error(getApplicationContext(), apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); swipeRefreshLayout.setRefreshing(false); swiped = false; flag_loading = false; return; } - if( actionType == GET_LIST_VIDEOS) { + if (actionType == GET_LIST_VIDEOS) { int previousPosition = this.peertubes.size(); List videos = apiResponse.getPeertubes(); diff --git a/app/src/main/java/app/fedilab/android/activities/PrivacyActivity.java b/app/src/main/java/app/fedilab/android/activities/PrivacyActivity.java index 9cab319d7..833dc6717 100644 --- a/app/src/main/java/app/fedilab/android/activities/PrivacyActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/PrivacyActivity.java @@ -18,8 +18,10 @@ package app.fedilab.android.activities; import android.annotation.SuppressLint; import android.content.SharedPreferences; import android.os.Bundle; + import androidx.appcompat.app.ActionBar; import androidx.appcompat.widget.Toolbar; + import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; @@ -44,7 +46,7 @@ public class PrivacyActivity extends BaseActivity { super.onCreate(savedInstanceState); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme); break; @@ -58,13 +60,13 @@ public class PrivacyActivity extends BaseActivity { setTheme(R.style.AppThemeDark); } - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null ) { + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); assert inflater != null; - View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); + View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close); @@ -76,7 +78,7 @@ public class PrivacyActivity extends BaseActivity { } }); toolbar_title.setText(R.string.action_privacy); - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Toolbar toolbar = actionBar.getCustomView().findViewById(R.id.toolbar); Helper.colorizeToolbar(toolbar, R.color.black, PrivacyActivity.this); } diff --git a/app/src/main/java/app/fedilab/android/activities/ProxyActivity.java b/app/src/main/java/app/fedilab/android/activities/ProxyActivity.java index ab38c9de3..d5fd6fff2 100644 --- a/app/src/main/java/app/fedilab/android/activities/ProxyActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/ProxyActivity.java @@ -15,11 +15,12 @@ package app.fedilab.android.activities; - import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; + import androidx.core.content.ContextCompat; + import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; @@ -50,7 +51,7 @@ public class ProxyActivity extends BaseActivity { requestWindowFeature(Window.FEATURE_NO_TITLE); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme_NoActionBar_Fedilab); getWindow().getDecorView().setBackgroundColor(ContextCompat.getColor(ProxyActivity.this, R.color.mastodonC3__)); @@ -69,7 +70,7 @@ public class ProxyActivity extends BaseActivity { } setContentView(R.layout.activity_proxy); getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().hide(); //Enable proxy @@ -96,12 +97,12 @@ public class ProxyActivity extends BaseActivity { int portVal = sharedpreferences.getInt(Helper.SET_PROXY_PORT, 8118); final String login = sharedpreferences.getString(Helper.SET_PROXY_LOGIN, null); final String pwd = sharedpreferences.getString(Helper.SET_PROXY_PASSWORD, null); - if( hostVal.length() > 0) + if (hostVal.length() > 0) host.setText(hostVal); port.setText(String.valueOf(portVal)); - if( login != null && login.length() > 0) + if (login != null && login.length() > 0) proxy_login.setText(login); - if( pwd != null && proxy_password.length() > 0) + if (pwd != null && proxy_password.length() > 0) proxy_password.setText(pwd); count2 = 0; final Spinner proxy_type = findViewById(R.id.type); @@ -114,14 +115,15 @@ public class ProxyActivity extends BaseActivity { proxy_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { - if( count2 > 0){ + if (count2 > 0) { SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putInt(Helper.SET_PROXY_TYPE, position); editor.apply(); - }else { + } else { count2++; } } + @Override public void onNothingSelected(AdapterView parent) { @@ -136,7 +138,7 @@ public class ProxyActivity extends BaseActivity { String proxy_passwordVal = proxy_password.getText().toString().trim(); SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(Helper.SET_PROXY_HOST, hostVal); - if( portVal.matches("\\d+") ) + if (portVal.matches("\\d+")) editor.putInt(Helper.SET_PROXY_PORT, Integer.parseInt(portVal)); editor.putString(Helper.SET_PROXY_LOGIN, proxy_loginVal); editor.putString(Helper.SET_PROXY_PASSWORD, proxy_passwordVal); @@ -158,7 +160,4 @@ public class ProxyActivity extends BaseActivity { } - - - } diff --git a/app/src/main/java/app/fedilab/android/activities/ReorderTimelinesActivity.java b/app/src/main/java/app/fedilab/android/activities/ReorderTimelinesActivity.java index 5c74117fa..d84032353 100644 --- a/app/src/main/java/app/fedilab/android/activities/ReorderTimelinesActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/ReorderTimelinesActivity.java @@ -23,12 +23,14 @@ import android.graphics.Paint; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; + import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AlertDialog; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.ItemTouchHelper; + import android.text.Editable; import android.text.InputFilter; import android.text.TextWatcher; @@ -89,7 +91,7 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra private RelativeLayout undo_container; private TextView undo_message; private TextView undo_action; - private List timelines; + private List timelines; private ReorderTabAdapter adapter; private ManageTimelines timeline; private boolean isLoadingInstance; @@ -102,7 +104,7 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra super.onCreate(savedInstanceState); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme); break; @@ -120,20 +122,20 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null ) { + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); assert inflater != null; - View view = inflater.inflate(R.layout.simple_bar_add, new LinearLayout(getApplicationContext()), false); + View view = inflater.inflate(R.layout.simple_bar_add, new LinearLayout(getApplicationContext()), false); actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close); @@ -145,9 +147,9 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra finish(); } }); - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA){ + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { add_remote_instance.setVisibility(View.VISIBLE); - }else{ + } else { add_remote_instance.setVisibility(View.GONE); } add_remote_instance.setOnClickListener(new View.OnClickListener() { @@ -168,39 +170,39 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra public void onClick(DialogInterface dialog, int id) { SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); String instanceName = instance_list.getText().toString().trim(); - new Thread(new Runnable(){ + new Thread(new Runnable() { @Override public void run() { try { - if(radioGroup.getCheckedRadioButtonId() == R.id.mastodon_instance) + if (radioGroup.getCheckedRadioButtonId() == R.id.mastodon_instance) new HttpsConnection(ReorderTimelinesActivity.this, null).get("https://" + instanceName + "/api/v1/timelines/public?local=true", 10, null, null); - else if( radioGroup.getCheckedRadioButtonId() == R.id.peertube_instance) + else if (radioGroup.getCheckedRadioButtonId() == R.id.peertube_instance) new HttpsConnection(ReorderTimelinesActivity.this, null).get("https://" + instanceName + "/api/v1/videos/", 10, null, null); - else if( radioGroup.getCheckedRadioButtonId() == R.id.pixelfed_instance) { + else if (radioGroup.getCheckedRadioButtonId() == R.id.pixelfed_instance) { new HttpsConnection(ReorderTimelinesActivity.this, null).get("https://" + instanceName + "/api/v1/timelines/public", 10, null, null); - }else if( radioGroup.getCheckedRadioButtonId() == R.id.misskey_instance) { + } else if (radioGroup.getCheckedRadioButtonId() == R.id.misskey_instance) { new HttpsConnection(ReorderTimelinesActivity.this, null).post("https://" + instanceName + "/api/notes/local-timeline", 10, null, null); - }else if( radioGroup.getCheckedRadioButtonId() == R.id.gnu_instance) { + } else if (radioGroup.getCheckedRadioButtonId() == R.id.gnu_instance) { new HttpsConnection(ReorderTimelinesActivity.this, null).get("https://" + instanceName + "/api/statuses/public_timeline.json", 10, null, null); } runOnUiThread(new Runnable() { public void run() { dialog.dismiss(); - if(radioGroup.getCheckedRadioButtonId() == R.id.mastodon_instance) { + if (radioGroup.getCheckedRadioButtonId() == R.id.mastodon_instance) { new InstancesDAO(ReorderTimelinesActivity.this, db).insertInstance(instanceName, "MASTODON"); - }else if( radioGroup.getCheckedRadioButtonId() == R.id.peertube_instance) { + } else if (radioGroup.getCheckedRadioButtonId() == R.id.peertube_instance) { new InstancesDAO(ReorderTimelinesActivity.this, db).insertInstance(instanceName, "PEERTUBE"); - } else if( radioGroup.getCheckedRadioButtonId() == R.id.pixelfed_instance) { + } else if (radioGroup.getCheckedRadioButtonId() == R.id.pixelfed_instance) { new InstancesDAO(ReorderTimelinesActivity.this, db).insertInstance(instanceName, "PIXELFED"); - } else if( radioGroup.getCheckedRadioButtonId() == R.id.misskey_instance) { + } else if (radioGroup.getCheckedRadioButtonId() == R.id.misskey_instance) { new InstancesDAO(ReorderTimelinesActivity.this, db).insertInstance(instanceName, "MISSKEY"); - }else if( radioGroup.getCheckedRadioButtonId() == R.id.gnu_instance) { + } else if (radioGroup.getCheckedRadioButtonId() == R.id.gnu_instance) { new InstancesDAO(ReorderTimelinesActivity.this, db).insertInstance(instanceName, "GNU"); } - if( timelines != null && adapter != null) { + if (timelines != null && adapter != null) { List instance = new InstancesDAO(ReorderTimelinesActivity.this, db).getInstanceByName(instanceName); - if( instance != null && instance.size() > 0 ) { + if (instance != null && instance.size() > 0) { ManageTimelines manageTimelines = new ManageTimelines(); manageTimelines.setRemoteInstance(instance.get(0)); manageTimelines.setPosition(timelines.size()); @@ -235,13 +237,13 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra imm.hideSoftInputFromWindow(instance_list.getWindowToken(), 0); } }); - if( alertDialog.getWindow() != null ) + if (alertDialog.getWindow() != null) alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); alertDialog.show(); instance_list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override - public void onItemClick (AdapterView parent, View view, int position, long id) { + public void onItemClick(AdapterView parent, View view, int position, long id) { String oldSearch = parent.getItemAtPosition(position).toString().trim(); } }); @@ -259,7 +261,7 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra public void afterTextChanged(Editable s) { Pattern host = Pattern.compile("([\\da-z\\.-]+\\.[a-z\\.]{2,12})"); Matcher matcher = host.matcher(s.toString().trim()); - if( s.toString().trim().length() == 0 || !matcher.find()) { + if (s.toString().trim().length() == 0 || !matcher.find()) { alertDialog.getButton( AlertDialog.BUTTON_POSITIVE).setEnabled(false); } else { @@ -275,7 +277,7 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra parameters.put("name", String.valueOf(true)); isLoadingInstance = true; - if( oldSearch == null || !oldSearch.equals(s.toString().trim())) + if (oldSearch == null || !oldSearch.equals(s.toString().trim())) new Thread(new Runnable() { @Override public void run() { @@ -291,13 +293,13 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra if (jsonArray != null) { int length = 0; for (int i = 0; i < jsonArray.length(); i++) { - if( !jsonArray.getJSONObject(i).get("name").toString().contains("@") && jsonArray.getJSONObject(i).get("up").toString().equals("true")) + if (!jsonArray.getJSONObject(i).get("name").toString().contains("@") && jsonArray.getJSONObject(i).get("up").toString().equals("true")) length++; } instances = new String[length]; int j = 0; for (int i = 0; i < jsonArray.length(); i++) { - if( !jsonArray.getJSONObject(i).get("name").toString().contains("@") && jsonArray.getJSONObject(i).get("up").toString().equals("true")) { + if (!jsonArray.getJSONObject(i).get("name").toString().contains("@") && jsonArray.getJSONObject(i).get("up").toString().equals("true")) { instances[j] = jsonArray.getJSONObject(i).get("name").toString(); j++; } @@ -334,7 +336,7 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra } }); toolbar_title.setText(R.string.action_reorder_timeline); - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Toolbar toolbar = actionBar.getCustomView().findViewById(R.id.toolbar); Helper.colorizeToolbar(toolbar, R.color.black, ReorderTimelinesActivity.this); } @@ -342,7 +344,6 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra setContentView(R.layout.activity_reorder_tabs); - updated = false; RecyclerView lv_reorder_tabs = findViewById(R.id.lv_reorder_tabs); @@ -373,7 +374,7 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra if (theme == Helper.THEME_LIGHT) undo_container.setBackgroundColor(getResources().getColor(R.color.mastodonC3)); undo_container.setVisibility(View.VISIBLE); - switch (manageTimelines.getType()){ + switch (manageTimelines.getType()) { case TAG: undo_message.setText(R.string.reorder_tag_removed); break; @@ -390,7 +391,7 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra public void run() { undo_container.setVisibility(View.GONE); SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - switch (manageTimelines.getType()){ + switch (manageTimelines.getType()) { case TAG: new SearchDAO(getApplicationContext(), db).remove(manageTimelines.getTagTimeline().getName()); new TimelinesDAO(getApplicationContext(), db).remove(manageTimelines); @@ -401,7 +402,7 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra break; case LIST: timeline = manageTimelines; - new ManageListsAsyncTask(getApplicationContext(), ManageListsAsyncTask.action.DELETE_LIST,null, null, manageTimelines.getListTimeline().getId(), null, ReorderTimelinesActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new ManageListsAsyncTask(getApplicationContext(), ManageListsAsyncTask.action.DELETE_LIST, null, null, manageTimelines.getListTimeline().getId(), null, ReorderTimelinesActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); new TimelinesDAO(getApplicationContext(), db).remove(timeline); break; } @@ -422,9 +423,9 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra } @Override - public void onStop(){ + public void onStop() { super.onStop(); - if( updated ) { + if (updated) { Intent intent = new Intent(getBaseContext(), MainActivity.class); intent.putExtra(Helper.INTENT_ACTION, Helper.REFRESH_TIMELINE); startActivity(intent); diff --git a/app/src/main/java/app/fedilab/android/activities/SearchResultActivity.java b/app/src/main/java/app/fedilab/android/activities/SearchResultActivity.java index d02efd160..d490b98ad 100644 --- a/app/src/main/java/app/fedilab/android/activities/SearchResultActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/SearchResultActivity.java @@ -18,8 +18,10 @@ import android.annotation.SuppressLint; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; + import androidx.appcompat.app.ActionBar; import androidx.appcompat.widget.Toolbar; + import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; @@ -64,7 +66,7 @@ public class SearchResultActivity extends BaseActivity implements OnRetrieveSear super.onCreate(savedInstanceState); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme); break; @@ -84,22 +86,22 @@ public class SearchResultActivity extends BaseActivity implements OnRetrieveSear lv_search = findViewById(R.id.lv_search); Bundle b = getIntent().getExtras(); - if(b != null){ + if (b != null) { search = b.getString("search"); - if( search != null) + if (search != null) new RetrieveSearchAsyncTask(getApplicationContext(), search.trim(), SearchResultActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else - Toasty.error(getApplicationContext(),getString(R.string.toast_error_search),Toast.LENGTH_LONG).show(); - }else{ - Toasty.error(getApplicationContext(),getString(R.string.toast_error_search),Toast.LENGTH_LONG).show(); + Toasty.error(getApplicationContext(), getString(R.string.toast_error_search), Toast.LENGTH_LONG).show(); + } else { + Toasty.error(getApplicationContext(), getString(R.string.toast_error_search), Toast.LENGTH_LONG).show(); } - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null ) { + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); assert inflater != null; - View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); + View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close); @@ -111,7 +113,7 @@ public class SearchResultActivity extends BaseActivity implements OnRetrieveSear } }); toolbar_title.setText(search); - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Toolbar toolbar = actionBar.getCustomView().findViewById(R.id.toolbar); Helper.colorizeToolbar(toolbar, R.color.black, SearchResultActivity.this); } @@ -138,22 +140,22 @@ public class SearchResultActivity extends BaseActivity implements OnRetrieveSear @Override public void onRetrieveSearch(APIResponse apiResponse) { loader.setVisibility(View.GONE); - if( apiResponse.getError() != null){ - if( apiResponse.getError().getError() != null) - Toasty.error(getApplicationContext(), apiResponse.getError().getError(),Toast.LENGTH_LONG).show(); + if (apiResponse.getError() != null) { + if (apiResponse.getError().getError() != null) + Toasty.error(getApplicationContext(), apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); else - Toasty.error(getApplicationContext(), getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); return; } - if( apiResponse.getResults() == null || ( apiResponse.getResults().getAccounts().size() == 0 && apiResponse.getResults().getStatuses().size() == 0 && apiResponse.getResults().getHashtags().size() == 0)){ + if (apiResponse.getResults() == null || (apiResponse.getResults().getAccounts().size() == 0 && apiResponse.getResults().getStatuses().size() == 0 && apiResponse.getResults().getHashtags().size() == 0)) { RelativeLayout no_result = findViewById(R.id.no_result); no_result.setVisibility(View.VISIBLE); return; } lv_search.setVisibility(View.VISIBLE); - List tags = apiResponse.getResults().getHashtags(); - List accounts = apiResponse.getResults().getAccounts(); - List statuses = apiResponse.getResults().getStatuses(); + List tags = apiResponse.getResults().getHashtags(); + List accounts = apiResponse.getResults().getAccounts(); + List statuses = apiResponse.getResults().getStatuses(); SearchListAdapter searchListAdapter = new SearchListAdapter(SearchResultActivity.this, statuses, accounts, tags); lv_search.setAdapter(searchListAdapter); @@ -165,8 +167,8 @@ public class SearchResultActivity extends BaseActivity implements OnRetrieveSear @Override public void onRetrieveSearchStatus(APIResponse apiResponse, Error error) { loader.setVisibility(View.GONE); - if( apiResponse.getError() != null){ - Toasty.error(getApplicationContext(), error.getError(),Toast.LENGTH_LONG).show(); + if (apiResponse.getError() != null) { + Toasty.error(getApplicationContext(), error.getError(), Toast.LENGTH_LONG).show(); return; } lv_search.setVisibility(View.VISIBLE); diff --git a/app/src/main/java/app/fedilab/android/activities/SearchResultTabActivity.java b/app/src/main/java/app/fedilab/android/activities/SearchResultTabActivity.java index 771281472..136eb2f43 100644 --- a/app/src/main/java/app/fedilab/android/activities/SearchResultTabActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/SearchResultTabActivity.java @@ -17,7 +17,9 @@ package app.fedilab.android.activities; import android.content.SharedPreferences; import android.os.Bundle; + import com.google.android.material.tabs.TabLayout; + import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentStatePagerAdapter; @@ -25,6 +27,7 @@ import androidx.viewpager.widget.PagerAdapter; import androidx.viewpager.widget.ViewPager; import androidx.appcompat.app.ActionBar; import androidx.appcompat.widget.Toolbar; + import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; @@ -51,7 +54,7 @@ import app.fedilab.android.asynctasks.RetrieveFeedsAsyncTask; * Show search results within tabs */ -public class SearchResultTabActivity extends BaseActivity { +public class SearchResultTabActivity extends BaseActivity { private String search; @@ -64,7 +67,7 @@ public class SearchResultTabActivity extends BaseActivity { super.onCreate(savedInstanceState); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme); break; @@ -82,27 +85,27 @@ public class SearchResultTabActivity extends BaseActivity { Bundle b = getIntent().getExtras(); - if(b != null){ + if (b != null) { search = b.getString("search"); - if( search == null) - Toasty.error(getApplicationContext(),getString(R.string.toast_error_search), Toast.LENGTH_LONG).show(); - }else{ - Toasty.error(getApplicationContext(),getString(R.string.toast_error_search),Toast.LENGTH_LONG).show(); + if (search == null) + Toasty.error(getApplicationContext(), getString(R.string.toast_error_search), Toast.LENGTH_LONG).show(); + } else { + Toasty.error(getApplicationContext(), getString(R.string.toast_error_search), Toast.LENGTH_LONG).show(); } - if( search == null) + if (search == null) finish(); tabLayout = findViewById(R.id.search_tabLayout); search_viewpager = findViewById(R.id.search_viewpager); - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null ) { + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); assert inflater != null; - View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); + View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close); @@ -114,7 +117,7 @@ public class SearchResultTabActivity extends BaseActivity { } }); toolbar_title.setText(search); - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Toolbar toolbar = actionBar.getCustomView().findViewById(R.id.toolbar); Helper.colorizeToolbar(toolbar, R.color.black, SearchResultTabActivity.this); } @@ -137,7 +140,7 @@ public class SearchResultTabActivity extends BaseActivity { @Override public void onPageSelected(int position) { TabLayout.Tab tab = tabLayout.getTabAt(position); - if( tab != null) + if (tab != null) tab.select(); } @@ -161,7 +164,7 @@ public class SearchResultTabActivity extends BaseActivity { @Override public void onTabReselected(TabLayout.Tab tab) { Fragment fragment; - if( search_viewpager.getAdapter() != null) { + if (search_viewpager.getAdapter() != null) { fragment = (Fragment) search_viewpager.getAdapter().instantiateItem(search_viewpager, tab.getPosition()); if (fragment instanceof DisplayAccountsFragment) { DisplayAccountsFragment displayAccountsFragment = ((DisplayAccountsFragment) fragment); @@ -202,7 +205,7 @@ public class SearchResultTabActivity extends BaseActivity { @Override public Fragment getItem(int position) { Bundle bundle = new Bundle(); - switch (position){ + switch (position) { case 0: DisplaySearchTagsFragment displaySearchTagsFragment = new DisplaySearchTagsFragment(); displaySearchTagsFragment.setArguments(bundle); diff --git a/app/src/main/java/app/fedilab/android/activities/SettingsActivity.java b/app/src/main/java/app/fedilab/android/activities/SettingsActivity.java index 61abbaab4..7468c7517 100644 --- a/app/src/main/java/app/fedilab/android/activities/SettingsActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/SettingsActivity.java @@ -66,12 +66,13 @@ public class SettingsActivity extends BaseActivity implements ViewAnimator.ViewA private List list = new ArrayList<>(); public static int position = 1; private ContentSettingsFragment.type previous; + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme_NoActionBar_Fedilab); break; @@ -85,13 +86,13 @@ public class SettingsActivity extends BaseActivity implements ViewAnimator.ViewA setTheme(R.style.AppThemeDark_NoActionBar); } position = 1; - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null ) { + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); assert inflater != null; - View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); + View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close); @@ -103,7 +104,7 @@ public class SettingsActivity extends BaseActivity implements ViewAnimator.ViewA } }); toolbar_title.setText(R.string.action_about); - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Toolbar toolbar = actionBar.getCustomView().findViewById(R.id.toolbar); Helper.colorizeToolbar(toolbar, R.color.black, SettingsActivity.this); } @@ -170,7 +171,7 @@ public class SettingsActivity extends BaseActivity implements ViewAnimator.ViewA } @Override - public void onDestroy(){ + public void onDestroy() { super.onDestroy(); } @@ -191,7 +192,7 @@ public class SettingsActivity extends BaseActivity implements ViewAnimator.ViewA list.add(menuItemInterface); list.add(menuItemBattery); list.add(menuItemEdit); - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA){ + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { list.add(menuMenu); list.add(menuItemAdmin); } @@ -211,9 +212,6 @@ public class SettingsActivity extends BaseActivity implements ViewAnimator.ViewA } - - - @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { @@ -224,10 +222,8 @@ public class SettingsActivity extends BaseActivity implements ViewAnimator.ViewA } - - @Override - public void onResume(){ + public void onResume() { super.onResume(); } @@ -235,11 +231,11 @@ public class SettingsActivity extends BaseActivity implements ViewAnimator.ViewA private ScreenShotable replaceFragment(ScreenShotable screenShotable, ContentSettingsFragment.type type, int topPosition) { this.res = this.res == R.drawable.ic_timeline_menu_s ? R.drawable.ic_notifications_menu : R.drawable.ic_timeline_menu_s; - if( type == ContentSettingsFragment.type.LANGUAGE){ + if (type == ContentSettingsFragment.type.LANGUAGE) { Intent intent = new Intent(getApplicationContext(), LanguageActivity.class); startActivity(intent); type = previous; - }else if( type == ContentSettingsFragment.type.MENU){ + } else if (type == ContentSettingsFragment.type.MENU) { Intent intent = new Intent(getApplicationContext(), HideItemActivity.class); startActivity(intent); type = previous; diff --git a/app/src/main/java/app/fedilab/android/activities/ShowAccountActivity.java b/app/src/main/java/app/fedilab/android/activities/ShowAccountActivity.java index 26b168d96..4d3b0c981 100644 --- a/app/src/main/java/app/fedilab/android/activities/ShowAccountActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/ShowAccountActivity.java @@ -26,11 +26,13 @@ import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; + import androidx.annotation.NonNull; import com.google.android.exoplayer2.Timeline; import com.google.android.material.appbar.AppBarLayout; import com.google.android.material.tabs.TabLayout; + import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentStatePagerAdapter; @@ -39,6 +41,7 @@ import androidx.viewpager.widget.PagerAdapter; import androidx.viewpager.widget.ViewPager; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.PopupMenu; + import android.text.Spannable; import android.text.SpannableString; import android.text.Spanned; @@ -158,8 +161,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt private AsyncTask retrieveRelationship; - - public enum action{ + public enum action { FOLLOW, UNFOLLOW, UNBLOCK, @@ -174,7 +176,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt super.onCreate(savedInstanceState); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme_NoActionBar_Fedilab); break; @@ -201,7 +203,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt TextView account_type = findViewById(R.id.account_type); account_bot = findViewById(R.id.account_bot); addToList = null; - switch (theme){ + switch (theme) { case THEME_LIGHT: account_pp.setBackgroundResource(R.drawable.account_pp_border_light); break; @@ -213,22 +215,22 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt break; } - if(b != null){ + if (b != null) { account = b.getParcelable("account"); - if( account == null){ + if (account == null) { accountId = b.getString("accountId"); - }else { + } else { accountId = account.getId(); } ischannel = b.getBoolean("ischannel", false); peertubeAccount = b.getBoolean("peertubeaccount", false); if (account == null) { - accountAsync = new RetrieveAccountAsyncTask(getApplicationContext(), accountId, ShowAccountActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + accountAsync = new RetrieveAccountAsyncTask(getApplicationContext(), accountId, ShowAccountActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - }else{ - Toasty.error(getApplicationContext(),getString(R.string.toast_error_loading_account),Toast.LENGTH_LONG).show(); + } else { + Toasty.error(getApplicationContext(), getString(R.string.toast_error_loading_account), Toast.LENGTH_LONG).show(); } accountUrl = null; show_boosts = true; @@ -246,7 +248,6 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt account_note = findViewById(R.id.account_note); - header_edit_profile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -260,13 +261,13 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt ImageButton action_more = findViewById(R.id.action_more); ImageButton reload_tabs = findViewById(R.id.reload_tabs); ImageButton action_back = findViewById(R.id.action_back); - if(theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { fake_actionbar.setBackgroundColor(ContextCompat.getColor(ShowAccountActivity.this, R.color.light_grey)); - changeDrawableColor(getApplicationContext(),action_more,R.color.dark_icon); - changeDrawableColor(getApplicationContext(),account_menu,R.color.dark_icon); - changeDrawableColor(getApplicationContext(),action_back,R.color.dark_icon); + changeDrawableColor(getApplicationContext(), action_more, R.color.dark_icon); + changeDrawableColor(getApplicationContext(), account_menu, R.color.dark_icon); + changeDrawableColor(getApplicationContext(), action_back, R.color.dark_icon); } - if(theme == THEME_BLACK){ + if (theme == THEME_BLACK) { fake_actionbar.setBackgroundColor(ContextCompat.getColor(ShowAccountActivity.this, R.color.light_black)); } account_menu.setOnClickListener(new View.OnClickListener() { @@ -283,27 +284,27 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt }); reload_tabs.setOnClickListener(view -> { - if( mPager != null && mPager - .getAdapter() != null){ - if( mPager + if (mPager != null && mPager + .getAdapter() != null) { + if (mPager .getAdapter() - .instantiateItem(mPager, mPager.getCurrentItem()) instanceof TabLayoutTootsFragment){ - TabLayoutTootsFragment tabLayoutTootsFragment = (TabLayoutTootsFragment)mPager + .instantiateItem(mPager, mPager.getCurrentItem()) instanceof TabLayoutTootsFragment) { + TabLayoutTootsFragment tabLayoutTootsFragment = (TabLayoutTootsFragment) mPager .getAdapter() .instantiateItem(mPager, mPager.getCurrentItem()); ViewPager viewPager = tabLayoutTootsFragment.getViewPager(); - if( viewPager != null && viewPager.getAdapter() != null && viewPager + if (viewPager != null && viewPager.getAdapter() != null && viewPager .getAdapter() - .instantiateItem(viewPager, viewPager.getCurrentItem()) instanceof DisplayStatusFragment){ - DisplayStatusFragment displayStatusFragment = (DisplayStatusFragment)viewPager + .instantiateItem(viewPager, viewPager.getCurrentItem()) instanceof DisplayStatusFragment) { + DisplayStatusFragment displayStatusFragment = (DisplayStatusFragment) viewPager .getAdapter() .instantiateItem(viewPager, viewPager.getCurrentItem()); displayStatusFragment.pullToRefresh(); } - }else if( mPager + } else if (mPager .getAdapter() - .instantiateItem(mPager, mPager.getCurrentItem()) instanceof DisplayAccountsFragment) { + .instantiateItem(mPager, mPager.getCurrentItem()) instanceof DisplayAccountsFragment) { DisplayAccountsFragment displayAccountsFragment = (DisplayAccountsFragment) mPager .getAdapter() .instantiateItem(mPager, mPager.getCurrentItem()); @@ -317,20 +318,20 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt finish(); } }); - if( account != null){ + if (account != null) { ManageAccount(); } } - private void ManageAccount(){ + private void ManageAccount() { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); accountUrl = account.getUrl(); - if( theme == Helper.THEME_LIGHT){ - changeDrawableColor(getApplicationContext(), R.drawable.ic_lock_outline,R.color.black); - }else { - changeDrawableColor(getApplicationContext(), R.drawable.ic_lock_outline,R.color.mastodonC3); + if (theme == Helper.THEME_LIGHT) { + changeDrawableColor(getApplicationContext(), R.drawable.ic_lock_outline, R.color.black); + } else { + changeDrawableColor(getApplicationContext(), R.drawable.ic_lock_outline, R.color.mastodonC3); } int style; @@ -342,7 +343,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt style = R.style.DialogDark; String accountIdRelation = accountId; - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { accountIdRelation = account.getAcct(); } retrieveRelationship = new RetrieveRelationshipAsyncTask(getApplicationContext(), accountIdRelation, ShowAccountActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); @@ -355,11 +356,11 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt boolean disableGif = sharedpreferences.getBoolean(Helper.SET_DISABLE_GIF, false); ImageView banner_pp = findViewById(R.id.banner_pp); - if( !disableGif){ + if (!disableGif) { Glide.with(banner_pp.getContext()) .load(urlHeader) .into(banner_pp); - }else{ + } else { Glide.with(banner_pp.getContext()) .asBitmap() .load(urlHeader) @@ -374,28 +375,28 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt } //Redraws icon for locked accounts final float scale = getResources().getDisplayMetrics().density; - if(account.isLocked()){ + if (account.isLocked()) { Drawable img = ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_lock_outline); assert img != null; - img.setBounds(0,0,(int) (16 * scale + 0.5f),(int) (16 * scale + 0.5f)); - account_un.setCompoundDrawables( null, null, img, null); - }else{ - account_un.setCompoundDrawables( null, null, null, null); + img.setBounds(0, 0, (int) (16 * scale + 0.5f), (int) (16 * scale + 0.5f)); + account_un.setCompoundDrawables(null, null, img, null); + } else { + account_un.setCompoundDrawables(null, null, null, null); } //Peertube account watched by a Mastodon account /*if( peertubeAccount && (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA)) { account_type.setVisibility(View.VISIBLE); }*/ //Bot account - if( account.isBot()){ + if (account.isBot()) { account_bot.setVisibility(View.VISIBLE); } TextView actionbar_title = findViewById(R.id.show_account_title); - if( account.getAcct() != null) + if (account.getAcct() != null) actionbar_title.setText(account.getAcct()); ImageView pp_actionBar = findViewById(R.id.pp_actionBar); - if( account.getAvatar() != null){ + if (account.getAvatar() != null) { Helper.loadGiF(getApplicationContext(), account.getAvatar(), pp_actionBar); } @@ -405,20 +406,20 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt final TextView warning_message = findViewById(R.id.warning_message); final SpannableString content = new SpannableString(getString(R.string.disclaimer_full)); content.setSpan(new UnderlineSpan(), 0, content.length(), 0); - if( theme == Helper.THEME_DARK) + if (theme == Helper.THEME_DARK) content.setSpan(new ForegroundColorSpan(ContextCompat.getColor(ShowAccountActivity.this, R.color.dark_link_toot)), 0, content.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); - else if( theme == Helper.THEME_BLACK) + else if (theme == Helper.THEME_BLACK) content.setSpan(new ForegroundColorSpan(ContextCompat.getColor(ShowAccountActivity.this, R.color.black_link_toot)), 0, content.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); - else if( theme == Helper.THEME_LIGHT) + else if (theme == Helper.THEME_LIGHT) content.setSpan(new ForegroundColorSpan(ContextCompat.getColor(ShowAccountActivity.this, R.color.mastodonC4)), 0, content.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); warning_message.setText(content); warning_message.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { - if( !accountUrl.startsWith("http://") && ! accountUrl.startsWith("https://")) + if (!accountUrl.startsWith("http://") && !accountUrl.startsWith("https://")) accountUrl = "http://" + accountUrl; Helper.openBrowser(ShowAccountActivity.this, accountUrl); } @@ -429,9 +430,9 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt final SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); final Account authenticatedAccount = new AccountDAO(getApplicationContext(), db).getUniqAccount(userId, instance); boolean isTimedMute = new TempMuteDAO(getApplicationContext(), db).isTempMuted(authenticatedAccount, accountId); - if( isTimedMute){ + if (isTimedMute) { String date_mute = new TempMuteDAO(getApplicationContext(), db).getMuteDateByID(authenticatedAccount, accountId); - if( date_mute != null) { + if (date_mute != null) { final TextView temp_mute = findViewById(R.id.temp_mute); temp_mute.setVisibility(View.VISIBLE); SpannableString content_temp_mute = new SpannableString(getString(R.string.timed_mute_profile, account.getAcct(), date_mute)); @@ -449,16 +450,16 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt } } //This account was moved to another one - if( account.getMoved_to_account() != null){ + if (account.getMoved_to_account() != null) { TextView account_moved = findViewById(R.id.account_moved); account_moved.setVisibility(View.VISIBLE); - if( theme == Helper.THEME_DARK || theme == Helper.THEME_BLACK) - changeDrawableColor(ShowAccountActivity.this, R.drawable.ic_card_travel,R.color.dark_icon); + if (theme == Helper.THEME_DARK || theme == Helper.THEME_BLACK) + changeDrawableColor(ShowAccountActivity.this, R.drawable.ic_card_travel, R.color.dark_icon); else - changeDrawableColor(ShowAccountActivity.this, R.drawable.ic_card_travel,R.color.black); + changeDrawableColor(ShowAccountActivity.this, R.drawable.ic_card_travel, R.color.black); Drawable imgTravel = ContextCompat.getDrawable(ShowAccountActivity.this, R.drawable.ic_card_travel); assert imgTravel != null; - imgTravel.setBounds(0,0,(int) (20 * scale + 0.5f),(int) (20 * scale + 0.5f)); + imgTravel.setBounds(0, 0, (int) (20 * scale + 0.5f), (int) (20 * scale + 0.5f)); account_moved.setCompoundDrawables(imgTravel, null, null, null); //Retrieves content and make account names clickable SpannableString spannableString = account.moveToText(ShowAccountActivity.this); @@ -467,8 +468,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt } - - if( account.getAcct().contains("@") ) + if (account.getAcct().contains("@")) warning_message.setVisibility(View.VISIBLE); else warning_message.setVisibility(View.GONE); @@ -476,7 +476,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt @Override public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) { LinearLayout toolbarContent = findViewById(R.id.toolbar_content); - if( toolbarContent != null) { + if (toolbarContent != null) { if (Math.abs(verticalOffset) - appBar.getTotalScrollRange() == 0) { if (toolbarContent.getVisibility() == View.GONE) toolbarContent.setVisibility(View.VISIBLE); @@ -504,7 +504,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt account_pp.animate() .scaleY(1).scaleX(1) .start(); - if( account.getAcct().contains("@") ) + if (account.getAcct().contains("@")) warning_message.setVisibility(View.VISIBLE); else warning_message.setVisibility(View.GONE); @@ -512,22 +512,21 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt } }); mPager = findViewById(R.id.account_viewpager); - if( !peertubeAccount) { + if (!peertubeAccount) { tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.toots))); tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.following))); tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.followers))); mPager.setOffscreenPageLimit(3); - }else if( ! ischannel){ + } else if (!ischannel) { tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.videos))); tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.channels))); mPager.setOffscreenPageLimit(2); - }else{ + } else { tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.videos))); mPager.setOffscreenPageLimit(1); } - PagerAdapter mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager()); mPager.setAdapter(mPagerAdapter); @@ -540,7 +539,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt @Override public void onPageSelected(int position) { TabLayout.Tab tab = tabLayout.getTabAt(position); - if( tab != null) + if (tab != null) tab.select(); } @@ -564,11 +563,11 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt @Override public void onTabReselected(TabLayout.Tab tab) { Fragment fragment = null; - if( mPager.getAdapter() != null) + if (mPager.getAdapter() != null) fragment = (Fragment) mPager.getAdapter().instantiateItem(mPager, tab.getPosition()); - switch (tab.getPosition()){ + switch (tab.getPosition()) { case 0: - if( mPager != null && mPager + if (mPager != null && mPager .getAdapter() != null) { if (mPager .getAdapter() @@ -592,7 +591,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt break; case 1: case 2: - if( fragment != null) { + if (fragment != null) { DisplayAccountsFragment displayAccountsFragment = ((DisplayAccountsFragment) fragment); displayAccountsFragment.scrollToTop(); } @@ -602,18 +601,18 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt }); - if ( (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) && account.getFields() != null && account.getFields().size() > 0){ + if ((MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) && account.getFields() != null && account.getFields().size() > 0) { LinkedHashMap fields = account.getFields(); LinkedHashMap fieldsVerified = account.getFieldsVerified(); Iterator it = fields.entrySet().iterator(); int i = 1; LinearLayout fields_container = findViewById(R.id.fields_container); - if( fields_container != null) + if (fields_container != null) fields_container.setVisibility(View.VISIBLE); while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - String label = (String)pair.getKey(); - if( label != null && fieldsVerified != null && fieldsVerified.containsKey(label)) { + Map.Entry pair = (Map.Entry) it.next(); + String label = (String) pair.getKey(); + if (label != null && fieldsVerified != null && fieldsVerified.containsKey(label)) { boolean verified = fieldsVerified.get(label); LinearLayout field; @@ -682,7 +681,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt } account_dn.setText(Helper.shortnameToUnicode(account.getDisplay_name(), true)); - if( !ischannel || account.getAcct().split("-").length < 4) { + if (!ischannel || account.getAcct().split("-").length < 4) { account_un.setText(String.format("@%s", account.getAcct())); account_un.setOnLongClickListener(new View.OnLongClickListener() { @Override @@ -698,12 +697,12 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt return false; } }); - }else { + } else { account_un.setVisibility(View.GONE); } SpannableString spannableString = Helper.clickableElementsDescription(ShowAccountActivity.this, account.getNote()); account.setNoteSpan(spannableString); - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) account.makeEmojisAccountProfile(ShowAccountActivity.this, ShowAccountActivity.this, account); account_note.setText(account.getNoteSpan(), TextView.BufferType.SPANNABLE); account_note.setMovementMethod(LinkMovementMethod.getInstance()); @@ -725,7 +724,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt .inflate(R.menu.option_filter_toots_account, popup.getMenu()); Menu menu = popup.getMenu(); - if( !Helper.canPin ) { + if (!Helper.canPin) { popup.getMenu().findItem(R.id.action_show_pinned).setVisible(false); } final MenuItem itemShowPined = menu.findItem(R.id.action_show_pinned); @@ -741,7 +740,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt popup.setOnDismissListener(new PopupMenu.OnDismissListener() { @Override public void onDismiss(PopupMenu menu) { - if( mPager != null && mPager + if (mPager != null && mPager .getAdapter() != null) { if (mPager .getAdapter() @@ -795,7 +794,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt show_replies = !show_replies; break; } - if( tabLayout.getTabAt(0) != null) + if (tabLayout.getTabAt(0) != null) //noinspection ConstantConditions tabLayout.getTabAt(0).select(); PagerAdapter mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager()); @@ -814,7 +813,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt } - Helper.loadGiF(getApplicationContext(),account.getAvatar(), account_pp); + Helper.loadGiF(getApplicationContext(), account.getAvatar(), account_pp); account_pp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -836,18 +835,18 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt }); //Follow button String target = account.getId(); - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) target = account.getAcct(); String finalTarget = target; account_follow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - if( doAction == action.NOTHING){ + if (doAction == action.NOTHING) { Toasty.info(getApplicationContext(), getString(R.string.nothing_to_do), Toast.LENGTH_LONG).show(); - }else if( doAction == action.FOLLOW){ + } else if (doAction == action.FOLLOW) { account_follow.setEnabled(false); new PostActionAsyncTask(getApplicationContext(), API.StatusAction.FOLLOW, finalTarget, ShowAccountActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else if( doAction == action.UNFOLLOW){ + } else if (doAction == action.UNFOLLOW) { boolean confirm_unfollow = sharedpreferences.getBoolean(Helper.SET_UNFOLLOW_VALIDATION, true); if (confirm_unfollow) { AlertDialog.Builder unfollowConfirm = new AlertDialog.Builder(ShowAccountActivity.this, style); @@ -855,13 +854,13 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt unfollowConfirm.setMessage(account.getAcct()); unfollowConfirm.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog,int which) { + public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); unfollowConfirm.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog,int which) { + public void onClick(DialogInterface dialog, int which) { account_follow.setEnabled(false); new PostActionAsyncTask(getApplicationContext(), API.StatusAction.UNFOLLOW, finalTarget, ShowAccountActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); dialog.dismiss(); @@ -873,7 +872,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt new PostActionAsyncTask(getApplicationContext(), API.StatusAction.UNFOLLOW, finalTarget, ShowAccountActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } - }else if( doAction == action.UNBLOCK){ + } else if (doAction == action.UNBLOCK) { account_follow.setEnabled(false); new PostActionAsyncTask(getApplicationContext(), API.StatusAction.UNBLOCK, finalTarget, ShowAccountActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } @@ -882,32 +881,33 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt account_follow.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { - CrossActions.doCrossAction(ShowAccountActivity.this, null, null, account, API.StatusAction.FOLLOW , null, ShowAccountActivity.this, false); + CrossActions.doCrossAction(ShowAccountActivity.this, null, null, account, API.StatusAction.FOLLOW, null, ShowAccountActivity.this, false); return false; } }); TextView account_date = findViewById(R.id.account_date); account_date.setText(Helper.shortDateToString(account.getCreated_at())); - new Thread(new Runnable(){ + new Thread(new Runnable() { @Override public void run() { String instance = getLiveInstance(getApplicationContext()); - if( account.getAcct().split("@").length > 1 ){ + if (account.getAcct().split("@").length > 1) { instance = account.getAcct().split("@")[1]; } InstanceNodeInfo instanceNodeInfo = new API(ShowAccountActivity.this).displayNodeInfo(instance); runOnUiThread(new Runnable() { public void run() { - if(instanceNodeInfo != null && instanceNodeInfo.getName() != null){ - TextView instance_info = findViewById(R.id.instance_info); + if (instanceNodeInfo != null && instanceNodeInfo.getName() != null) { + TextView instance_info = findViewById(R.id.instance_info); instance_info.setText(instanceNodeInfo.getName()); instance_info.setVisibility(View.VISIBLE); TextView seperator = findViewById(R.id.seperator); seperator.setVisibility(View.VISIBLE); } - }}); + } + }); } @@ -915,11 +915,9 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt } - - @Override public void onRetrieveFeedsAccount(List statuses) { - if( statuses != null) { + if (statuses != null) { this.statuses.addAll(statuses); statusListAdapter.notifyDataSetChanged(); } @@ -927,8 +925,8 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt @Override public void onRetrieveFeeds(APIResponse apiResponse) { - if( apiResponse.getError() != null){ - Toasty.error(getApplicationContext(), apiResponse.getError().getError(),Toast.LENGTH_LONG).show(); + if (apiResponse.getError() != null) { + Toasty.error(getApplicationContext(), apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); return; } pins = apiResponse.getStatuses(); @@ -946,8 +944,8 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt @Override public void onRetrieveRelationship(Relationship relationship, Error error) { - if( error != null){ - Toasty.error(getApplicationContext(), error.getError(),Toast.LENGTH_LONG).show(); + if (error != null) { + Toasty.error(getApplicationContext(), error.getError(), Toast.LENGTH_LONG).show(); return; } this.relationship = relationship; @@ -955,7 +953,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt //The authenticated account is followed by the account - if( relationship != null && relationship.isFollowed_by() && !accountId.equals(userId)){ + if (relationship != null && relationship.isFollowed_by() && !accountId.equals(userId)) { TextView account_followed_by = findViewById(R.id.account_followed_by); account_followed_by.setVisibility(View.VISIBLE); } @@ -964,38 +962,39 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt } //Manages the visibility of the button - private void manageButtonVisibility(){ - if( relationship == null) + private void manageButtonVisibility() { + if (relationship == null) return; account_follow.setEnabled(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { account_follow.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ShowAccountActivity.this, R.color.mastodonC4))); } - if( account.getId() != null && account.getId().equals(userId) && (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA)){ + if (account.getId() != null && account.getId().equals(userId) && (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA)) { account_follow.setVisibility(View.GONE); header_edit_profile.setVisibility(View.VISIBLE); header_edit_profile.bringToFront(); - }else if( relationship.isBlocking()){ + } else if (relationship.isBlocking()) { account_follow.setImageResource(R.drawable.ic_lock_open); doAction = action.UNBLOCK; account_follow.setVisibility(View.VISIBLE); - }else if( relationship.isRequested()){ + } else if (relationship.isRequested()) { account_follow_request.setVisibility(View.VISIBLE); account_follow.setImageResource(R.drawable.ic_hourglass_full); account_follow.setVisibility(View.VISIBLE); doAction = action.UNFOLLOW; - }else if( relationship.isFollowing()){ + } else if (relationship.isFollowing()) { account_follow.setImageResource(R.drawable.ic_user_times); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { account_follow.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ShowAccountActivity.this, R.color.red_1))); } doAction = action.UNFOLLOW; account_follow.setVisibility(View.VISIBLE); - }else if( !relationship.isFollowing()){ + } else if (!relationship.isFollowing()) { account_follow.setImageResource(R.drawable.ic_user_plus); doAction = action.FOLLOW; - account_follow.setVisibility(View.VISIBLE);; - }else{ + account_follow.setVisibility(View.VISIBLE); + ; + } else { account_follow.setVisibility(View.GONE); doAction = action.NOTHING; } @@ -1013,34 +1012,34 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt @Override public Fragment getItem(int position) { Bundle bundle = new Bundle(); - switch (position){ + switch (position) { case 0: - if( ! peertubeAccount){ + if (!peertubeAccount) { TabLayoutTootsFragment tabLayoutTootsFragment = new TabLayoutTootsFragment(); bundle.putString("targetedid", account.getId()); tabLayoutTootsFragment.setArguments(bundle); return tabLayoutTootsFragment; - }else{ + } else { DisplayStatusFragment displayStatusFragment = new DisplayStatusFragment(); bundle = new Bundle(); bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.USER); bundle.putString("targetedid", account.getAcct()); bundle.putString("instanceType", "PEERTUBE"); - bundle.putBoolean("showReply",false); - bundle.putBoolean("ischannel",ischannel); + bundle.putBoolean("showReply", false); + bundle.putBoolean("ischannel", ischannel); displayStatusFragment.setArguments(bundle); return displayStatusFragment; } case 1: - if( peertubeAccount){ + if (peertubeAccount) { DisplayAccountsFragment displayAccountsFragment = new DisplayAccountsFragment(); bundle.putSerializable("type", RetrieveAccountsAsyncTask.Type.CHANNELS); bundle.putString("targetedid", account.getId()); bundle.putString("instance", Helper.getLiveInstance(ShowAccountActivity.this)); - bundle.putString("name",account.getAcct()); + bundle.putString("name", account.getAcct()); displayAccountsFragment.setArguments(bundle); return displayAccountsFragment; - }else{ + } else { DisplayAccountsFragment displayAccountsFragment = new DisplayAccountsFragment(); bundle.putSerializable("type", RetrieveAccountsAsyncTask.Type.FOLLOWING); bundle.putString("targetedid", account.getId()); @@ -1062,9 +1061,9 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt @Override public int getCount() { - if( ischannel) + if (ischannel) return 1; - else if( peertubeAccount) + else if (peertubeAccount) return 2; else return 3; @@ -1076,21 +1075,21 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt account_note.setText(account.getNoteSpan(), TextView.BufferType.SPANNABLE); account_dn.setText(account.getdisplayNameSpan(), TextView.BufferType.SPANNABLE); LinkedHashMap fieldsVerified = account.getFieldsVerified(); - if ( account.getFieldsSpan() != null && account.getFieldsSpan().size() > 0){ + if (account.getFieldsSpan() != null && account.getFieldsSpan().size() > 0) { HashMap fieldsSpan = account.getFieldsSpan(); Iterator it = fieldsSpan.entrySet().iterator(); int i = 1; LinearLayout fields_container = findViewById(R.id.fields_container); - if( fields_container != null) + if (fields_container != null) fields_container.setVisibility(View.VISIBLE); while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - SpannableString label = (SpannableString)pair.getKey(); - SpannableString value = (SpannableString)pair.getValue(); + Map.Entry pair = (Map.Entry) it.next(); + SpannableString label = (SpannableString) pair.getKey(); + SpannableString value = (SpannableString) pair.getValue(); LinearLayout field; TextView labelView; TextView valueView; - switch(i){ + switch (i) { case 1: field = findViewById(R.id.field1); labelView = findViewById(R.id.label1); @@ -1117,15 +1116,15 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt valueView = findViewById(R.id.value1); break; } - if( field != null && labelView != null && valueView != null) { + if (field != null && labelView != null && valueView != null) { field.setVisibility(View.VISIBLE); valueView.setText(value, TextView.BufferType.SPANNABLE); valueView.setMovementMethod(LinkMovementMethod.getInstance()); labelView.setText(label); } - if( field != null && labelView != null && valueView != null) { - boolean verified = fieldsVerified.get((String)pair.getKey().toString()); - if( verified) { + if (field != null && labelView != null && valueView != null) { + boolean verified = fieldsVerified.get((String) pair.getKey().toString()); + if (verified) { valueView.setBackgroundResource(R.drawable.verified); value.setSpan(new ForegroundColorSpan(ContextCompat.getColor(ShowAccountActivity.this, R.color.verified_text)), 0, value.toString().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); @@ -1139,10 +1138,10 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt i++; } } - if( account.getEmojis() != null && account.getEmojis().size() > 0 ){ + if (account.getEmojis() != null && account.getEmojis().size() > 0) { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); boolean disableAnimatedEmoji = sharedpreferences.getBoolean(Helper.SET_DISABLE_ANIMATED_EMOJI, false); - if( !disableAnimatedEmoji) { + if (!disableAnimatedEmoji) { scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override @@ -1154,8 +1153,8 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt } } - private void showMenu(View account_menu){ - if( account == null) + private void showMenu(View account_menu) { + if (account == null) return; final PopupMenu popup = new PopupMenu(ShowAccountActivity.this, account_menu); popup.getMenuInflater() @@ -1165,13 +1164,14 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt final boolean isOwner = account.getId().equals(userId); String[] splitAcct = account.getAcct().split("@"); - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) popup.getMenu().findItem(R.id.action_filter).setVisible(true); - if( splitAcct.length <= 1) { + if (splitAcct.length <= 1) { popup.getMenu().findItem(R.id.action_follow_instance).setVisible(false); popup.getMenu().findItem(R.id.action_block_instance).setVisible(false); - }if( isOwner) { + } + if (isOwner) { popup.getMenu().findItem(R.id.action_block).setVisible(false); popup.getMenu().findItem(R.id.action_report).setVisible(false); popup.getMenu().findItem(R.id.action_mute).setVisible(false); @@ -1182,38 +1182,38 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt popup.getMenu().findItem(R.id.action_endorse).setVisible(false); popup.getMenu().findItem(R.id.action_direct_message).setVisible(false); popup.getMenu().findItem(R.id.action_add_to_list).setVisible(false); - stringArrayConf = getResources().getStringArray(R.array.more_action_owner_confirm); - }else { + stringArrayConf = getResources().getStringArray(R.array.more_action_owner_confirm); + } else { popup.getMenu().findItem(R.id.action_block).setVisible(true); popup.getMenu().findItem(R.id.action_mute).setVisible(true); popup.getMenu().findItem(R.id.action_mention).setVisible(true); - stringArrayConf = getResources().getStringArray(R.array.more_action_confirm); + stringArrayConf = getResources().getStringArray(R.array.more_action_confirm); } - if( peertubeAccount){ + if (peertubeAccount) { popup.getMenu().findItem(R.id.action_hide_boost).setVisible(false); popup.getMenu().findItem(R.id.action_endorse).setVisible(false); popup.getMenu().findItem(R.id.action_direct_message).setVisible(false); popup.getMenu().findItem(R.id.action_add_to_list).setVisible(false); } - if( relationship != null){ - if( !relationship.isFollowing()) { + if (relationship != null) { + if (!relationship.isFollowing()) { popup.getMenu().findItem(R.id.action_hide_boost).setVisible(false); popup.getMenu().findItem(R.id.action_endorse).setVisible(false); } - if( relationship.isBlocking()){ + if (relationship.isBlocking()) { popup.getMenu().findItem(R.id.action_block).setTitle(R.string.action_unblock); } - if( relationship.isMuting()){ + if (relationship.isMuting()) { popup.getMenu().findItem(R.id.action_mute).setTitle(R.string.action_unmute); } - if(relationship.isEndorsed()){ + if (relationship.isEndorsed()) { popup.getMenu().findItem(R.id.action_endorse).setTitle(R.string.unendorse); - }else { + } else { popup.getMenu().findItem(R.id.action_endorse).setTitle(R.string.endorse); } - if(relationship.isShowing_reblogs()){ + if (relationship.isShowing_reblogs()) { popup.getMenu().findItem(R.id.action_hide_boost).setTitle(getString(R.string.hide_boost, account.getUsername())); - }else { + } else { popup.getMenu().findItem(R.id.action_hide_boost).setTitle(getString(R.string.show_boost, account.getUsername())); } } @@ -1226,9 +1226,9 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } switch (item.getItemId()) { @@ -1236,44 +1236,43 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt String finalInstanceName = splitAcct[1]; final SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); List remoteInstances = new InstancesDAO(ShowAccountActivity.this, db).getInstanceByName(finalInstanceName); - if( remoteInstances != null && remoteInstances.size() > 0 ){ - Toasty.info(getApplicationContext(), getString(R.string.toast_instance_already_added),Toast.LENGTH_LONG).show(); + if (remoteInstances != null && remoteInstances.size() > 0) { + Toasty.info(getApplicationContext(), getString(R.string.toast_instance_already_added), Toast.LENGTH_LONG).show(); Intent intent = new Intent(getApplicationContext(), MainActivity.class); Bundle bundle = new Bundle(); bundle.putInt(Helper.INTENT_ACTION, Helper.SEARCH_INSTANCE); - bundle.putString(Helper.INSTANCE_NAME,finalInstanceName); + bundle.putString(Helper.INSTANCE_NAME, finalInstanceName); intent.putExtras(bundle); startActivity(intent); return true; } - new Thread(new Runnable(){ + new Thread(new Runnable() { @Override public void run() { try { - if( !peertubeAccount) { + if (!peertubeAccount) { //Here we can't know if the instance is a Mastodon one or not try { //Testing Mastodon new HttpsConnection(ShowAccountActivity.this, null).get("https://" + finalInstanceName + "/api/v1/timelines/public?local=true", 10, null, null); - }catch (Exception ignored){ + } catch (Exception ignored) { new HttpsConnection(ShowAccountActivity.this, null).get("https://" + finalInstanceName + "/api/v1/videos/", 10, null, null); peertubeAccount = true; } - } - else + } else new HttpsConnection(ShowAccountActivity.this, null).get("https://" + finalInstanceName + "/api/v1/videos/", 10, null, null); runOnUiThread(new Runnable() { public void run() { final SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - if( !peertubeAccount) + if (!peertubeAccount) new InstancesDAO(ShowAccountActivity.this, db).insertInstance(finalInstanceName, "MASTODON"); else new InstancesDAO(ShowAccountActivity.this, db).insertInstance(finalInstanceName, "PEERTUBE"); - Toasty.success(getApplicationContext(), getString(R.string.toast_instance_followed),Toast.LENGTH_LONG).show(); + Toasty.success(getApplicationContext(), getString(R.string.toast_instance_followed), Toast.LENGTH_LONG).show(); Intent intent = new Intent(getApplicationContext(), MainActivity.class); Bundle bundle = new Bundle(); bundle.putInt(Helper.INTENT_ACTION, Helper.SEARCH_INSTANCE); - bundle.putString(Helper.INSTANCE_NAME,finalInstanceName); + bundle.putString(Helper.INSTANCE_NAME, finalInstanceName); intent.putExtras(bundle); startActivity(intent); } @@ -1282,7 +1281,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt e.printStackTrace(); runOnUiThread(new Runnable() { public void run() { - Toasty.warning(getApplicationContext(), getString(R.string.toast_instance_unavailable),Toast.LENGTH_LONG).show(); + Toasty.warning(getApplicationContext(), getString(R.string.toast_instance_unavailable), Toast.LENGTH_LONG).show(); } }); } @@ -1293,17 +1292,17 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt AlertDialog.Builder filterTagDialog = new AlertDialog.Builder(ShowAccountActivity.this, style); Set featuredTagsSet = sharedpreferences.getStringSet(Helper.SET_FEATURED_TAGS, null); List tags = new ArrayList<>(); - if( featuredTagsSet != null){ + if (featuredTagsSet != null) { tags = new ArrayList<>(featuredTagsSet); } - tags.add(0,getString(R.string.no_tags)); + tags.add(0, getString(R.string.no_tags)); String[] tagsString = tags.toArray(new String[tags.size()]); List finalTags = tags; String tag = sharedpreferences.getString(Helper.SET_FEATURED_TAG_ACTION, null); int checkedposition = 0; int i = 0; - for(String _t: tags){ - if( tag != null && _t.equals(tag)) + for (String _t : tags) { + if (tag != null && _t.equals(tag)) checkedposition = i; i++; } @@ -1311,9 +1310,9 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt .OnClickListener() { public void onClick(DialogInterface dialog, int item) { String tag; - if( item == 0){ + if (item == 0) { tag = null; - }else { + } else { tag = finalTags.get(item); } SharedPreferences.Editor editor = sharedpreferences.edit(); @@ -1325,18 +1324,18 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt filterTagDialog.show(); return true; case R.id.action_endorse: - if( relationship != null) - if(relationship.isEndorsed()){ + if (relationship != null) + if (relationship.isEndorsed()) { new PostActionAsyncTask(getApplicationContext(), API.StatusAction.UNENDORSE, account.getId(), ShowAccountActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else { + } else { new PostActionAsyncTask(getApplicationContext(), API.StatusAction.ENDORSE, account.getId(), ShowAccountActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } return true; case R.id.action_hide_boost: - if( relationship != null) - if(relationship.isShowing_reblogs()){ + if (relationship != null) + if (relationship.isShowing_reblogs()) { new PostActionAsyncTask(getApplicationContext(), API.StatusAction.HIDE_BOOST, account.getId(), ShowAccountActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else { + } else { new PostActionAsyncTask(getApplicationContext(), API.StatusAction.SHOW_BOOST, account.getId(), ShowAccountActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } return true; @@ -1349,16 +1348,16 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt startActivity(intent); return true; case R.id.action_add_to_list: - if( timelines!= null){ + if (timelines != null) { ArrayAdapter arrayAdapter = new ArrayAdapter(ShowAccountActivity.this, android.R.layout.select_dialog_item); boolean hasLists = false; - for(ManageTimelines timeline: timelines){ - if( timeline.getListTimeline() != null){ + for (ManageTimelines timeline : timelines) { + if (timeline.getListTimeline() != null) { arrayAdapter.add(timeline.getListTimeline().getTitle()); hasLists = true; } } - if(! hasLists){ + if (!hasLists) { Toasty.info(getApplicationContext(), getString(R.string.action_lists_empty), Toast.LENGTH_SHORT).show(); return true; } @@ -1375,13 +1374,13 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt @Override public void onClick(DialogInterface dialog, int which) { String listTitle = arrayAdapter.getItem(which); - for(ManageTimelines timeline: timelines){ - if( timeline.getListTimeline() != null && timeline.getListTimeline().getTitle().equals(listTitle)){ + for (ManageTimelines timeline : timelines) { + if (timeline.getListTimeline() != null && timeline.getListTimeline().getTitle().equals(listTitle)) { app.fedilab.android.client.Entities.List list = timeline.getListTimeline(); - if( relationship == null || !relationship.isFollowing()){ + if (relationship == null || !relationship.isFollowing()) { addToList = list.getId(); new PostActionAsyncTask(getApplicationContext(), API.StatusAction.FOLLOW, account.getId(), ShowAccountActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else{ + } else { new ManageListsAsyncTask(ShowAccountActivity.this, ManageListsAsyncTask.action.ADD_USERS, new String[]{account.getId()}, null, list.getId(), null, ShowAccountActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } break; @@ -1393,8 +1392,8 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt } return true; case R.id.action_open_browser: - if( accountUrl != null) { - if( !accountUrl.startsWith("http://") && ! accountUrl.startsWith("https://")) + if (accountUrl != null) { + if (!accountUrl.startsWith("http://") && !accountUrl.startsWith("https://")) accountUrl = "http://" + accountUrl; Helper.openBrowser(ShowAccountActivity.this, accountUrl); } @@ -1430,13 +1429,13 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt doActionAccount = API.StatusAction.REPORT; builderInner.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog,int which) { + public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builderInner.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog,int which) { + public void onClick(DialogInterface dialog, int which) { String targetedId; String comment = null; if (input.getText() != null) @@ -1463,17 +1462,17 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt } builderInner.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog,int which) { + public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builderInner.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog,int which) { + public void onClick(DialogInterface dialog, int which) { String targetedId; - if( item.getItemId() == R.id.action_block_instance){ + if (item.getItemId() == R.id.action_block_instance) { targetedId = account.getAcct().split("@")[1]; - }else { + } else { targetedId = account.getId(); } new PostActionAsyncTask(getApplicationContext(), doActionAccount, targetedId, ShowAccountActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); @@ -1489,47 +1488,46 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt @Override - public void onDestroy(){ + public void onDestroy() { super.onDestroy(); } - @Override - public void onStop(){ + public void onStop() { super.onStop(); - if( scheduledExecutorService != null) { + if (scheduledExecutorService != null) { scheduledExecutorService.shutdownNow(); } - if( accountAsync != null && !accountAsync.isCancelled()){ + if (accountAsync != null && !accountAsync.isCancelled()) { accountAsync.cancel(true); } - if( retrieveRelationship != null && !retrieveRelationship.isCancelled()){ + if (retrieveRelationship != null && !retrieveRelationship.isCancelled()) { retrieveRelationship.cancel(true); } } @Override - public void onPostAction(int statusCode,API.StatusAction statusAction, String targetedId, Error error) { + public void onPostAction(int statusCode, API.StatusAction statusAction, String targetedId, Error error) { - if( error != null){ - Toasty.error(getApplicationContext(), error.getError(),Toast.LENGTH_LONG).show(); + if (error != null) { + Toasty.error(getApplicationContext(), error.getError(), Toast.LENGTH_LONG).show(); return; } - if( addToList != null){ + if (addToList != null) { new ManageListsAsyncTask(ShowAccountActivity.this, ManageListsAsyncTask.action.ADD_USERS, new String[]{account.getId()}, null, addToList, null, ShowAccountActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else { + } else { Helper.manageMessageStatusCode(getApplicationContext(), statusCode, statusAction); } String target = account.getId(); //IF action is unfollow or mute, sends an intent to remove statuses - if( statusAction == API.StatusAction.UNFOLLOW || statusAction == API.StatusAction.MUTE){ + if (statusAction == API.StatusAction.UNFOLLOW || statusAction == API.StatusAction.MUTE) { Bundle b = new Bundle(); b.putString("receive_action", targetedId); Intent intentBC = new Intent(Helper.RECEIVE_ACTION); intentBC.putExtras(b); } - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) target = account.getAcct(); retrieveRelationship = new RetrieveRelationshipAsyncTask(getApplicationContext(), target, ShowAccountActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } @@ -1538,11 +1536,11 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt @Override public void onRetrieveAccount(final Account account, Error error) { - if( error != null || account == null || account.getAcct() == null){ - if( error == null) - Toasty.error(getApplicationContext(), getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + if (error != null || account == null || account.getAcct() == null) { + if (error == null) + Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); else - Toasty.error(getApplicationContext(), error.getError(),Toast.LENGTH_LONG).show(); + Toasty.error(getApplicationContext(), error.getError(), Toast.LENGTH_LONG).show(); return; } this.account = account; @@ -1552,21 +1550,21 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt @Override public void onActionDone(ManageListsAsyncTask.action actionType, APIResponse apiResponse, int statusCode) { if (apiResponse.getError() != null) { - if ( !apiResponse.getError().getError().startsWith("404 -")) + if (!apiResponse.getError().getError().startsWith("404 -")) Toasty.error(getApplicationContext(), apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); return; } - if( actionType == ManageListsAsyncTask.action.ADD_USERS) { + if (actionType == ManageListsAsyncTask.action.ADD_USERS) { Toasty.success(getApplicationContext(), getString(R.string.action_lists_add_user), Toast.LENGTH_LONG).show(); } } - public boolean showReplies(){ + public boolean showReplies() { return show_replies; } - public boolean showBoosts(){ + public boolean showBoosts() { return show_boosts; } diff --git a/app/src/main/java/app/fedilab/android/activities/ShowConversationActivity.java b/app/src/main/java/app/fedilab/android/activities/ShowConversationActivity.java index d55ef24be..2da257c78 100644 --- a/app/src/main/java/app/fedilab/android/activities/ShowConversationActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/ShowConversationActivity.java @@ -23,6 +23,7 @@ import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.os.Bundle; + import androidx.core.content.ContextCompat; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; @@ -64,7 +65,7 @@ import app.fedilab.android.interfaces.OnRetrieveContextInterface; * Show conversation activity class */ -public class ShowConversationActivity extends BaseActivity implements OnRetrieveContextInterface { +public class ShowConversationActivity extends BaseActivity implements OnRetrieveContextInterface { private Status initialStatus; @@ -85,7 +86,7 @@ public class ShowConversationActivity extends BaseActivity implements OnRetriev SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme_NoActionBar_Fedilab); break; @@ -102,27 +103,27 @@ public class ShowConversationActivity extends BaseActivity implements OnRetriev setContentView(R.layout.activity_show_conversation); lv_status = findViewById(R.id.lv_status); Toolbar toolbar = findViewById(R.id.toolbar); - if( theme == Helper.THEME_BLACK) + if (theme == Helper.THEME_BLACK) toolbar.setBackgroundColor(ContextCompat.getColor(ShowConversationActivity.this, R.color.black)); setSupportActionBar(toolbar); - spoilerShown = spoilerBehaviour =sharedpreferences.getBoolean(Helper.SET_EXPAND_CW, false); + spoilerShown = spoilerBehaviour = sharedpreferences.getBoolean(Helper.SET_EXPAND_CW, false); Bundle b = getIntent().getExtras(); statuses = new ArrayList<>(); - if(b != null) { + if (b != null) { detailsStatus = b.getParcelable("status"); - expanded = b.getBoolean("expanded", false); + expanded = b.getBoolean("expanded", false); initialStatus = b.getParcelable("initialStatus"); - conversationId = b.getString("conversationId", null); + conversationId = b.getString("conversationId", null); } - if( detailsStatus == null || detailsStatus.getId() == null) + if (detailsStatus == null || detailsStatus.getId() == null) finish(); detailsStatus.setFocused(true); - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { - if( receive_action != null) + if (receive_action != null) LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(receive_action); receive_action = new BroadcastReceiver() { @Override @@ -130,7 +131,7 @@ public class ShowConversationActivity extends BaseActivity implements OnRetriev Bundle b = intent.getExtras(); assert b != null; Status status = b.getParcelable("status"); - if( status != null && statusListAdapter != null) { + if (status != null && statusListAdapter != null) { statusListAdapter.notifyStatusWithActionChanged(status); } } @@ -138,12 +139,12 @@ public class ShowConversationActivity extends BaseActivity implements OnRetriev LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(receive_action, new IntentFilter(Helper.RECEIVE_ACTION)); } - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); - if( getSupportActionBar() != null) { + if (getSupportActionBar() != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); assert inflater != null; - View view = inflater.inflate(R.layout.conversation_action_bar, new LinearLayout(getApplicationContext()), false); + View view = inflater.inflate(R.layout.conversation_action_bar, new LinearLayout(getApplicationContext()), false); getSupportActionBar().setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); TextView title = getSupportActionBar().getCustomView().findViewById(R.id.toolbar_title); @@ -153,19 +154,19 @@ public class ShowConversationActivity extends BaseActivity implements OnRetriev title.setText(R.string.conversation); ImageView close_conversation = getSupportActionBar().getCustomView().findViewById(R.id.close_conversation); ImageView action_unhide = getSupportActionBar().getCustomView().findViewById(R.id.action_unhide); - if( expanded) + if (expanded) action_expand.setImageResource(R.drawable.ic_expand_less); else action_expand.setImageResource(R.drawable.ic_expand_more); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { - if( lv_status != null) { + if (lv_status != null) { lv_status.setAdapter(statusListAdapter); } } }); - if( close_conversation != null){ + if (close_conversation != null) { close_conversation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -180,7 +181,7 @@ public class ShowConversationActivity extends BaseActivity implements OnRetriev Bundle b = new Bundle(); b.putParcelable("status", detailsStatus); b.putBoolean("expanded", expanded); - if( expanded && statuses != null && statuses.size() > 0) + if (expanded && statuses != null && statuses.size() > 0) b.putParcelable("initialStatus", statuses.get(0)); intent.putExtras(b); finish(); @@ -191,12 +192,12 @@ public class ShowConversationActivity extends BaseActivity implements OnRetriev action_unhide.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - if( statuses != null && statuses.size() > 0) { + if (statuses != null && statuses.size() > 0) { spoilerShown = !spoilerShown; for (Status status : statuses) { - if( spoilerBehaviour && !status.isSpoilerShown() ){ + if (spoilerBehaviour && !status.isSpoilerShown()) { status.setAutoHiddenCW(true); - }else{ + } else { status.setAutoHiddenCW(false); } status.setSpoilerShown(spoilerShown); @@ -215,7 +216,7 @@ public class ShowConversationActivity extends BaseActivity implements OnRetriev Bundle b = new Bundle(); b.putParcelable("status", detailsStatus); b.putBoolean("expanded", expanded); - if( expanded && statuses != null && statuses.size() > 0) + if (expanded && statuses != null && statuses.size() > 0) b.putParcelable("initialStatus", statuses.get(0)); intent.putExtras(b); finish(); @@ -225,19 +226,19 @@ public class ShowConversationActivity extends BaseActivity implements OnRetriev } }); - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Helper.colorizeToolbar(getSupportActionBar().getCustomView().findViewById(R.id.toolbar), R.color.black, ShowConversationActivity.this); } - }else{ + } else { setTitle(R.string.conversation); } SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, null); - Account account = new AccountDAO(getApplicationContext(),db).getUniqAccount(userId, instance); - if( account.getAvatar() == null){ - Toasty.error(getApplicationContext(),getString(R.string.toast_error), Toast.LENGTH_LONG).show(); + Account account = new AccountDAO(getApplicationContext(), db).getUniqAccount(userId, instance); + if (account.getAvatar() == null) { + Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); finish(); } Helper.loadGiF(getApplicationContext(), account.getAvatar(), pp_actionBar); @@ -245,7 +246,7 @@ public class ShowConversationActivity extends BaseActivity implements OnRetriev swipeRefreshLayout = findViewById(R.id.swipeContainer); boolean isOnWifi = Helper.isOnWIFI(getApplicationContext()); - if( initialStatus != null) + if (initialStatus != null) statuses.add(initialStatus); else statuses.add(detailsStatus); @@ -257,17 +258,17 @@ public class ShowConversationActivity extends BaseActivity implements OnRetriev lv_status.addItemDecoration(new ConversationDecoration(ShowConversationActivity.this, theme)); lv_status.setAdapter(statusListAdapter); String statusIdToFetch = null; - if( initialStatus != null) + if (initialStatus != null) statusIdToFetch = initialStatus.getId(); - else if(detailsStatus != null) + else if (detailsStatus != null) statusIdToFetch = detailsStatus.getId(); - if( statusIdToFetch == null) + if (statusIdToFetch == null) finish(); - if( conversationId != null) + if (conversationId != null) statusIdToFetch = conversationId; - new RetrieveContextAsyncTask(getApplicationContext(),expanded, detailsStatus.getVisibility().equals("direct"), statusIdToFetch, ShowConversationActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - switch (theme){ + new RetrieveContextAsyncTask(getApplicationContext(), expanded, detailsStatus.getVisibility().equals("direct"), statusIdToFetch, ShowConversationActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + switch (theme) { case Helper.THEME_LIGHT: swipeRefreshLayout.setColorSchemeResources(R.color.mastodonC4, R.color.mastodonC2, @@ -295,7 +296,7 @@ public class ShowConversationActivity extends BaseActivity implements OnRetriev Bundle b = new Bundle(); b.putParcelable("status", detailsStatus); b.putBoolean("expanded", expanded); - if( expanded && statuses != null && statuses.size() > 0) + if (expanded && statuses != null && statuses.size() > 0) b.putParcelable("initialStatus", statuses.get(0)); b.putParcelable("status", detailsStatus); intent.putExtras(b); @@ -308,13 +309,13 @@ public class ShowConversationActivity extends BaseActivity implements OnRetriev } - public void addStatuses(Status status){ - if( status != null && status.getIn_reply_to_id() != null && this.statuses != null){ + public void addStatuses(Status status) { + if (status != null && status.getIn_reply_to_id() != null && this.statuses != null) { int position = 0; - for(Status s: this.statuses){ - if(status.getIn_reply_to_id().equals(s.getId())){ - this.statuses.add(position+1, status); - statusListAdapter.notifyItemInserted(position+1); + for (Status s : this.statuses) { + if (status.getIn_reply_to_id().equals(s.getId())) { + this.statuses.add(position + 1, status); + statusListAdapter.notifyItemInserted(position + 1); break; } position++; @@ -336,70 +337,70 @@ public class ShowConversationActivity extends BaseActivity implements OnRetriev @Override public void onDestroy() { super.onDestroy(); - if( receive_action != null) + if (receive_action != null) LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(receive_action); } @Override public void onRetrieveContext(Context context, Error error) { swipeRefreshLayout.setRefreshing(false); - if( error != null ){ - Toasty.error(getApplicationContext(), error.getError(),Toast.LENGTH_LONG).show(); + if (error != null) { + Toasty.error(getApplicationContext(), error.getError(), Toast.LENGTH_LONG).show(); return; } - if( context.getAncestors() == null ){ + if (context.getAncestors() == null) { return; } - if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA){ - statusListAdapter.setConversationPosition( context.getAncestors().size()); - if(!expanded) { + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + statusListAdapter.setConversationPosition(context.getAncestors().size()); + if (!expanded) { if (context.getAncestors() != null && context.getAncestors().size() > 0) { statuses.addAll(0, context.getAncestors()); statusListAdapter.notifyItemRangeInserted(0, context.getAncestors().size()); } if (context.getDescendants() != null && context.getDescendants().size() > 0) { statuses.addAll(context.getAncestors().size() + 1, context.getDescendants()); - statusListAdapter.notifyItemRangeChanged(context.getAncestors().size()+1, context.getDescendants().size()); + statusListAdapter.notifyItemRangeChanged(context.getAncestors().size() + 1, context.getDescendants().size()); } - }else{ + } else { List statusesTemp = context.getDescendants(); int i = 1; int position = 0; - for(Status status: statusesTemp){ + for (Status status : statusesTemp) { statuses.add(status); - if( status.getId().equals(detailsStatus.getId())) { + if (status.getId().equals(detailsStatus.getId())) { statusListAdapter.setConversationPosition(i); detailsStatus = status; position = i; } i++; } - statusListAdapter.notifyItemRangeChanged(1,context.getDescendants().size()); + statusListAdapter.notifyItemRangeChanged(1, context.getDescendants().size()); lv_status.scrollToPosition(position); } - }else{ + } else { int i = 0; - if( context.getAncestors() != null && context.getAncestors().size() > 1){ + if (context.getAncestors() != null && context.getAncestors().size() > 1) { statuses = new ArrayList<>(); statuses.clear(); - for(Status status: context.getAncestors()){ - if(detailsStatus.equals(status)) { + for (Status status : context.getAncestors()) { + if (detailsStatus.equals(status)) { break; } i++; } boolean isOnWifi = Helper.isOnWIFI(getApplicationContext()); - for(Status status: context.getAncestors()){ - statuses.add(0,status); + for (Status status : context.getAncestors()) { + statuses.add(0, status); } - statusListAdapter = new StatusListAdapter((statuses.size()-1-i), null, isOnWifi, statuses); - statusListAdapter.setConversationPosition((statuses.size()-1-i)); + statusListAdapter = new StatusListAdapter((statuses.size() - 1 - i), null, isOnWifi, statuses); + statusListAdapter.setConversationPosition((statuses.size() - 1 - i)); final LinearLayoutManager mLayoutManager; mLayoutManager = new LinearLayoutManager(this); lv_status.setLayoutManager(mLayoutManager); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme_NoActionBar_Fedilab); break; diff --git a/app/src/main/java/app/fedilab/android/activities/TagCacheActivity.java b/app/src/main/java/app/fedilab/android/activities/TagCacheActivity.java index 8ce26dd85..15d1e88f8 100644 --- a/app/src/main/java/app/fedilab/android/activities/TagCacheActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/TagCacheActivity.java @@ -19,9 +19,11 @@ import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.os.Bundle; + import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; + import android.view.View; import android.view.ViewGroup; import android.view.Window; @@ -58,7 +60,7 @@ public class TagCacheActivity extends BaseActivity { requestWindowFeature(Window.FEATURE_NO_TITLE); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme_NoActionBar_Fedilab); getWindow().getDecorView().setBackgroundColor(ContextCompat.getColor(TagCacheActivity.this, R.color.mastodonC3__)); @@ -88,10 +90,10 @@ public class TagCacheActivity extends BaseActivity { save_tag.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - if( tag_add.getText() != null && tag_add.getText().toString().trim().replaceAll("\\#","").length() > 0) { - String tagToInsert = tag_add.getText().toString().trim().replaceAll("\\#",""); + if (tag_add.getText() != null && tag_add.getText().toString().trim().replaceAll("\\#", "").length() > 0) { + String tagToInsert = tag_add.getText().toString().trim().replaceAll("\\#", ""); boolean isPresent = new TagsCacheDAO(TagCacheActivity.this, db).isPresent(tagToInsert); - if( isPresent) + if (isPresent) Toasty.warning(TagCacheActivity.this, getString(R.string.tags_already_stored), Toast.LENGTH_LONG).show(); else { new TagsCacheDAO(TagCacheActivity.this, db).insert(tagToInsert); @@ -111,9 +113,9 @@ public class TagCacheActivity extends BaseActivity { public void run() { List tagsTemp = new TagsCacheDAO(TagCacheActivity.this, db).getAll(); - if( tagsTemp != null) + if (tagsTemp != null) tags = tagsTemp; - if( tags != null){ + if (tags != null) { tagsEditAdapter = new TagsEditAdapter(tags); tag_list.setAdapter(tagsEditAdapter); LinearLayoutManager mLayoutManager = new LinearLayoutManager(TagCacheActivity.this); diff --git a/app/src/main/java/app/fedilab/android/activities/TootActivity.java b/app/src/main/java/app/fedilab/android/activities/TootActivity.java index 053a7138e..e7605898e 100644 --- a/app/src/main/java/app/fedilab/android/activities/TootActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/TootActivity.java @@ -38,6 +38,7 @@ import android.os.Environment; import android.os.Handler; import android.os.Looper; import android.provider.MediaStore; + import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.core.app.ActivityCompat; @@ -215,7 +216,6 @@ import static app.fedilab.android.helper.Helper.countWithEmoji; public class TootActivity extends BaseActivity implements UploadStatusDelegate, OnPostActionInterface, OnRetrieveSearcAccountshInterface, OnPostStatusActionInterface, OnRetrieveSearchInterface, OnRetrieveAccountsReplyInterface, OnRetrieveEmojiInterface, OnDownloadInterface, OnRetrieveAttachmentInterface, OnRetrieveRelationshipInterface { - private String visibility; private final int PICK_IMAGE = 56556; private final int TAKE_PHOTO = 56532; @@ -284,7 +284,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, private EditText wysiwygEditText; private String url_for_media; private UpdateAccountInfoAsyncTask.SOCIAL social; - List emojis; + List emojis; @Override protected void onCreate(Bundle savedInstanceState) { @@ -323,7 +323,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); assert inflater != null; - View view = inflater.inflate(R.layout.toot_action_bar, new LinearLayout(getApplicationContext()), false); + View view = inflater.inflate(R.layout.toot_action_bar, new LinearLayout(getApplicationContext()), false); actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); ImageView close_toot = actionBar.getCustomView().findViewById(R.id.close_toot); @@ -335,14 +335,14 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, assert inputMethodManager != null; inputMethodManager.hideSoftInputFromWindow(toot_content.getWindowToken(), 0); boolean storeToot = sharedpreferences.getBoolean(Helper.SET_AUTO_STORE, true); - if( !storeToot ) { - if (toot_content.getText().toString().trim().length() == 0 && (attachments == null || attachments.size() < 1) && toot_cw_content.getText().toString().trim().length() == 0){ + if (!storeToot) { + if (toot_content.getText().toString().trim().length() == 0 && (attachments == null || attachments.size() < 1) && toot_cw_content.getText().toString().trim().length() == 0) { finish(); - }else if (!displayWYSIWYG() && initialContent.trim().equals(toot_content.getText().toString().trim())){ - finish(); - }else if (displayWYSIWYG() && initialContent.trim().equals(wysiwyg.getContentAsHTML().trim())){ + } else if (!displayWYSIWYG() && initialContent.trim().equals(toot_content.getText().toString().trim())) { finish(); - }else { + } else if (displayWYSIWYG() && initialContent.trim().equals(wysiwyg.getContentAsHTML().trim())) { + finish(); + } else { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(TootActivity.this, style); dialogBuilder.setMessage(R.string.save_draft); dialogBuilder.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() { @@ -369,7 +369,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, alertDialog.show(); } - }else{ + } else { finish(); } } @@ -386,7 +386,6 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, changeColor(); - //By default the toot is not restored so the id -1 is defined currentToId = -1; restoredScheduled = false; @@ -430,7 +429,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, ScrollView wysiwyg_container = findViewById(R.id.wysiwyg_container); wysiwyg = findViewById(R.id.editor); - switch (theme){ + switch (theme) { case THEME_LIGHT: wysiwyg.setEditorTextColor("#000000"); break; @@ -440,7 +439,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, break; } - if( displayWYSIWYG()){ + if (displayWYSIWYG()) { wysiwyg_container.setVisibility(View.VISIBLE); composer_container.setVisibility(View.GONE); HorizontalScrollView toolbar_scrollview = findViewById(R.id.toolbar_scrollview); @@ -520,9 +519,10 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, totalChar = countLength(wysiwyg, toot_cw_content); toot_space_left.setText(String.valueOf(totalChar)); } + @Override public void onUpload(Bitmap image, String uuid) { - if( url_for_media != null) { + if (url_for_media != null) { wysiwyg.onImageUploadComplete(url_for_media, uuid); } } @@ -563,7 +563,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, accountReply = null; if (accountReplyToken != null) { String[] val = accountReplyToken.split("\\|"); - if( val.length == 2) { + if (val.length == 2) { accountReply = new AccountDAO(getApplicationContext(), db).getUniqAccount(val[0], val[1]); } } @@ -579,7 +579,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, visibility = b.getString("visibility", null); restoredScheduled = b.getBoolean("restoredScheduled", false); quickmessagecontent = b.getString("quickmessagecontent", null); - quickmessagevisibility = b.getString("quickmessagevisibility", null); + quickmessagevisibility = b.getString("quickmessagevisibility", null); // ACTION_SEND route if (b.getInt("uriNumberMast", 0) == 1) { Uri fileUri = b.getParcelable("sharedUri"); @@ -597,11 +597,11 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } restored = b.getLong("restored", -1); } - if( tootReply != null){ - if( tootReply.getAccount().getMoved_to_account() != null){ + if (tootReply != null) { + if (tootReply.getAccount().getMoved_to_account() != null) { warning_message.setVisibility(View.VISIBLE); } - new RetrieveRelationshipAsyncTask(getApplicationContext(), tootReply.getAccount().getId(),TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new RetrieveRelationshipAsyncTask(getApplicationContext(), tootReply.getAccount().getId(), TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } if (scheduledstatus != null) toot_it.setText(R.string.modify); @@ -613,7 +613,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, if (accountReply == null) { userIdReply = sharedpreferences.getString(Helper.PREF_KEY_ID, null); instanceReply = sharedpreferences.getString(Helper.PREF_INSTANCE, null); - }else { + } else { userIdReply = accountReply.getId(); instanceReply = accountReply.getInstance(); } @@ -676,7 +676,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } toot_content.requestFocus(); - if( quickmessagecontent == null) { + if (quickmessagecontent == null) { if (mentionAccount != null) { toot_content.setText(String.format("@%s\n", mentionAccount)); toot_content.setSelection(toot_content.getText().length()); @@ -686,15 +686,14 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, toot_content.setText(String.format("\n\nvia @%s\n\n%s\n\n", tootMention, urlMention)); toot_space_left.setText(String.valueOf(countLength(social, toot_content, toot_cw_content))); } - }else{ + } else { toot_content.setText(quickmessagecontent); toot_space_left.setText(String.valueOf(countLength(social, toot_content, toot_cw_content))); toot_content.setSelection(toot_content.getText().length()); } - initialContent = displayWYSIWYG()?wysiwyg.getContentAsHTML():toot_content.getText().toString(); - + initialContent = displayWYSIWYG() ? wysiwyg.getContentAsHTML() : toot_content.getText().toString(); Helper.loadGiF(getApplicationContext(), account.getAvatar(), pp_actionBar); @@ -794,9 +793,9 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, toot_it.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - if( !displayWYSIWYG()) { + if (!displayWYSIWYG()) { sendToot(null, null); - }else{ + } else { sendToot(null, "text/html"); } } @@ -854,7 +853,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { intent.setType("*/*"); intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); - String[] mimetypes = {"image/*", "video/*" , "audio/mpeg", "audio/opus", "audio/flac", "audio/wav" , "audio/ogg"}; + String[] mimetypes = {"image/*", "video/*", "audio/mpeg", "audio/opus", "audio/flac", "audio/wav", "audio/ogg"}; intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes); startActivityForResult(intent, PICK_IMAGE); } else { @@ -921,11 +920,11 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } - public static TextWatcher initializeTextWatcher(Context context, UpdateAccountInfoAsyncTask.SOCIAL social, - MastalabAutoCompleteTextView toot_content, EditText toot_cw_content, TextView toot_space_left, - ImageView pp_actionBar, ProgressBar pp_progress, - OnRetrieveSearchInterface listener, OnRetrieveSearcAccountshInterface listenerAccount, OnRetrieveEmojiInterface listenerEmoji - ){ + public static TextWatcher initializeTextWatcher(Context context, UpdateAccountInfoAsyncTask.SOCIAL social, + MastalabAutoCompleteTextView toot_content, EditText toot_cw_content, TextView toot_space_left, + ImageView pp_actionBar, ProgressBar pp_progress, + OnRetrieveSearchInterface listener, OnRetrieveSearcAccountshInterface listenerAccount, OnRetrieveEmojiInterface listenerEmoji + ) { String pattern = "^(.|\\s)*(@([a-zA-Z0-9_]{2,}))$"; final Pattern sPattern = Pattern.compile(pattern); @@ -960,18 +959,17 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, String fedilabHugsTrigger = ":fedilab_hugs:"; String fedilabMorseTrigger = ":fedilab_morse:"; - if( s.toString().contains(fedilabHugsTrigger)){ + if (s.toString().contains(fedilabHugsTrigger)) { newContent[0] = s.toString().replaceAll(fedilabHugsTrigger, ""); int currentLength = countLength(social, toot_content, toot_cw_content); - int toFill = 500 - currentLength; - if(toFill <= 0) { + int toFill = 500 - currentLength; + if (toFill <= 0) { return; } - StringBuilder hugs = new StringBuilder(); - for(int i = 0; i < toFill; i++) { + for (int i = 0; i < toFill; i++) { hugs.append(new String(Character.toChars(0x1F917))); } @@ -989,23 +987,23 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } }; mainHandler.post(myRunnable); - }else if(s.toString().contains(fedilabMorseTrigger)){ + } else if (s.toString().contains(fedilabMorseTrigger)) { newContent[0] = s.toString().replaceAll(fedilabMorseTrigger, "").trim(); List mentions = new ArrayList<>(); String mentionPattern = "@[a-z0-9_]+(@[a-z0-9\\.\\-]+[a-z0-9]+)?"; final Pattern mPattern = Pattern.compile(mentionPattern, Pattern.CASE_INSENSITIVE); Matcher matcherMentions = mPattern.matcher(newContent[0]); - while ( matcherMentions.find()){ + while (matcherMentions.find()) { mentions.add(matcherMentions.group()); } - for(String mention: mentions){ + for (String mention : mentions) { newContent[0] = newContent[0].replace(mention, ""); } newContent[0] = Normalizer.normalize(newContent[0], Normalizer.Form.NFD); newContent[0] = newContent[0].replaceAll("[^\\p{ASCII}]", ""); HashMap ALPHA_TO_MORSE = new HashMap<>(); - for (int i = 0; i < ALPHA.length && i < MORSE.length; i++) { + for (int i = 0; i < ALPHA.length && i < MORSE.length; i++) { ALPHA_TO_MORSE.put(ALPHA[i], MORSE[i]); } StringBuilder builder = new StringBuilder(); @@ -1020,10 +1018,10 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, builder.append(" "); } newContent[0] = ""; - for(String mention: mentions){ + for (String mention : mentions) { newContent[0] += mention + " "; } - newContent[0] += builder.toString(); + newContent[0] += builder.toString(); Handler mainHandler = new Handler(Looper.getMainLooper()); @@ -1133,7 +1131,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, @Override public void onReceive(Context context, Intent intent) { String imgpath = intent.getStringExtra("imgpath"); - if( imgpath != null) { + if (imgpath != null) { prepareUpload(TootActivity.this, Uri.fromFile(new File(imgpath)), null, uploadReceiver); } } @@ -1156,18 +1154,18 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, }; - private void addNewMedia(JSONObject response, ArrayListsuccessfullyUploadedFiles){ + private void addNewMedia(JSONObject response, ArrayList successfullyUploadedFiles) { Attachment attachment; //response = new JSONObject(serverResponse.getBodyAsString()); - if( social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) + if (social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) attachment = API.parseAttachmentResponse(response); else attachment = GNUAPI.parseUploadedAttachmentResponse(response); boolean alreadyAdded = false; int index = 0; - for(Attachment attach_: attachments){ - if( attach_.getId().equals(attachment.getId())){ + for (Attachment attach_ : attachments) { + if (attach_.getId().equals(attachment.getId())) { alreadyAdded = true; break; } @@ -1176,7 +1174,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, File audioFile = new File(getCacheDir() + "/fedilab_recorded_audio.wav"); audioFile.delete(); - if( !alreadyAdded){ + if (!alreadyAdded) { toot_picture_container.setVisibility(View.VISIBLE); String url = attachment.getPreview_url(); if (url == null || url.trim().equals("")) @@ -1185,17 +1183,17 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, final ImageView imageView = new ImageView(getApplicationContext()); imageView.setId(Integer.parseInt(attachment.getId())); - if( social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA){ - if( successfullyUploadedFiles != null && successfullyUploadedFiles.size() > 0) { + if (social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + if (successfullyUploadedFiles != null && successfullyUploadedFiles.size() > 0) { Iterator it = filesMap.entrySet().iterator(); Uri fileName = null; while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); + Map.Entry pair = (Map.Entry) it.next(); fileName = (Uri) pair.getValue(); it.remove(); } - if (fileName != null ) { + if (fileName != null) { Glide.with(imageView.getContext()) .asBitmap() .load(fileName) @@ -1208,7 +1206,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } } - }else { + } else { String finalUrl = url; String uuid = attachment.getId(); Glide.with(imageView.getContext()) @@ -1219,16 +1217,16 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, @Override public void onResourceReady(@NonNull Bitmap resource, Transition transition) { imageView.setImageBitmap(resource); - if( displayWYSIWYG()) { + if (displayWYSIWYG()) { url_for_media = finalUrl; Iterator it = filesMap.entrySet().iterator(); String fileName = null; while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); + Map.Entry pair = (Map.Entry) it.next(); fileName = (String) pair.getKey(); it.remove(); } - if( fileName != null && fileName.toString().contains("fedilabins_")) { + if (fileName != null && fileName.toString().contains("fedilabins_")) { wysiwyg.insertImage(resource); } } @@ -1237,7 +1235,6 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } - LinearLayout.LayoutParams imParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); imParams.setMargins(20, 5, 20, 5); imParams.height = (int) Helper.convertDpToPixel(100, getApplicationContext()); @@ -1248,7 +1245,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, if (show_media_urls && !displayWYSIWYG()) { //Adds the shorter text_url of attachment at the end of the toot
 int selectionBefore = toot_content.getSelectionStart(); - toot_content.setText(String.format("%s\n\n%s",toot_content.getText().toString(), attachment.getText_url())); + toot_content.setText(String.format("%s\n\n%s", toot_content.getText().toString(), attachment.getText_url())); toot_space_left.setText(String.valueOf(countLength(social, toot_content, toot_cw_content))); //Moves the cursor toot_content.setSelection(selectionBefore); @@ -1281,12 +1278,12 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, toot_picture.setEnabled(true); toot_it.setEnabled(true); toot_sensitive.setVisibility(View.VISIBLE); - if( account.isSensitive()){ + if (account.isSensitive()) { toot_sensitive.setChecked(true); } picture_scrollview.setVisibility(View.VISIBLE); - }else { - if( attachments.size() > index && attachment.getDescription() != null) { + } else { + if (attachments.size() > index && attachment.getDescription() != null) { attachments.get(index).setDescription(attachment.getDescription()); } } @@ -1364,11 +1361,11 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } // Continue only if the File was successfully created if (photoFile != null) { - if(BuildConfig.DONATIONS) { + if (BuildConfig.DONATIONS) { photoFileUri = FileProvider.getUriForFile(this, "fr.gouv.etalab.mastodon.fileProvider", photoFile); - }else{ + } else { photoFileUri = FileProvider.getUriForFile(this, "app.fedilab.android.fileProvider", photoFile); @@ -1426,47 +1423,47 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, ContentResolver cr = getContentResolver(); String mime = cr.getType(data.getData()); if (mime != null && (mime.toLowerCase().contains("video") || mime.toLowerCase().contains("gif"))) { - prepareUpload(TootActivity.this, data.getData(), filename,uploadReceiver); + prepareUpload(TootActivity.this, data.getData(), filename, uploadReceiver); } else if (mime != null && mime.toLowerCase().contains("image")) { - if( photo_editor) { + if (photo_editor) { Intent intent = new Intent(TootActivity.this, PhotoEditorActivity.class); Bundle b = new Bundle(); intent.putExtra("imageUri", data.getData().toString()); intent.putExtras(b); startActivity(intent); - }else{ - prepareUpload(TootActivity.this, data.getData(), filename,uploadReceiver); + } else { + prepareUpload(TootActivity.this, data.getData(), filename, uploadReceiver); } - }else if(mime != null && mime.toLowerCase().contains("audio")){ - prepareUpload(TootActivity.this, data.getData(), filename,uploadReceiver); - }else { - Toasty.error(getApplicationContext(),getString(R.string.toot_select_image_error),Toast.LENGTH_LONG).show(); + } else if (mime != null && mime.toLowerCase().contains("audio")) { + prepareUpload(TootActivity.this, data.getData(), filename, uploadReceiver); + } else { + Toasty.error(getApplicationContext(), getString(R.string.toot_select_image_error), Toast.LENGTH_LONG).show(); } } - }else if (requestCode == SEND_VOICE_MESSAGE && resultCode == RESULT_OK) { + } else if (requestCode == SEND_VOICE_MESSAGE && resultCode == RESULT_OK) { Uri uri = Uri.fromFile(new File(getCacheDir() + "/fedilab_recorded_audio.wav")); - prepareUpload(TootActivity.this, uri, "fedilab_recorded_audio.wav",uploadReceiver); - }else if (requestCode == TAKE_PHOTO && resultCode == RESULT_OK) { - if( photo_editor) { + prepareUpload(TootActivity.this, uri, "fedilab_recorded_audio.wav", uploadReceiver); + } else if (requestCode == TAKE_PHOTO && resultCode == RESULT_OK) { + if (photo_editor) { Intent intent = new Intent(TootActivity.this, PhotoEditorActivity.class); Bundle b = new Bundle(); intent.putExtra("imageUri", photoFileUri.toString()); intent.putExtras(b); startActivity(intent); - }else { + } else { prepareUpload(TootActivity.this, photoFileUri, null, uploadReceiver); } - }else if (requestCode == wysiwyg.PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK && data != null && data.getData() != null) { + } else if (requestCode == wysiwyg.PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK && data != null && data.getData() != null) { String filename = Helper.getFileName(TootActivity.this, data.getData()); - prepareUpload(TootActivity.this, data.getData(), "fedilabins_"+filename, uploadReceiver); + prepareUpload(TootActivity.this, data.getData(), "fedilabins_" + filename, uploadReceiver); } } - private void prepareUpload(Activity activity, android.net.Uri uri,String filename, UploadServiceSingleBroadcastReceiver uploadReceiver){ - if( uploadReceiver == null){ + private void prepareUpload(Activity activity, android.net.Uri uri, String filename, UploadServiceSingleBroadcastReceiver uploadReceiver) { + if (uploadReceiver == null) { uploadReceiver = new UploadServiceSingleBroadcastReceiver(TootActivity.this); uploadReceiver.register(this); } @@ -1483,7 +1480,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, String filename; UpdateAccountInfoAsyncTask.SOCIAL social; - asyncPicture(Activity activity, UpdateAccountInfoAsyncTask.SOCIAL social, android.net.Uri uri, String filename, UploadServiceSingleBroadcastReceiver uploadReceiver){ + asyncPicture(Activity activity, UpdateAccountInfoAsyncTask.SOCIAL social, android.net.Uri uri, String filename, UploadServiceSingleBroadcastReceiver uploadReceiver) { this.activityWeakReference = new WeakReference<>(activity); this.uriFile = uri; this.uploadReceiver = uploadReceiver; @@ -1492,8 +1489,8 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } @Override - protected void onPreExecute(){ - if( uriFile == null) { + protected void onPreExecute() { + if (uriFile == null) { Toasty.error(activityWeakReference.get(), activityWeakReference.get().getString(R.string.toast_error), Toast.LENGTH_SHORT).show(); error = true; } @@ -1502,7 +1499,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, @Override protected Void doInBackground(Void... voids) { - if( error) { + if (error) { return null; } bs = Helper.compressImage(activityWeakReference.get(), uriFile, Helper.MediaType.MEDIA); @@ -1511,7 +1508,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, @Override protected void onPostExecute(Void result) { - if( !error) { + if (!error) { if (bs == null) return; ImageButton toot_picture; @@ -1524,7 +1521,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, toot_picture_container.setVisibility(View.VISIBLE); toot_picture.setEnabled(false); toot_it.setEnabled(false); - if( filename == null) { + if (filename == null) { filename = Helper.getFileName(this.activityWeakReference.get(), uriFile); } filesMap.put(filename, uriFile); @@ -1535,9 +1532,9 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } - static private void upload(Activity activity, UpdateAccountInfoAsyncTask.SOCIAL social, Uri inUri, String fname, UploadServiceSingleBroadcastReceiver uploadReceiver){ + static private void upload(Activity activity, UpdateAccountInfoAsyncTask.SOCIAL social, Uri inUri, String fname, UploadServiceSingleBroadcastReceiver uploadReceiver) { String uploadId = UUID.randomUUID().toString(); - if( uploadReceiver != null) { + if (uploadReceiver != null) { uploadReceiver.setUploadID(uploadId); } Uri uri; @@ -1546,14 +1543,14 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, String filename = inUri.toString().substring(inUri.toString().lastIndexOf("/")); int suffixPosition = filename.lastIndexOf("."); String suffix = ""; - if(suffixPosition > 0) suffix = filename.substring(suffixPosition); + if (suffixPosition > 0) suffix = filename.substring(suffixPosition); try { File file; tempInput = activity.getContentResolver().openInputStream(inUri); - if( fname.startsWith("fedilabins_")){ - file = File.createTempFile("fedilabins_randomTemp1", suffix, activity.getCacheDir()); - }else{ - file = File.createTempFile("randomTemp1", suffix, activity.getCacheDir()); + if (fname.startsWith("fedilabins_")) { + file = File.createTempFile("fedilabins_randomTemp1", suffix, activity.getCacheDir()); + } else { + file = File.createTempFile("randomTemp1", suffix, activity.getCacheDir()); } filesMap.put(file.getAbsolutePath(), inUri); @@ -1564,18 +1561,18 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, while ((read = tempInput.read(buff)) > 0) { tempOut.write(buff, 0, read); } - if(BuildConfig.DONATIONS) { - uri = FileProvider.getUriForFile( activity, + if (BuildConfig.DONATIONS) { + uri = FileProvider.getUriForFile(activity, "fr.gouv.etalab.mastodon.fileProvider", file); - }else{ - uri = FileProvider.getUriForFile( activity, + } else { + uri = FileProvider.getUriForFile(activity, "app.fedilab.android.fileProvider", file); } tempInput.close(); tempOut.close(); - } catch(IOException e) { + } catch (IOException e) { e.printStackTrace(); uri = inUri; } finally { @@ -1585,32 +1582,33 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, try { final String fileName = FileNameCleaner.cleanFileName(fname); - SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - String scheme = sharedpreferences.getString(Helper.SET_ONION_SCHEME+Helper.getLiveInstance( activity), "https"); + SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + String scheme = sharedpreferences.getString(Helper.SET_ONION_SCHEME + Helper.getLiveInstance(activity), "https"); String token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); int maxUploadRetryTimes = sharedpreferences.getInt(Helper.MAX_UPLOAD_IMG_RETRY_TIMES, 3); String url = null; - if(social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { - url = scheme + "://" + Helper.getLiveInstance( activity) + "/api/v1/media"; - }else { - url = scheme + "://" + Helper.getLiveInstance( activity) + "/api/media/upload.json"; + if (social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + url = scheme + "://" + Helper.getLiveInstance(activity) + "/api/v1/media"; + } else { + url = scheme + "://" + Helper.getLiveInstance(activity) + "/api/media/upload.json"; } UploadNotificationConfig uploadConfig = new UploadNotificationConfig(); uploadConfig .setClearOnActionForAllStatuses(true); uploadConfig.getProgress().message = activity.getString(R.string.uploading); uploadConfig.getCompleted().autoClear = true; - MultipartUploadRequest request = new MultipartUploadRequest( activity,uploadId, url); + MultipartUploadRequest request = new MultipartUploadRequest(activity, uploadId, url); if (token != null && !token.startsWith("Basic ")) request.addHeader("Authorization", "Bearer " + token); - else if( token != null && token.startsWith("Basic ")) + else if (token != null && token.startsWith("Basic ")) request.addHeader("Authorization", token); request.setNotificationConfig(uploadConfig); - if( social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { - request.addFileToUpload(uri.toString().replace("file://",""), "file"); - }else { - request.addFileToUpload(uri.toString().replace("file://",""), "media"); - }; + if (social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + request.addFileToUpload(uri.toString().replace("file://", ""), "file"); + } else { + request.addFileToUpload(uri.toString().replace("file://", ""), "media"); + } + ; request.addParameter("filename", fileName).setMaxRetries(maxUploadRetryTimes) .startUpload(); } catch (MalformedURLException e) { @@ -1622,10 +1620,10 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, @Override public void onPostAction(int statusCode, API.StatusAction statusAction, String userId, Error error) { - if( error != null){ - Toasty.error(getApplicationContext(),getString(R.string.toast_error),Toast.LENGTH_LONG).show(); - }else { - Toasty.success(getApplicationContext(),getString(R.string.toot_scheduled),Toast.LENGTH_LONG).show(); + if (error != null) { + Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); + } else { + Toasty.success(getApplicationContext(), getString(R.string.toot_scheduled), Toast.LENGTH_LONG).show(); resetForNextToot(); } } @@ -1640,7 +1638,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, public void onError(Context context, UploadInfo uploadInfo, ServerResponse serverResponse, Exception exception) { Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); - if( attachments.size() == 0 ) + if (attachments.size() == 0) toot_picture_container.setVisibility(View.GONE); toot_picture.setEnabled(true); toot_it.setEnabled(true); @@ -1664,10 +1662,10 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, @Override public void onRetrieveRelationship(Relationship relationship, Error error) { - if( error != null){ + if (error != null) { return; } - if( relationship != null && relationship.isBlocked_by() ){ + if (relationship != null && relationship.isBlocked_by()) { warning_message.setVisibility(View.VISIBLE); } @@ -1681,13 +1679,13 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, if (extras != null && extras.getString("imageUri") != null) { Uri imageUri = Uri.parse(extras.getString("imageUri")); picture_scrollview.setVisibility(View.VISIBLE); - if( imageUri == null) { - Toasty.error(getApplicationContext(),getString(R.string.toot_select_image_error),Toast.LENGTH_LONG).show(); + if (imageUri == null) { + Toasty.error(getApplicationContext(), getString(R.string.toot_select_image_error), Toast.LENGTH_LONG).show(); return; } - String filename = Helper.getFileName(TootActivity.this, imageUri); + String filename = Helper.getFileName(TootActivity.this, imageUri); - prepareUpload(TootActivity.this, imageUri, filename,uploadReceiver); + prepareUpload(TootActivity.this, imageUri, filename, uploadReceiver); } } @@ -1700,9 +1698,9 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } @@ -1718,7 +1716,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, input.setPadding(30, 30, 30, 30); alert.setView(input); String content = tootReply.getContent(); - if(tootReply.getReblog() != null) + if (tootReply.getReblog() != null) content = tootReply.getReblog().getContent(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) input.setText(Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY)); @@ -1732,7 +1730,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, }); alert.setNegativeButton(R.string.accounts, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { - new RetrieveAccountsForReplyAsyncTask(getApplicationContext(), tootReply.getReblog() != null?tootReply.getReblog():tootReply, TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new RetrieveAccountsForReplyAsyncTask(getApplicationContext(), tootReply.getReblog() != null ? tootReply.getReblog() : tootReply, TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); dialog.dismiss(); } }); @@ -1744,18 +1742,18 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, return false; case R.id.action_translate: final CountryPicker picker = CountryPicker.newInstance(getString(R.string.which_language)); // dialog title - if( theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { picker.setStyle(R.style.AppTheme, R.style.AlertDialog); - }else { + } else { picker.setStyle(R.style.AppThemeDark, R.style.AlertDialogDark); } - if( toot_content.getText().length() == 0 && toot_cw_content.getText().length() == 0) + if (toot_content.getText().length() == 0 && toot_cw_content.getText().length() == 0) return true; String dateString = sharedpreferences.getString(Helper.LAST_TRANSLATION_TIME, null); - if( dateString != null){ + if (dateString != null) { Date dateCompare = Helper.stringToDate(getApplicationContext(), dateString); Date date = new Date(); - if( date.before(dateCompare)) { + if (date.before(dateCompare)) { Toasty.info(getApplicationContext(), getString(R.string.please_wait), Toast.LENGTH_SHORT).show(); return true; } @@ -1767,10 +1765,10 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, AlertDialog.Builder transAlert = new AlertDialog.Builder(TootActivity.this, style); transAlert.setTitle(R.string.translate_toot); - popup_trans = getLayoutInflater().inflate( R.layout.popup_translate, new LinearLayout(getApplicationContext()), false ); + popup_trans = getLayoutInflater().inflate(R.layout.popup_translate, new LinearLayout(getApplicationContext()), false); transAlert.setView(popup_trans); SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putString(Helper.LAST_TRANSLATION_TIME, Helper.dateToString(new Date( System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(Helper.SECONDES_BETWEEN_TRANSLATE)))); + editor.putString(Helper.LAST_TRANSLATION_TIME, Helper.dateToString(new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(Helper.SECONDES_BETWEEN_TRANSLATE)))); editor.apply(); TextView yandex_translate = popup_trans.findViewById(R.id.yandex_translate); yandex_translate.setOnClickListener(new View.OnClickListener() { @@ -1784,75 +1782,75 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, myTransL.setYandexAPIKey(Helper.YANDEX_KEY); myTransL.setObfuscation(true); myTransL.setTimeout(60); - if( toot_cw_content.getText().toString().length() > 0) + if (toot_cw_content.getText().toString().length() > 0) myTransL.translate(toot_cw_content.getText().toString(), locale, new com.github.stom79.mytransl.client.Results() { @Override public void onSuccess(Translate translate) { try { - if( translate.getTranslatedContent() == null) + if (translate.getTranslatedContent() == null) return; - if( popup_trans != null ) { + if (popup_trans != null) { ProgressBar trans_progress_cw = popup_trans.findViewById(R.id.trans_progress_cw); ProgressBar trans_progress_toot = popup_trans.findViewById(R.id.trans_progress_toot); - if( trans_progress_cw != null) + if (trans_progress_cw != null) trans_progress_cw.setVisibility(View.GONE); LinearLayout trans_container = popup_trans.findViewById(R.id.trans_container); - if( trans_container != null ){ + if (trans_container != null) { TextView cw_trans = popup_trans.findViewById(R.id.cw_trans); - if( cw_trans != null) { + if (cw_trans != null) { cw_trans.setVisibility(View.VISIBLE); cw_trans.setText(translate.getTranslatedContent()); } - }else { - Toasty.error(getApplicationContext(),getString(R.string.toast_error_translate),Toast.LENGTH_LONG).show(); + } else { + Toasty.error(getApplicationContext(), getString(R.string.toast_error_translate), Toast.LENGTH_LONG).show(); } - if(trans_progress_cw != null && trans_progress_toot != null && trans_progress_cw.getVisibility() == View.GONE && trans_progress_toot.getVisibility() == View.GONE ) - if( dialogTrans.getButton(DialogInterface.BUTTON_NEGATIVE) != null) + if (trans_progress_cw != null && trans_progress_toot != null && trans_progress_cw.getVisibility() == View.GONE && trans_progress_toot.getVisibility() == View.GONE) + if (dialogTrans.getButton(DialogInterface.BUTTON_NEGATIVE) != null) dialogTrans.getButton(DialogInterface.BUTTON_NEGATIVE).setEnabled(true); } } catch (IllegalArgumentException e) { - Toasty.error(getApplicationContext(),getString(R.string.toast_error_translate),Toast.LENGTH_LONG).show(); + Toasty.error(getApplicationContext(), getString(R.string.toast_error_translate), Toast.LENGTH_LONG).show(); } } @Override public void onFail(HttpsConnectionException e) { - e.printStackTrace(); + e.printStackTrace(); } }); else { ProgressBar trans_progress_cw = popup_trans.findViewById(R.id.trans_progress_cw); trans_progress_cw.setVisibility(View.GONE); } - if( toot_content.getText().toString().length() > 0) + if (toot_content.getText().toString().length() > 0) myTransL.translate(toot_content.getText().toString(), locale, new com.github.stom79.mytransl.client.Results() { @Override public void onSuccess(Translate translate) { try { - if( translate.getTranslatedContent() == null) + if (translate.getTranslatedContent() == null) return; - if( popup_trans != null ) { + if (popup_trans != null) { ProgressBar trans_progress_cw = popup_trans.findViewById(R.id.trans_progress_cw); ProgressBar trans_progress_toot = popup_trans.findViewById(R.id.trans_progress_toot); - if( trans_progress_toot != null) + if (trans_progress_toot != null) trans_progress_toot.setVisibility(View.GONE); LinearLayout trans_container = popup_trans.findViewById(R.id.trans_container); - if( trans_container != null ){ + if (trans_container != null) { TextView toot_trans = popup_trans.findViewById(R.id.toot_trans); - if(toot_trans != null){ + if (toot_trans != null) { toot_trans.setVisibility(View.VISIBLE); toot_trans.setText(translate.getTranslatedContent()); } - }else { - Toasty.error(getApplicationContext(),getString(R.string.toast_error_translate),Toast.LENGTH_LONG).show(); + } else { + Toasty.error(getApplicationContext(), getString(R.string.toast_error_translate), Toast.LENGTH_LONG).show(); } - if(trans_progress_cw != null && trans_progress_toot != null && trans_progress_cw.getVisibility() == View.GONE && trans_progress_toot.getVisibility() == View.GONE ) - if( dialogTrans.getButton(DialogInterface.BUTTON_NEGATIVE) != null) + if (trans_progress_cw != null && trans_progress_toot != null && trans_progress_cw.getVisibility() == View.GONE && trans_progress_toot.getVisibility() == View.GONE) + if (dialogTrans.getButton(DialogInterface.BUTTON_NEGATIVE) != null) dialogTrans.getButton(DialogInterface.BUTTON_NEGATIVE).setEnabled(true); } } catch (IllegalArgumentException e) { - Toasty.error(getApplicationContext(),getString(R.string.toast_error_translate),Toast.LENGTH_LONG).show(); + Toasty.error(getApplicationContext(), getString(R.string.toast_error_translate), Toast.LENGTH_LONG).show(); } } @@ -1871,11 +1869,11 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, public void onClick(DialogInterface dialog, int whichButton) { TextView toot_trans = popup_trans.findViewById(R.id.toot_trans); TextView cw_trans = popup_trans.findViewById(R.id.cw_trans); - if( toot_trans != null) { + if (toot_trans != null) { toot_content.setText(toot_trans.getText().toString()); toot_content.setSelection(toot_content.getText().length()); } - if( cw_trans != null) + if (cw_trans != null) toot_cw_content.setText(cw_trans.getText().toString()); dialog.dismiss(); } @@ -1888,7 +1886,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, public void onShow(DialogInterface dialog) { Button negativeButton = ((AlertDialog) dialog) .getButton(AlertDialog.BUTTON_NEGATIVE); - if( negativeButton != null) + if (negativeButton != null) negativeButton.setEnabled(false); } }); @@ -1902,30 +1900,30 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, final AlertDialog.Builder builder = new AlertDialog.Builder(this, style); int paddingPixel = 15; float density = getResources().getDisplayMetrics().density; - int paddingDp = (int)(paddingPixel * density); + int paddingDp = (int) (paddingPixel * density); builder.setNeutralButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setTitle(R.string.insert_emoji); - if( emojis != null && emojis.size() > 0) { + if (emojis != null && emojis.size() > 0) { GridView gridView = new GridView(TootActivity.this); gridView.setAdapter(new CustomEmojiAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, emojis)); gridView.setNumColumns(5); gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { - toot_content.getText().insert(toot_content.getSelectionStart(), " :" + emojis.get(position).getShortcode()+": "); + toot_content.getText().insert(toot_content.getSelectionStart(), " :" + emojis.get(position).getShortcode() + ": "); alertDialogEmoji.dismiss(); } }); - gridView.setPadding(paddingDp,paddingDp,paddingDp,paddingDp); + gridView.setPadding(paddingDp, paddingDp, paddingDp, paddingDp); builder.setView(gridView); - }else{ + } else { TextView textView = new TextView(TootActivity.this); textView.setText(getString(R.string.no_emoji)); - textView.setPadding(paddingDp,paddingDp,paddingDp,paddingDp); + textView.setPadding(paddingDp, paddingDp, paddingDp, paddingDp); builder.setView(textView); } alertDialogEmoji = builder.show(); @@ -1941,29 +1939,32 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, builderSingle.setTitle(getString(R.string.select_accounts)); LayoutInflater inflater = getLayoutInflater(); - View dialogView = inflater.inflate(R.layout.popup_contact, new LinearLayout(getApplicationContext()), false); + View dialogView = inflater.inflate(R.layout.popup_contact, new LinearLayout(getApplicationContext()), false); loader = dialogView.findViewById(R.id.loader); EditText search_account = dialogView.findViewById(R.id.search_account); lv_accounts_search = dialogView.findViewById(R.id.lv_accounts_search); loader.setVisibility(View.VISIBLE); - new RetrieveSearchAccountsAsyncTask(TootActivity.this, "a", true,TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new RetrieveSearchAccountsAsyncTask(TootActivity.this, "a", true, TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); search_account.addTextChangedListener(new TextWatcher() { @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) {} + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } + @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (count > 0) { search_account.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_close, 0); - }else{ + } else { search_account.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_search, 0); } } + @Override public void afterTextChanged(Editable s) { - if( s != null && s.length() > 0){ - new RetrieveSearchAccountsAsyncTask(TootActivity.this, s.toString(), true,TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + if (s != null && s.length() > 0) { + new RetrieveSearchAccountsAsyncTask(TootActivity.this, s.toString(), true, TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } }); @@ -1974,7 +1975,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, if (event.getAction() == MotionEvent.ACTION_UP) { if (search_account.length() > 0 && event.getRawX() >= (search_account.getRight() - search_account.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) { search_account.setText(""); - new RetrieveSearchAccountsAsyncTask(TootActivity.this, "a", true,TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new RetrieveSearchAccountsAsyncTask(TootActivity.this, "a", true, TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } @@ -2021,9 +2022,9 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, startActivity(intentTags); return true; case R.id.action_restore: - try{ + try { final List drafts = new StatusStoredDAO(TootActivity.this, db).getAllDrafts(); - if( drafts == null || drafts.size() == 0){ + if (drafts == null || drafts.size() == 0) { Toasty.info(getApplicationContext(), getString(R.string.no_draft), Toast.LENGTH_LONG).show(); return true; } @@ -2032,7 +2033,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, final DraftsListAdapter draftsListAdapter = new DraftsListAdapter(drafts); final int[] ids = new int[drafts.size()]; int i = 0; - for(StoredStatus draft: drafts){ + for (StoredStatus draft : drafts) { ids[i] = draft.getId(); i++; } @@ -2075,14 +2076,14 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } }); builderSingle.show(); - }catch (Exception e){ + } catch (Exception e) { Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); } return true; case R.id.action_schedule: - if(toot_content.getText().toString().trim().length() == 0 ){ - Toasty.error(getApplicationContext(),getString(R.string.toot_error_no_content), Toast.LENGTH_LONG).show(); + if (toot_content.getText().toString().trim().length() == 0) { + Toasty.error(getApplicationContext(), getString(R.string.toot_error_no_content), Toast.LENGTH_LONG).show(); return true; } AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(TootActivity.this, style); @@ -2134,7 +2135,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { hour = timePicker.getHour(); minute = timePicker.getMinute(); - }else { + } else { //noinspection deprecation hour = timePicker.getCurrentHour(); //noinspection deprecation @@ -2147,9 +2148,9 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, minute); final long[] time = {calendar.getTimeInMillis()}; - if( (time[0] - new Date().getTime()) < 60000 ){ + if ((time[0] - new Date().getTime()) < 60000) { Toasty.warning(getApplicationContext(), getString(R.string.toot_scheduled_date), Toast.LENGTH_LONG).show(); - }else { + } else { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); String instanceVersion = sharedpreferences.getString(Helper.INSTANCE_VERSION + userId + instance, null); Version currentVersion = new Version(instanceVersion); @@ -2191,15 +2192,15 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } - private void sendToot(String timestamp, String content_type){ + private void sendToot(String timestamp, String content_type) { toot_it.setEnabled(false); - if(!displayWYSIWYG() && toot_content.getText().toString().trim().length() == 0 && attachments.size() == 0){ - Toasty.error(getApplicationContext(),getString(R.string.toot_error_no_content),Toast.LENGTH_LONG).show(); + if (!displayWYSIWYG() && toot_content.getText().toString().trim().length() == 0 && attachments.size() == 0) { + Toasty.error(getApplicationContext(), getString(R.string.toot_error_no_content), Toast.LENGTH_LONG).show(); toot_it.setEnabled(true); return; } - if(displayWYSIWYG() && wysiwyg.getContent().toString().trim().length() == 0 && attachments.size() == 0){ - Toasty.error(getApplicationContext(),getString(R.string.toot_error_no_content),Toast.LENGTH_LONG).show(); + if (displayWYSIWYG() && wysiwyg.getContent().toString().trim().length() == 0 && attachments.size() == 0) { + Toasty.error(getApplicationContext(), getString(R.string.toot_error_no_content), Toast.LENGTH_LONG).show(); toot_it.setEnabled(true); return; } @@ -2209,52 +2210,52 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, return; }*/ SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); - boolean split_toot = sharedpreferences.getBoolean(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS+userId+instance, false); - int split_toot_size = sharedpreferences.getInt(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS_SIZE+userId+instance, Helper.SPLIT_TOOT_SIZE); + boolean split_toot = sharedpreferences.getBoolean(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS + userId + instance, false); + int split_toot_size = sharedpreferences.getInt(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS_SIZE + userId + instance, Helper.SPLIT_TOOT_SIZE); - if(displayWYSIWYG()){ + if (displayWYSIWYG()) { split_toot = false; } String tootContent; - if( toot_cw_content.getText() != null && toot_cw_content.getText().toString().trim().length() > 0 ) + if (toot_cw_content.getText() != null && toot_cw_content.getText().toString().trim().length() > 0) split_toot_size -= toot_cw_content.getText().toString().trim().length(); - if( social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || !split_toot || (countLength(social, toot_content, toot_cw_content) < split_toot_size)){ - if( !displayWYSIWYG()) { + if (social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || !split_toot || (countLength(social, toot_content, toot_cw_content) < split_toot_size)) { + if (!displayWYSIWYG()) { tootContent = toot_content.getText().toString().trim(); - }else{ + } else { tootContent = wysiwyg.getContentAsHTML(); } - }else{ + } else { splitToot = Helper.splitToots(toot_content.getText().toString().trim(), split_toot_size); tootContent = splitToot.get(0); stepSpliToot = 1; } Status toot = new Status(); - if(content_type != null) + if (content_type != null) toot.setContentType(content_type); toot.setSensitive(isSensitive); - if( toot_cw_content.getText().toString().trim().length() > 0) + if (toot_cw_content.getText().toString().trim().length() > 0) toot.setSpoiler_text(toot_cw_content.getText().toString().trim()); toot.setVisibility(visibility); - if( tootReply != null) + if (tootReply != null) toot.setIn_reply_to_id(tootReply.getId()); toot.setContent(tootContent); - if( social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { + if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { if (poll != null) { toot.setPoll(poll); } else { toot.setMedia_attachments(attachments); } - }else{ + } else { if (poll != null) { toot.setPoll(poll); } toot.setMedia_attachments(attachments); } - if( timestamp == null) - if( scheduledstatus == null) - new PostStatusAsyncTask(getApplicationContext(), social, account, toot, TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + if (timestamp == null) + if (scheduledstatus == null) + new PostStatusAsyncTask(getApplicationContext(), social, account, toot, TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else { toot.setScheduled_at(Helper.dateToString(scheduledstatus.getScheduled_date())); scheduledstatus.setStatus(toot); @@ -2270,13 +2271,13 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } - private void serverSchedule(String time){ + private void serverSchedule(String time) { sendToot(time, null); isScheduled = true; resetForNextToot(); } - private void deviceSchedule(long time){ + private void deviceSchedule(long time) { //Store the toot as draft first storeToot(false, false); isScheduled = true; @@ -2286,12 +2287,12 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } - private void resetForNextToot(){ + private void resetForNextToot() { //Clear content toot_content.setText(""); toot_cw_content.setText(""); toot_space_left.setText("0"); - if( attachments != null) { + if (attachments != null) { for (Attachment attachment : attachments) { View namebar = findViewById(Integer.parseInt(attachment.getId())); if (namebar != null && namebar.getParent() != null) @@ -2305,33 +2306,33 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, isSensitive = false; toot_sensitive.setVisibility(View.GONE); currentToId = -1; - Toasty.info(getApplicationContext(),getString(R.string.toot_scheduled), Toast.LENGTH_LONG).show(); + Toasty.info(getApplicationContext(), getString(R.string.toot_scheduled), Toast.LENGTH_LONG).show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_toot, menu); - if( restored != -1 ){ + if (restored != -1) { MenuItem itemRestore = menu.findItem(R.id.action_restore); - if( itemRestore != null) + if (itemRestore != null) itemRestore.setVisible(false); MenuItem itemSchedule = menu.findItem(R.id.action_schedule); - if( restoredScheduled ) + if (restoredScheduled) itemSchedule.setVisible(false); } MenuItem itemViewReply = menu.findItem(R.id.action_view_reply); - if( tootReply == null){ - if( itemViewReply != null) + if (tootReply == null) { + if (itemViewReply != null) itemViewReply.setVisible(false); } - if( social != UpdateAccountInfoAsyncTask.SOCIAL.MASTODON && social != UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA ){ + if (social != UpdateAccountInfoAsyncTask.SOCIAL.MASTODON && social != UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { MenuItem itemPoll = menu.findItem(R.id.action_poll); - if( itemPoll != null) + if (itemPoll != null) itemPoll.setVisible(false); } SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if( theme == Helper.THEME_LIGHT) + if (theme == Helper.THEME_LIGHT) Helper.colorizeIconMenu(menu, R.color.black); changeColor(); String instanceVersion = sharedpreferences.getString(Helper.INSTANCE_VERSION + userId + instance, null); @@ -2339,27 +2340,27 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, Version minVersion = new Version("2.0"); MenuItem itemEmoji = menu.findItem(R.id.action_emoji); SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - final List emojis = new CustomEmojiDAO(getApplicationContext(), db).getAllEmojis(); + final List emojis = new CustomEmojiDAO(getApplicationContext(), db).getAllEmojis(); //Displays button only if custom emojis if (emojis != null && emojis.size() > 0 && (currentVersion.compareTo(minVersion) == 1 || currentVersion.equals(minVersion))) { itemEmoji.setVisible(true); - }else{ + } else { itemEmoji.setVisible(false); } - if( accountReply != null){ + if (accountReply != null) { MenuItem itemRestore = menu.findItem(R.id.action_restore); - if( itemRestore != null) + if (itemRestore != null) itemRestore.setVisible(false); MenuItem itemSchedule = menu.findItem(R.id.action_schedule); - if( itemSchedule != null) + if (itemSchedule != null) itemSchedule.setVisible(false); - MenuItem itemStore= menu.findItem(R.id.action_store); - if( itemStore != null) + MenuItem itemStore = menu.findItem(R.id.action_store); + if (itemStore != null) itemStore.setVisible(false); } - if( social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA){ + if (social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { MenuItem itemContacts = menu.findItem(R.id.action_contacts); - if( itemContacts != null) + if (itemContacts != null) itemContacts.setVisible(false); } return true; @@ -2369,7 +2370,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, @Override public void onDownloaded(String pathToFile, String url, Error error) { - if( error == null && pathToFile != null) { + if (error == null && pathToFile != null) { picture_scrollview.setVisibility(View.VISIBLE); Uri uri = Uri.fromFile(new File(pathToFile)); String filename = FileNameCleaner.cleanFileName(url); @@ -2390,21 +2391,21 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, ProgressBar progressBar = findViewById(R.id.upload_progress); TextView toolbar_text = findViewById(R.id.toolbar_text); RelativeLayout progress_bar_container = findViewById(R.id.progress_bar_container); - if( progress <= 100) { + if (progress <= 100) { progressBar.setScaleY(3f); progress_bar_container.setVisibility(View.VISIBLE); progressBar.setProgress(progress); toolbar_text.setText(String.format("%s%%", progress)); - }else{ + } else { progress_bar_container.setVisibility(View.GONE); } } - private void showAddDescription(final Attachment attachment){ + private void showAddDescription(final Attachment attachment) { AlertDialog.Builder builderInner = new AlertDialog.Builder(TootActivity.this, style); builderInner.setTitle(R.string.upload_form_description); - View popup_media_description = getLayoutInflater().inflate( R.layout.popup_media_description, new LinearLayout(getApplicationContext()), false ); + View popup_media_description = getLayoutInflater().inflate(R.layout.popup_media_description, new LinearLayout(getApplicationContext()), false); builderInner.setView(popup_media_description); //Text for report @@ -2421,7 +2422,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, media_picture.setImageBitmap(resource); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { media_picture.setImageAlpha(60); - }else { + } else { media_picture.setAlpha(60); } } @@ -2434,14 +2435,14 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } }); - if( attachment.getDescription() != null && !attachment.getDescription().equals("null")) { + if (attachment.getDescription() != null && !attachment.getDescription().equals("null")) { input.setText(attachment.getDescription()); input.setSelection(input.getText().length()); } builderInner.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { - new UpdateDescriptionAttachmentAsyncTask(getApplicationContext(), attachment.getId(), input.getText().toString(), account,TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new UpdateDescriptionAttachmentAsyncTask(getApplicationContext(), attachment.getId(), input.getText().toString(), account, TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); attachment.setDescription(input.getText().toString()); addBorder(); dialog.dismiss(); @@ -2454,29 +2455,30 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, /** * Removes a media + * * @param viewId String */ - private void showRemove(final int viewId){ + private void showRemove(final int viewId) { AlertDialog.Builder dialog = new AlertDialog.Builder(TootActivity.this, style); dialog.setMessage(R.string.toot_delete_media); dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog,int which) { + public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog,int which) { + public void onClick(DialogInterface dialog, int which) { View namebar = findViewById(viewId); - for(Attachment attachment: attachments){ - if( Integer.valueOf(attachment.getId()) == viewId){ + for (Attachment attachment : attachments) { + if (Integer.valueOf(attachment.getId()) == viewId) { attachments.remove(attachment); final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); boolean show_media_urls = sharedpreferences.getBoolean(Helper.SET_MEDIA_URLS, false); - if( show_media_urls) { + if (show_media_urls) { //Clears the text_url at the end of the toot
 for this attachment int selectionBefore = toot_content.getSelectionStart(); toot_content.setText(toot_content.getText().toString().replace(attachment.getText_url(), "")); @@ -2490,7 +2492,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } } dialog.dismiss(); - if( attachments.size() == 0 ) { + if (attachments.size() == 0) { toot_sensitive.setVisibility(View.GONE); isSensitive = false; toot_sensitive.setChecked(false); @@ -2504,7 +2506,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } - private void tootVisibilityDialog(){ + private void tootVisibilityDialog() { AlertDialog.Builder dialog = new AlertDialog.Builder(TootActivity.this, style); dialog.setTitle(R.string.toot_visibility_tilte); @@ -2519,7 +2521,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, dialog.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int position) { - switch (position){ + switch (position) { case 0: visibility = "public"; toot_visibility.setImageResource(R.drawable.ic_public_toot); @@ -2545,7 +2547,6 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } - @Override protected void onResume() { super.onResume(); @@ -2553,13 +2554,13 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, @Override - public void onPause(){ + public void onPause() { super.onPause(); final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); boolean storeToot = sharedpreferences.getBoolean(Helper.SET_AUTO_STORE, true); - if( storeToot && accountReply == null) { + if (storeToot && accountReply == null) { storeToot(true, false); - }else if( storeToot) { + } else if (storeToot) { storeToot(false, false); } } @@ -2568,12 +2569,12 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, public void onBackPressed() { final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); boolean storeToot = sharedpreferences.getBoolean(Helper.SET_AUTO_STORE, true); - if( !storeToot ){ - if (toot_content.getText().toString().trim().length() == 0 && (attachments == null || attachments.size() < 1) && toot_cw_content.getText().toString().trim().length() == 0){ + if (!storeToot) { + if (toot_content.getText().toString().trim().length() == 0 && (attachments == null || attachments.size() < 1) && toot_cw_content.getText().toString().trim().length() == 0) { finish(); - }else if (initialContent.trim().equals(toot_content.getText().toString().trim())){ + } else if (initialContent.trim().equals(toot_content.getText().toString().trim())) { finish(); - }else { + } else { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(TootActivity.this, style); dialogBuilder.setMessage(R.string.save_draft); dialogBuilder.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() { @@ -2599,7 +2600,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, alertDialog.setCancelable(false); alertDialog.show(); } - }else{ + } else { super.onBackPressed(); } @@ -2617,12 +2618,12 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, @Override public void onPostStatusAction(APIResponse apiResponse) { - if( apiResponse.getError() != null ){ + if (apiResponse.getError() != null) { toot_it.setEnabled(true); - if( apiResponse.getError().getError().contains("422")){ + if (apiResponse.getError().getError().contains("422")) { showAToast(getString(R.string.toast_error_char_limit)); return; - }else if( apiResponse.getError().getStatusCode() == -33){ + } else if (apiResponse.getError().getStatusCode() == -33) { storeToot(false, true); } else { showAToast(apiResponse.getError().getError()); @@ -2631,29 +2632,29 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); - boolean split_toot = sharedpreferences.getBoolean(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS+userId+instance, false); - int split_toot_size = sharedpreferences.getInt(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS_SIZE+userId+instance, Helper.SPLIT_TOOT_SIZE); + boolean split_toot = sharedpreferences.getBoolean(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS + userId + instance, false); + int split_toot_size = sharedpreferences.getInt(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS_SIZE + userId + instance, Helper.SPLIT_TOOT_SIZE); int cwSize = toot_cw_content.getText().toString().trim().length(); int size = toot_content.getText().toString().trim().length() + cwSize; - if( split_toot && splitToot != null && stepSpliToot < splitToot.size()){ + if (split_toot && splitToot != null && stepSpliToot < splitToot.size()) { String tootContent = splitToot.get(stepSpliToot); stepSpliToot += 1; Status toot = new Status(); toot.setSensitive(isSensitive); toot.setMedia_attachments(attachments); - if( toot_cw_content.getText().toString().trim().length() > 0) + if (toot_cw_content.getText().toString().trim().length() > 0) toot.setSpoiler_text(toot_cw_content.getText().toString().trim()); toot.setVisibility(visibility); - if( apiResponse.getStatuses() != null && apiResponse.getStatuses().size() > 0) + if (apiResponse.getStatuses() != null && apiResponse.getStatuses().size() > 0) toot.setIn_reply_to_id(apiResponse.getStatuses().get(0).getId()); toot.setContent(tootContent); new PostStatusAsyncTask(getApplicationContext(), social, account, toot, TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); return; } - if( apiResponse.getError() == null || apiResponse.getError().getStatusCode() != -33) { + if (apiResponse.getError() == null || apiResponse.getError().getStatusCode() != -33) { if (restored != -1) { SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); new StatusStoredDAO(getApplicationContext(), db).remove(restored); @@ -2666,7 +2667,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, toot_content.setText(""); toot_cw_content.setText(""); toot_space_left.setText("0"); - if( attachments != null) { + if (attachments != null) { for (Attachment attachment : attachments) { View namebar = findViewById(Integer.parseInt(attachment.getId())); if (namebar != null && namebar.getParent() != null) @@ -2680,28 +2681,28 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, isSensitive = false; toot_sensitive.setVisibility(View.GONE); currentToId = -1; - if(apiResponse.getError() == null) { + if (apiResponse.getError() == null) { if (scheduledstatus == null && !isScheduled) { boolean display_confirm = sharedpreferences.getBoolean(Helper.SET_DISPLAY_CONFIRM, true); - if( display_confirm){ + if (display_confirm) { Toasty.success(getApplicationContext(), getString(R.string.toot_sent), Toast.LENGTH_LONG).show(); } - }else + } else Toasty.success(getApplicationContext(), getString(R.string.toot_scheduled), Toast.LENGTH_LONG).show(); - }else { - if(apiResponse.getError().getStatusCode() == -33) + } else { + if (apiResponse.getError().getStatusCode() == -33) Toasty.info(getApplicationContext(), getString(R.string.toast_toot_saved_error), Toast.LENGTH_LONG).show(); } toot_it.setEnabled(true); //It's a reply, so the user will be redirect to its answer - if( tootReply != null){ + if (tootReply != null) { List statuses = apiResponse.getStatuses(); - if( statuses != null && statuses.size() > 0 ){ + if (statuses != null && statuses.size() > 0) { Status status = statuses.get(0); - if( status != null ) { + if (status != null) { Intent intent = new Intent(getApplicationContext(), ShowConversationActivity.class); Bundle b = new Bundle(); - if( idRedirect == null) + if (idRedirect == null) b.putParcelable("status", status); else { b.putParcelable("status", idRedirect); @@ -2711,7 +2712,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, finish(); } } - }else { + } else { Intent intent = new Intent(getApplicationContext(), MainActivity.class); intent.putExtra(Helper.INTENT_ACTION, Helper.HOME_TIMELINE_INTENT); startActivity(intent); @@ -2722,15 +2723,15 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, @Override public void onRetrieveSearchAccounts(APIResponse apiResponse) { - if( pp_progress != null && pp_actionBar != null) { + if (pp_progress != null && pp_actionBar != null) { pp_progress.setVisibility(View.GONE); pp_actionBar.setVisibility(View.VISIBLE); } - if( apiResponse.getError() != null) + if (apiResponse.getError() != null) return; final List accounts = apiResponse.getAccounts(); - if( accounts != null && accounts.size() > 0){ - if( !displayWYSIWYG()) { + if (accounts != null && accounts.size() > 0) { + if (!displayWYSIWYG()) { int currentCursorPosition = toot_content.getSelectionStart(); AccountsSearchAdapter accountsListAdapter = new AccountsSearchAdapter(TootActivity.this, accounts); toot_content.setThreshold(1); @@ -2774,11 +2775,11 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, }); } } - }else { //For Pleroma and its wysiwyg + } else { //For Pleroma and its wysiwyg RecyclerView suggestionsRV = findViewById(R.id.suggestions); suggestionsRV.setLayoutManager(new LinearLayoutManager(this)); List suggestions = new ArrayList<>(); - for(Account account: accounts){ + for (Account account : accounts) { Suggestion suggestion = new Suggestion(); suggestion.setContent(account.getAcct()); suggestion.setImageUrl(account.getAvatar()); @@ -2836,12 +2837,12 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, @Override public void onRetrieveContact(APIResponse apiResponse) { - if( apiResponse.getError() != null || apiResponse.getAccounts() == null) + if (apiResponse.getError() != null || apiResponse.getAccounts() == null) return; this.contacts = new ArrayList<>(); this.checkedValues = new ArrayList<>(); this.contacts.addAll(apiResponse.getAccounts()); - for(Account account: contacts) { + for (Account account : contacts) { this.checkedValues.add(toot_content.getText().toString().contains("@" + account.getAcct())); } this.loader.setVisibility(View.GONE); @@ -2861,56 +2862,56 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, @Override public void onRetrieveSearchEmoji(final List emojis) { - if( pp_progress != null && pp_actionBar != null) { + if (pp_progress != null && pp_actionBar != null) { pp_progress.setVisibility(View.GONE); pp_actionBar.setVisibility(View.VISIBLE); } if (emojis != null && emojis.size() > 0) { - if( !displayWYSIWYG()) { - int currentCursorPosition = toot_content.getSelectionStart(); - EmojisSearchAdapter emojisSearchAdapter = new EmojisSearchAdapter(TootActivity.this, emojis); - toot_content.setThreshold(1); - toot_content.setAdapter(emojisSearchAdapter); - final String oldContent = toot_content.getText().toString(); - String[] searchA = oldContent.substring(0, currentCursorPosition).split(":"); - if (searchA.length > 0) { - final String search = searchA[searchA.length - 1]; - toot_content.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView parent, View view, int position, long id) { - String shortcode = emojis.get(position).getShortcode(); - String deltaSearch = ""; - int searchLength = 15; - if (currentCursorPosition < 15) { //Less than 15 characters are written before the cursor position - searchLength = currentCursorPosition; - } - if (currentCursorPosition - searchLength > 0 && currentCursorPosition < oldContent.length()) - deltaSearch = oldContent.substring(currentCursorPosition - searchLength, currentCursorPosition); - else { - if (currentCursorPosition >= oldContent.length()) - deltaSearch = oldContent.substring(currentCursorPosition - searchLength, oldContent.length()); - } + if (!displayWYSIWYG()) { + int currentCursorPosition = toot_content.getSelectionStart(); + EmojisSearchAdapter emojisSearchAdapter = new EmojisSearchAdapter(TootActivity.this, emojis); + toot_content.setThreshold(1); + toot_content.setAdapter(emojisSearchAdapter); + final String oldContent = toot_content.getText().toString(); + String[] searchA = oldContent.substring(0, currentCursorPosition).split(":"); + if (searchA.length > 0) { + final String search = searchA[searchA.length - 1]; + toot_content.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + String shortcode = emojis.get(position).getShortcode(); + String deltaSearch = ""; + int searchLength = 15; + if (currentCursorPosition < 15) { //Less than 15 characters are written before the cursor position + searchLength = currentCursorPosition; + } + if (currentCursorPosition - searchLength > 0 && currentCursorPosition < oldContent.length()) + deltaSearch = oldContent.substring(currentCursorPosition - searchLength, currentCursorPosition); + else { + if (currentCursorPosition >= oldContent.length()) + deltaSearch = oldContent.substring(currentCursorPosition - searchLength, oldContent.length()); + } - if (!search.equals("")) - deltaSearch = deltaSearch.replace(":" + search, ""); - String newContent = oldContent.substring(0, currentCursorPosition - searchLength); - newContent += deltaSearch; - newContent += ":" + shortcode + ": "; - int newPosition = newContent.length(); - if (currentCursorPosition < oldContent.length()) - newContent += oldContent.substring(currentCursorPosition, oldContent.length()); - toot_content.setText(newContent); - toot_space_left.setText(String.valueOf(countLength(social, toot_content, toot_cw_content))); - toot_content.setSelection(newPosition); - EmojisSearchAdapter emojisSearchAdapter = new EmojisSearchAdapter(TootActivity.this, new ArrayList<>()); - toot_content.setThreshold(1); - toot_content.setAdapter(emojisSearchAdapter); + if (!search.equals("")) + deltaSearch = deltaSearch.replace(":" + search, ""); + String newContent = oldContent.substring(0, currentCursorPosition - searchLength); + newContent += deltaSearch; + newContent += ":" + shortcode + ": "; + int newPosition = newContent.length(); + if (currentCursorPosition < oldContent.length()) + newContent += oldContent.substring(currentCursorPosition, oldContent.length()); + toot_content.setText(newContent); + toot_space_left.setText(String.valueOf(countLength(social, toot_content, toot_cw_content))); + toot_content.setSelection(newPosition); + EmojisSearchAdapter emojisSearchAdapter = new EmojisSearchAdapter(TootActivity.this, new ArrayList<>()); + toot_content.setThreshold(1); + toot_content.setAdapter(emojisSearchAdapter); - } - }); - } - } else { + } + }); + } + } else { int currentCursorPosition = wysiwygEditText.getSelectionStart(); RecyclerView suggestionsRV = findViewById(R.id.suggestions); suggestionsRV.setLayoutManager(new LinearLayoutManager(this)); @@ -2970,21 +2971,21 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } - private void checkMastodon( Uri inUri){ + private void checkMastodon(Uri inUri) { try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), inUri); int imageWidth = -1; int imageHeight = -1; long size = -1; - if( bitmap != null) { + if (bitmap != null) { imageWidth = bitmap.getWidth(); imageHeight = bitmap.getHeight(); } - if( inUri != null) { + if (inUri != null) { File imageFile = new File(inUri.getPath()); size = imageFile.length(); } - if( imageWidth != -1 && imageHeight != -1 && size != -1){ + if (imageWidth != -1 && imageHeight != -1 && size != -1) { } } catch (IOException e) { @@ -2993,23 +2994,20 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } - - - @Override public void onRetrieveSearch(APIResponse apiResponse) { - if( pp_progress != null && pp_actionBar != null) { + if (pp_progress != null && pp_actionBar != null) { pp_progress.setVisibility(View.GONE); pp_actionBar.setVisibility(View.VISIBLE); } - if( apiResponse == null || apiResponse.getResults() == null) + if (apiResponse == null || apiResponse.getResults() == null) return; Results results = apiResponse.getResults(); final List tags = results.getHashtags(); - if( tags != null && tags.size() > 0){ - if( !displayWYSIWYG()) { + if (tags != null && tags.size() > 0) { + if (!displayWYSIWYG()) { int currentCursorPosition = toot_content.getSelectionStart(); TagsSearchAdapter tagsSearchAdapter = new TagsSearchAdapter(TootActivity.this, tags); toot_content.setThreshold(1); @@ -3056,7 +3054,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } }); - }else{ + } else { int currentCursorPosition = wysiwygEditText.getSelectionStart(); List suggestions = new ArrayList<>(); @@ -3115,27 +3113,27 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } } - private void restoreToot(long id){ + private void restoreToot(long id) { SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); StoredStatus draft = new StatusStoredDAO(TootActivity.this, db).getStatus(id); - if( draft == null) + if (draft == null) return; Status status = draft.getStatus(); //Retrieves attachments - if( removed ){ + if (removed) { new StatusStoredDAO(TootActivity.this, db).remove(draft.getId()); } restored = id; attachments = status.getMedia_attachments(); int childCount = toot_picture_container.getChildCount(); ArrayList toRemove = new ArrayList<>(); - if( childCount > 0 ){ - for(int i = 0 ; i < childCount ; i++){ - if( toot_picture_container.getChildAt(i) instanceof ImageView) - toRemove.add((ImageView)toot_picture_container.getChildAt(i)); + if (childCount > 0) { + for (int i = 0; i < childCount; i++) { + if (toot_picture_container.getChildAt(i) instanceof ImageView) + toRemove.add((ImageView) toot_picture_container.getChildAt(i)); } - if( toRemove.size() > 0){ - for(ImageView imageView: toRemove) + if (toRemove.size() > 0) { + for (ImageView imageView : toRemove) toot_picture_container.removeView(imageView); } toRemove.clear(); @@ -3147,29 +3145,29 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, content = matcher.replaceAll("$3@$2"); } - if( removed ) { + if (removed) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) content = Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY).toString(); else //noinspection deprecation content = Html.fromHtml(content).toString(); } - if( status.getPoll() != null) { + if (status.getPoll() != null) { poll = status.getPoll(); poll_action.setVisibility(View.VISIBLE); - if( social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { + if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { toot_picture.setVisibility(View.GONE); picture_scrollview.setVisibility(View.GONE); } } - if( attachments != null && attachments.size() > 0){ + if (attachments != null && attachments.size() > 0) { toot_picture_container.setVisibility(View.VISIBLE); picture_scrollview.setVisibility(View.VISIBLE); - int i = 0 ; - for(final Attachment attachment: attachments){ + int i = 0; + for (final Attachment attachment : attachments) { String url = attachment.getPreview_url(); - if( url == null || url.trim().equals("")) + if (url == null || url.trim().equals("")) url = attachment.getUrl(); final ImageView imageView = new ImageView(getApplicationContext()); imageView.setId(Integer.parseInt(attachment.getId())); @@ -3218,47 +3216,47 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } }); addBorder(); - if( attachments.size() < max_media_count) + if (attachments.size() < max_media_count) toot_picture.setEnabled(true); toot_sensitive.setVisibility(View.VISIBLE); i++; } - }else { + } else { toot_picture_container.setVisibility(View.GONE); } //Sensitive content toot_sensitive.setChecked(status.isSensitive()); - if( status.getSpoiler_text() != null && status.getSpoiler_text().length() > 0 ){ + if (status.getSpoiler_text() != null && status.getSpoiler_text().length() > 0) { toot_cw_content.setText(status.getSpoiler_text()); toot_cw_content.setVisibility(View.VISIBLE); - }else { + } else { toot_cw_content.setText(""); toot_cw_content.setVisibility(View.GONE); } - if( !displayWYSIWYG()) { + if (!displayWYSIWYG()) { toot_content.setText(content); - }else{ - if( content != null){ - content =content.replaceAll("]*><\\/p>",""); + } else { + if (content != null) { + content = content.replaceAll("]*><\\/p>", ""); } wysiwyg.render(content); try { - }catch (Exception e){ + } catch (Exception e) { e.printStackTrace(); Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_SHORT).show(); } } toot_space_left.setText(String.valueOf(countLength(social, toot_content, toot_cw_content))); - if( !displayWYSIWYG()) { + if (!displayWYSIWYG()) { toot_content.setSelection(toot_content.getText().length()); - }else{ - if( wysiwygEditText != null) { + } else { + if (wysiwygEditText != null) { wysiwygEditText.setSelection(wysiwygEditText.getText().length()); } } - switch (status.getVisibility()){ + switch (status.getVisibility()) { case "public": visibility = "public"; toot_visibility.setImageResource(R.drawable.ic_public_toot); @@ -3280,17 +3278,16 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, //The current id is set to the draft currentToId = draft.getId(); tootReply = draft.getStatusReply(); - if( tootReply != null) { + if (tootReply != null) { tootReply(); - }else { - if( title != null){ - if(social == UpdateAccountInfoAsyncTask.SOCIAL.GNU) + } else { + if (title != null) { + if (social == UpdateAccountInfoAsyncTask.SOCIAL.GNU) title.setText(getString(R.string.queet_title)); else title.setText(getString(R.string.toot_title)); - } - else { + } else { if (social == UpdateAccountInfoAsyncTask.SOCIAL.GNU) setTitle(R.string.queet_title); else @@ -3298,27 +3295,27 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } } invalidateOptionsMenu(); - initialContent = displayWYSIWYG()?wysiwyg.getContentAsHTML():toot_content.getText().toString(); - if( !displayWYSIWYG()) { + initialContent = displayWYSIWYG() ? wysiwyg.getContentAsHTML() : toot_content.getText().toString(); + if (!displayWYSIWYG()) { toot_space_left.setText(String.valueOf(countLength(social, toot_content, toot_cw_content))); - }else{ + } else { toot_space_left.setText(String.valueOf(countLength(wysiwyg, toot_cw_content))); } } - private void restoreServerSchedule(Status status){ + private void restoreServerSchedule(Status status) { attachments = status.getMedia_attachments(); int childCount = toot_picture_container.getChildCount(); ArrayList toRemove = new ArrayList<>(); - if( childCount > 0 ){ - for(int i = 0 ; i < childCount ; i++){ - if( toot_picture_container.getChildAt(i) instanceof ImageView) - toRemove.add((ImageView)toot_picture_container.getChildAt(i)); + if (childCount > 0) { + for (int i = 0; i < childCount; i++) { + if (toot_picture_container.getChildAt(i) instanceof ImageView) + toRemove.add((ImageView) toot_picture_container.getChildAt(i)); } - if( toRemove.size() > 0){ - for(ImageView imageView: toRemove) + if (toRemove.size() > 0) { + for (ImageView imageView : toRemove) toot_picture_container.removeView(imageView); } toRemove.clear(); @@ -3329,20 +3326,20 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, if (matcher.find()) { content = matcher.replaceAll("$3@$2"); } - if( removed ) { + if (removed) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) content = Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY).toString(); else //noinspection deprecation content = Html.fromHtml(content).toString(); } - if( attachments != null && attachments.size() > 0){ + if (attachments != null && attachments.size() > 0) { toot_picture_container.setVisibility(View.VISIBLE); picture_scrollview.setVisibility(View.VISIBLE); - int i = 0 ; - for(final Attachment attachment: attachments){ + int i = 0; + for (final Attachment attachment : attachments) { String url = attachment.getPreview_url(); - if( url == null || url.trim().equals("")) + if (url == null || url.trim().equals("")) url = attachment.getUrl(); final ImageView imageView = new ImageView(getApplicationContext()); imageView.setId(Integer.parseInt(attachment.getId())); @@ -3391,20 +3388,20 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } }); addBorder(); - if( attachments.size() < max_media_count) + if (attachments.size() < max_media_count) toot_picture.setEnabled(true); toot_sensitive.setVisibility(View.VISIBLE); i++; } - }else { + } else { toot_picture_container.setVisibility(View.GONE); } //Sensitive content toot_sensitive.setChecked(status.isSensitive()); - if( status.getSpoiler_text() != null && status.getSpoiler_text().length() > 0 ){ + if (status.getSpoiler_text() != null && status.getSpoiler_text().length() > 0) { toot_cw_content.setText(status.getSpoiler_text()); toot_cw_content.setVisibility(View.VISIBLE); - }else { + } else { toot_cw_content.setText(""); toot_cw_content.setVisibility(View.GONE); } @@ -3412,7 +3409,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, toot_content.setText(content); toot_space_left.setText(String.valueOf(countLength(social, toot_content, toot_cw_content))); toot_content.setSelection(toot_content.getText().length()); - switch (status.getVisibility()){ + switch (status.getVisibility()) { case "public": visibility = "public"; toot_visibility.setImageResource(R.drawable.ic_public_toot); @@ -3431,60 +3428,58 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, break; } - if( title != null) { + if (title != null) { if (social == UpdateAccountInfoAsyncTask.SOCIAL.GNU) title.setText(getString(R.string.queet_title)); else title.setText(getString(R.string.toot_title)); - } - else { + } else { if (social == UpdateAccountInfoAsyncTask.SOCIAL.GNU) setTitle(R.string.queet_title); else setTitle(R.string.toot_title); } invalidateOptionsMenu(); - initialContent = displayWYSIWYG()?wysiwyg.getContentAsHTML():toot_content.getText().toString(); + initialContent = displayWYSIWYG() ? wysiwyg.getContentAsHTML() : toot_content.getText().toString(); toot_space_left.setText(String.valueOf(countLength(social, toot_content, toot_cw_content))); } - private void tootReply(){ + private void tootReply() { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); - if( title != null) { + if (title != null) { if (social == UpdateAccountInfoAsyncTask.SOCIAL.GNU) title.setText(getString(R.string.queet_title_reply)); else title.setText(getString(R.string.toot_title_reply)); - } - else { + } else { if (social == UpdateAccountInfoAsyncTask.SOCIAL.GNU) setTitle(R.string.queet_title_reply); else setTitle(R.string.toot_title_reply); } String userIdReply; - if( accountReply == null) + if (accountReply == null) userIdReply = sharedpreferences.getString(Helper.PREF_KEY_ID, null); else userIdReply = accountReply.getId(); //If toot is not restored - if( restored == -1 ){ + if (restored == -1) { //Gets the default visibility, will be used if not set in settings - String defaultVisibility = account.isLocked()?"private":"public"; + String defaultVisibility = account.isLocked() ? "private" : "public"; String settingsVisibility = sharedpreferences.getString(Helper.SET_TOOT_VISIBILITY + "@" + account.getAcct() + "@" + account.getInstance(), defaultVisibility); int initialTootVisibility = 0; int ownerTootVisibility = 0; String temp_visibility = tootReply.getVisibility(); - if( quickmessagevisibility != null){ + if (quickmessagevisibility != null) { temp_visibility = quickmessagevisibility; } - switch (temp_visibility){ + switch (temp_visibility) { case "public": initialTootVisibility = 4; break; case "unlisted": - initialTootVisibility = 3; + initialTootVisibility = 3; break; case "private": visibility = "private"; @@ -3496,12 +3491,12 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, break; } if (settingsVisibility != null) { - switch (settingsVisibility){ + switch (settingsVisibility) { case "public": ownerTootVisibility = 4; break; case "unlisted": - ownerTootVisibility = 3; + ownerTootVisibility = 3; break; case "private": visibility = "private"; @@ -3514,12 +3509,12 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } } int tootVisibility; - if( ownerTootVisibility >= initialTootVisibility){ + if (ownerTootVisibility >= initialTootVisibility) { tootVisibility = initialTootVisibility; - }else { + } else { tootVisibility = ownerTootVisibility; } - switch (tootVisibility){ + switch (tootVisibility) { case 4: visibility = "public"; toot_visibility.setImageResource(R.drawable.ic_public_toot); @@ -3538,61 +3533,61 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, break; } - if( tootReply.getSpoiler_text() != null && tootReply.getSpoiler_text().length() > 0) { + if (tootReply.getSpoiler_text() != null && tootReply.getSpoiler_text().length() > 0) { toot_cw_content.setText(tootReply.getSpoiler_text()); toot_cw_content.setVisibility(View.VISIBLE); } - if( tootReply != null) { + if (tootReply != null) { manageMentions(getApplicationContext(), social, userIdReply, toot_content, toot_cw_content, toot_space_left, tootReply); } boolean forwardTags = sharedpreferences.getBoolean(Helper.SET_FORWARD_TAGS_IN_REPLY, false); - if( tootReply != null && forwardTags && tootReply.getTags() != null && tootReply.getTags().size() > 0){ + if (tootReply != null && forwardTags && tootReply.getTags() != null && tootReply.getTags().size() > 0) { int currentCursorPosition = toot_content.getSelectionStart(); - toot_content.setText(toot_content.getText() +"\n"); - for(Tag tag: tootReply.getTags()){ - toot_content.setText(toot_content.getText() +" #"+tag.getName()); + toot_content.setText(toot_content.getText() + "\n"); + for (Tag tag : tootReply.getTags()) { + toot_content.setText(toot_content.getText() + " #" + tag.getName()); } toot_content.setSelection(currentCursorPosition); toot_space_left.setText(String.valueOf(countLength(social, toot_content, toot_cw_content))); } } - initialContent = displayWYSIWYG()?wysiwyg.getContentAsHTML():toot_content.getText().toString(); + initialContent = displayWYSIWYG() ? wysiwyg.getContentAsHTML() : toot_content.getText().toString(); } - public static void manageMentions(Context context, UpdateAccountInfoAsyncTask.SOCIAL social, String userIdReply, MastalabAutoCompleteTextView contentView, EditText CWView, TextView counterView, Status tootReply){ + public static void manageMentions(Context context, UpdateAccountInfoAsyncTask.SOCIAL social, String userIdReply, MastalabAutoCompleteTextView contentView, EditText CWView, TextView counterView, Status tootReply) { //Retrieves mentioned accounts + OP and adds them at the beginin of the toot ArrayList mentionedAccountsAdded = new ArrayList<>(); final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int cursorReply = 0; - if( tootReply.getAccount() != null && tootReply.getAccount().getAcct() != null && !tootReply.getAccount().getId().equals(userIdReply)) { + if (tootReply.getAccount() != null && tootReply.getAccount().getAcct() != null && !tootReply.getAccount().getId().equals(userIdReply)) { contentView.setText(String.format("@%s", tootReply.getAccount().getAcct())); mentionedAccountsAdded.add(tootReply.getAccount().getAcct()); //Evaluate the cursor position => mention length + 1 char for carriage return cursorReply = contentView.getText().toString().length() + 1; } - if( tootReply.getMentions() != null ){ + if (tootReply.getMentions() != null) { //Put other accounts mentioned at the bottom boolean capitalize = sharedpreferences.getBoolean(Helper.SET_CAPITALIZE, true); - if( capitalize) + if (capitalize) contentView.setText(String.format("%s", (contentView.getText().toString() + "\n\n"))); else contentView.setText(String.format("%s", (contentView.getText().toString() + " "))); - for(Mention mention : tootReply.getMentions()){ - if( mention.getAcct() != null && !mention.getId().equals(userIdReply) && !mentionedAccountsAdded.contains(mention.getAcct())) { + for (Mention mention : tootReply.getMentions()) { + if (mention.getAcct() != null && !mention.getId().equals(userIdReply) && !mentionedAccountsAdded.contains(mention.getAcct())) { mentionedAccountsAdded.add(mention.getAcct()); String tootTemp = String.format("@%s ", mention.getAcct()); - contentView.setText(String.format("%s ", (contentView.getText().toString() + tootTemp.trim()))); + contentView.setText(String.format("%s ", (contentView.getText().toString() + tootTemp.trim()))); } } contentView.setText(contentView.getText().toString().trim()); - if (contentView.getText().toString().startsWith("@") ) { - if( capitalize ) + if (contentView.getText().toString().startsWith("@")) { + if (capitalize) contentView.append("\n"); else contentView.append(" "); @@ -3600,7 +3595,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, counterView.setText(String.valueOf(countLength(social, contentView, CWView))); contentView.requestFocus(); - if( capitalize) { + if (capitalize) { if (mentionedAccountsAdded.size() == 1) { contentView.setSelection(contentView.getText().length()); //Put cursor at the end } else { @@ -3609,13 +3604,13 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, else contentView.setSelection(contentView.getText().length()); //Put cursor at the end } - }else { + } else { contentView.setSelection(contentView.getText().length()); //Put cursor at the end } } } - private void displayPollPopup(){ + private void displayPollPopup() { AlertDialog.Builder alertPoll = new AlertDialog.Builder(TootActivity.this, style); alertPoll.setTitle(R.string.create_poll); View view = getLayoutInflater().inflate(R.layout.popup_poll, null); @@ -3631,11 +3626,11 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, int max_length = 25; pollCountItem = 2; remove.setVisibility(View.GONE); - if( MainActivity.poll_limits != null && MainActivity.poll_limits.containsKey("max_options")){ - max_entry = MainActivity.poll_limits.get("max_options")!=null?MainActivity.poll_limits.get("max_options"):4; + if (MainActivity.poll_limits != null && MainActivity.poll_limits.containsKey("max_options")) { + max_entry = MainActivity.poll_limits.get("max_options") != null ? MainActivity.poll_limits.get("max_options") : 4; } - if( MainActivity.poll_limits != null && MainActivity.poll_limits.containsKey("max_option_chars")){ - max_length = MainActivity.poll_limits.get("max_option_chars")!=null?MainActivity.poll_limits.get("max_option_chars"):25; + if (MainActivity.poll_limits != null && MainActivity.poll_limits.containsKey("max_option_chars")) { + max_length = MainActivity.poll_limits.get("max_option_chars") != null ? MainActivity.poll_limits.get("max_option_chars") : 25; } InputFilter[] fArray = new InputFilter[1]; fArray[0] = new InputFilter.LengthFilter(max_length); @@ -3647,18 +3642,18 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - if( pollCountItem < finalMax_entry){ + if (pollCountItem < finalMax_entry) { EditText poll_item = new EditText(TootActivity.this); InputFilter[] fArray = new InputFilter[1]; fArray[0] = new InputFilter.LengthFilter(finalMax_length); poll_item.setFilters(fArray); - poll_item.setHint(getString(R.string.poll_choice_s,(pollCountItem+1))); + poll_item.setHint(getString(R.string.poll_choice_s, (pollCountItem + 1))); poll_items_container.addView(poll_item); } pollCountItem++; - if( pollCountItem >= finalMax_entry){ + if (pollCountItem >= finalMax_entry) { add.setVisibility(View.GONE); - }else{ + } else { add.setVisibility(View.VISIBLE); } remove.setVisibility(View.VISIBLE); @@ -3667,14 +3662,14 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, remove.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - if( pollCountItem > 2){ + if (pollCountItem > 2) { int childCount = poll_items_container.getChildCount(); - poll_items_container.removeViewAt(childCount -1); + poll_items_container.removeViewAt(childCount - 1); } pollCountItem--; - if( pollCountItem <= 2){ + if (pollCountItem <= 2) { remove.setVisibility(View.GONE); - }else{ + } else { remove.setVisibility(View.VISIBLE); } add.setVisibility(View.VISIBLE); @@ -3690,22 +3685,22 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, poll_duration.setAdapter(pollduration); poll_duration.setSelection(4); poll_choice.setSelection(0); - if( poll != null && poll.getOptionsList() != null){ + if (poll != null && poll.getOptionsList() != null) { int i = 1; - for(PollOptions pollOptions: poll.getOptionsList()){ - if( i == 1){ - if( pollOptions.getTitle() != null) + for (PollOptions pollOptions : poll.getOptionsList()) { + if (i == 1) { + if (pollOptions.getTitle() != null) choice_1.setText(pollOptions.getTitle()); - }else if(i == 2){ - if( pollOptions.getTitle() != null) + } else if (i == 2) { + if (pollOptions.getTitle() != null) choice_2.setText(pollOptions.getTitle()); - }else{ + } else { EditText poll_item = new EditText(TootActivity.this); fArray = new InputFilter[1]; fArray[0] = new InputFilter.LengthFilter(finalMax_length); poll_item.setFilters(fArray); - poll_item.setHint(getString(R.string.poll_choice_s,(pollCountItem+1))); - if( pollOptions.getTitle() != null){ + poll_item.setHint(getString(R.string.poll_choice_s, (pollCountItem + 1))); + if (pollOptions.getTitle() != null) { poll_item.setText(pollOptions.getTitle()); } poll_items_container.addView(poll_item); @@ -3715,12 +3710,12 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } remove.setVisibility(View.VISIBLE); add.setVisibility(View.VISIBLE); - if(poll.getOptionsList().size() >= max_entry){ + if (poll.getOptionsList().size() >= max_entry) { add.setVisibility(View.GONE); - }else if( poll.getOptionsList().size() <= 2 ){ + } else if (poll.getOptionsList().size() <= 2) { remove.setVisibility(View.GONE); } - switch (poll.getExpires_in()){ + switch (poll.getExpires_in()) { case 300: poll_duration.setSelection(0); break; @@ -3743,7 +3738,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, poll_duration.setSelection(6); break; } - if( poll.isMultiple()) + if (poll.isMultiple()) poll_choice.setSelection(1); else poll_choice.setSelection(0); @@ -3752,11 +3747,11 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } alertPoll.setNeutralButton(R.string.delete, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { - if( poll != null) + if (poll != null) poll = null; poll_action.setVisibility(View.GONE); toot_picture.setVisibility(View.VISIBLE); - if( attachments != null && attachments.size() > 0) + if (attachments != null && attachments.size() > 0) picture_scrollview.setVisibility(View.VISIBLE); dialog.dismiss(); } @@ -3779,13 +3774,13 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, String choice1 = choice_1.getText().toString().trim(); String choice2 = choice_2.getText().toString().trim(); - if( choice1.isEmpty() && choice2.isEmpty()){ + if (choice1.isEmpty() && choice2.isEmpty()) { Toasty.error(getApplicationContext(), getString(R.string.poll_invalid_choices), Toast.LENGTH_SHORT).show(); - }else{ + } else { poll = new Poll(); poll.setMultiple(poll_choice_pos != 0); int expire = 0; - switch (poll_duration_pos){ + switch (poll_duration_pos) { case 0: expire = 300; break; @@ -3822,31 +3817,31 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, pollOptions.add(pollOption2); int childCount = poll_items_container.getChildCount(); - if( childCount > 2){ - for( int i = 2 ; i < childCount; i++){ + if (childCount > 2) { + for (int i = 2; i < childCount; i++) { PollOptions pollItem = new PollOptions(); - pollItem.setTitle(((EditText)poll_items_container.getChildAt(i)).getText().toString()); + pollItem.setTitle(((EditText) poll_items_container.getChildAt(i)).getText().toString()); pollOptions.add(pollItem); } } List options = new ArrayList<>(); boolean doubleTitle = false; - for(PollOptions po: pollOptions){ - if( !options.contains(po.getTitle().trim())){ + for (PollOptions po : pollOptions) { + if (!options.contains(po.getTitle().trim())) { options.add(po.getTitle().trim()); - }else{ + } else { doubleTitle = true; } } - if( !doubleTitle) { + if (!doubleTitle) { poll.setOptionsList(pollOptions); dialog.dismiss(); - }else { + } else { Toasty.error(getApplicationContext(), getString(R.string.poll_duplicated_entry), Toast.LENGTH_SHORT).show(); } } poll_action.setVisibility(View.VISIBLE); - if(social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { + if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { toot_picture.setVisibility(View.GONE); picture_scrollview.setVisibility(View.GONE); } @@ -3858,15 +3853,15 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, alertPollDiaslog.show(); } - private void storeToot(boolean message, boolean forced){ + private void storeToot(boolean message, boolean forced) { //Nothing to store here.... String currentContent; - if( displayWYSIWYG()){ + if (displayWYSIWYG()) { currentContent = wysiwyg.getContentAsHTML().trim(); - }else{ + } else { currentContent = toot_content.getText().toString().trim(); } - if( !forced) { + if (!forced) { if (currentContent.length() == 0 && (attachments == null || attachments.size() < 1) && toot_cw_content.getText().toString().trim().length() == 0) return; if (initialContent.trim().equals(currentContent)) @@ -3875,39 +3870,40 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, Status toot = new Status(); toot.setSensitive(isSensitive); toot.setMedia_attachments(attachments); - if( toot_cw_content.getText().toString().trim().length() > 0) + if (toot_cw_content.getText().toString().trim().length() > 0) toot.setSpoiler_text(toot_cw_content.getText().toString().trim()); toot.setVisibility(visibility); toot.setContent(currentContent); - if( poll != null) + if (poll != null) toot.setPoll(poll); - if( tootReply != null) + if (tootReply != null) toot.setIn_reply_to_id(tootReply.getId()); SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - try{ - if( currentToId == -1 ) { + try { + if (currentToId == -1) { currentToId = new StatusStoredDAO(TootActivity.this, db).insertStatus(toot, tootReply); - }else{ + } else { StoredStatus storedStatus = new StatusStoredDAO(TootActivity.this, db).getStatus(currentToId); - if( storedStatus != null ){ + if (storedStatus != null) { new StatusStoredDAO(TootActivity.this, db).updateStatus(currentToId, toot); - }else { //Might have been deleted, so it needs insertion + } else { //Might have been deleted, so it needs insertion new StatusStoredDAO(TootActivity.this, db).insertStatus(toot, tootReply); } } - if( message ) + if (message) Toasty.success(getApplicationContext(), getString(R.string.toast_toot_saved), Toast.LENGTH_LONG).show(); - }catch (Exception e){ - if( message) + } catch (Exception e) { + if (message) Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); } } - private void changeColor(){ + + private void changeColor() { final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if( theme == Helper.THEME_DARK || theme == Helper.THEME_BLACK) { + if (theme == Helper.THEME_DARK || theme == Helper.THEME_BLACK) { changeDrawableColor(TootActivity.this, R.drawable.ic_public_toot, R.color.dark_text); changeDrawableColor(TootActivity.this, R.drawable.ic_lock_open_toot, R.color.dark_text); changeDrawableColor(TootActivity.this, R.drawable.ic_lock_outline_toot, R.color.dark_text); @@ -3924,7 +3920,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, changeDrawableColor(TootActivity.this, findViewById(R.id.toot_emoji), R.color.dark_text); Helper.changeButtonTextColor(TootActivity.this, findViewById(R.id.toot_cw), R.color.dark_text); - }else { + } else { changeDrawableColor(TootActivity.this, R.drawable.ic_public_toot, R.color.white); changeDrawableColor(TootActivity.this, R.drawable.ic_lock_open_toot, R.color.white); changeDrawableColor(TootActivity.this, R.drawable.ic_lock_outline_toot, R.color.white); @@ -3949,7 +3945,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, public void onRetrieveAccountsReply(ArrayList accounts) { final boolean[] checkedValues = new boolean[accounts.size()]; int i = 0; - for(Account account: accounts) { + for (Account account : accounts) { checkedValues[i] = toot_content.getText().toString().contains("@" + account.getAcct()); i++; } @@ -3966,12 +3962,12 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, builderSingle.show(); } - public void changeAccountReply(boolean isChecked, String acct){ + public void changeAccountReply(boolean isChecked, String acct) { if (isChecked) { - if( !toot_content.getText().toString().contains(acct)) - toot_content.setText(String.format("%s %s",acct, toot_content.getText())); + if (!toot_content.getText().toString().contains(acct)) + toot_content.setText(String.format("%s %s", acct, toot_content.getText())); } else { - toot_content.setText(toot_content.getText().toString().replaceAll("\\s*" +acct, "")); + toot_content.setText(toot_content.getText().toString().replaceAll("\\s*" + acct, "")); } } @@ -3987,21 +3983,21 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, active = false; } - private void addBorder(){ + private void addBorder() { for (int i = 0; i < toot_picture_container.getChildCount(); i++) { View v = toot_picture_container.getChildAt(i); if (v instanceof ImageView) { - for(Attachment attachment: attachments){ - if(attachment.getType().toLowerCase().equals("image")) - if( v.getTag().toString().trim().equals(attachment.getId().trim())){ - int borderSize = (int) Helper.convertDpToPixel(1, TootActivity.this); - int borderSizeTop = (int) Helper.convertDpToPixel(6, TootActivity.this); - v.setPadding(borderSize,borderSizeTop,borderSize,borderSizeTop); - if( attachment.getDescription() == null ||attachment.getDescription().trim().equals("null") || attachment.getDescription().trim().equals("")) { - v.setBackgroundColor( ContextCompat.getColor(TootActivity.this, R.color.red_1)); - }else - v.setBackgroundColor(ContextCompat.getColor(TootActivity.this, R.color.green_1)); - } + for (Attachment attachment : attachments) { + if (attachment.getType().toLowerCase().equals("image")) + if (v.getTag().toString().trim().equals(attachment.getId().trim())) { + int borderSize = (int) Helper.convertDpToPixel(1, TootActivity.this); + int borderSizeTop = (int) Helper.convertDpToPixel(6, TootActivity.this); + v.setPadding(borderSize, borderSizeTop, borderSize, borderSizeTop); + if (attachment.getDescription() == null || attachment.getDescription().trim().equals("null") || attachment.getDescription().trim().equals("")) { + v.setBackgroundColor(ContextCompat.getColor(TootActivity.this, R.color.red_1)); + } else + v.setBackgroundColor(ContextCompat.getColor(TootActivity.this, R.color.green_1)); + } } } @@ -4010,19 +4006,19 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } - public static int countLength(UpdateAccountInfoAsyncTask.SOCIAL social, MastalabAutoCompleteTextView toot_content, EditText toot_cw_content){ - if( toot_content == null || toot_cw_content == null) { + public static int countLength(UpdateAccountInfoAsyncTask.SOCIAL social, MastalabAutoCompleteTextView toot_content, EditText toot_cw_content) { + if (toot_content == null || toot_cw_content == null) { return -1; } String content = toot_content.getText().toString(); String cwContent = toot_cw_content.getText().toString(); String contentCount = content; - if( social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON ){ - contentCount = contentCount.replaceAll("(^|[^/\\w])@(([a-z0-9_]+)@[a-z0-9\\.\\-]+[a-z0-9]+)","$1@$3"); + if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { + contentCount = contentCount.replaceAll("(^|[^/\\w])@(([a-z0-9_]+)@[a-z0-9\\.\\-]+[a-z0-9]+)", "$1@$3"); Matcher matcherALink = Patterns.WEB_URL.matcher(contentCount); - while (matcherALink.find()){ + while (matcherALink.find()) { final String url = matcherALink.group(1); - contentCount = contentCount.replace(url,"abcdefghijklmnopkrstuvw"); + contentCount = contentCount.replace(url, "abcdefghijklmnopkrstuvw"); } } @@ -4031,8 +4027,8 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, return cwLength + contentLength; } - int countLength(Editor wysiwyg, EditText toot_cw_content){ - if( wysiwyg == null || toot_cw_content == null) { + int countLength(Editor wysiwyg, EditText toot_cw_content) { + if (wysiwyg == null || toot_cw_content == null) { return -1; } String content = wysiwyg.getContentAsHTML(); @@ -4042,7 +4038,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, return cwLength + contentLength; } - private void recordAudio(){ + private void recordAudio() { String filePath = getCacheDir() + "/fedilab_recorded_audio.wav"; int color = getResources().getColor(R.color.mastodonC1); AndroidAudioRecorder.with(this) @@ -4062,15 +4058,15 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } - private boolean displayWYSIWYG(){ - if( social != UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA){ + private boolean displayWYSIWYG() { + if (social != UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { return false; } SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); return sharedpreferences.getBoolean(Helper.SET_WYSIWYG, false); } - private void renderEditor(){ + private void renderEditor() { findViewById(R.id.action_h1).setOnClickListener(new View.OnClickListener() { diff --git a/app/src/main/java/app/fedilab/android/activities/TootInfoActivity.java b/app/src/main/java/app/fedilab/android/activities/TootInfoActivity.java index 0f9b76282..d32fed93b 100644 --- a/app/src/main/java/app/fedilab/android/activities/TootInfoActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/TootInfoActivity.java @@ -17,12 +17,15 @@ package app.fedilab.android.activities; import android.content.SharedPreferences; import android.os.Bundle; + import com.google.android.material.tabs.TabLayout; + import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentStatePagerAdapter; import androidx.viewpager.widget.PagerAdapter; import androidx.viewpager.widget.ViewPager; + import android.view.ViewGroup; import android.view.Window; import android.widget.Toast; @@ -55,7 +58,7 @@ public class TootInfoActivity extends BaseActivity { requestWindowFeature(Window.FEATURE_NO_TITLE); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme); break; @@ -71,24 +74,24 @@ public class TootInfoActivity extends BaseActivity { setContentView(R.layout.activity_toot_info); getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT); Bundle b = getIntent().getExtras(); - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().hide(); int toot_reblogs_count = 0; int toot_favorites_count = 0; - if( b != null){ + if (b != null) { toot_id = b.getString("toot_id", null); toot_reblogs_count = b.getInt("toot_reblogs_count", 0); toot_favorites_count = b.getInt("toot_favorites_count", 0); } - if( toot_id == null){ + if (toot_id == null) { Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_SHORT).show(); finish(); } userID = sharedpreferences.getString(Helper.PREF_KEY_ID, null); tabLayout = findViewById(R.id.tabLayout); mPager = findViewById(R.id.viewpager); - tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.reblog) + " ("+toot_reblogs_count+")")); - tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.favourite) + " ("+toot_favorites_count+")")); + tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.reblog) + " (" + toot_reblogs_count + ")")); + tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.favourite) + " (" + toot_favorites_count + ")")); tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @@ -96,6 +99,7 @@ public class TootInfoActivity extends BaseActivity { public void onTabSelected(TabLayout.Tab tab) { mPager.setCurrentItem(tab.getPosition()); } + @Override public void onTabUnselected(TabLayout.Tab tab) { @@ -118,7 +122,7 @@ public class TootInfoActivity extends BaseActivity { @Override public void onPageSelected(int position) { TabLayout.Tab tab = tabLayout.getTabAt(position); - if( tab != null) + if (tab != null) tab.select(); } @@ -130,12 +134,12 @@ public class TootInfoActivity extends BaseActivity { } - public void updateBoostCount(int count){ - Objects.requireNonNull(tabLayout.getTabAt(0)).setText(getString(R.string.reblog) + " ("+count+")"); + public void updateBoostCount(int count) { + Objects.requireNonNull(tabLayout.getTabAt(0)).setText(getString(R.string.reblog) + " (" + count + ")"); } - public void updateFavCount(int count){ - Objects.requireNonNull(tabLayout.getTabAt(1)).setText(getString(R.string.favourite) + " ("+count+")"); + public void updateFavCount(int count) { + Objects.requireNonNull(tabLayout.getTabAt(1)).setText(getString(R.string.favourite) + " (" + count + ")"); } private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter { @@ -147,7 +151,7 @@ public class TootInfoActivity extends BaseActivity { @Override public Fragment getItem(int position) { Bundle bundle = new Bundle(); - switch (position){ + switch (position) { case 0: DisplayAccountsFragment displayAccountsFragment = new DisplayAccountsFragment(); bundle.putSerializable("type", RetrieveAccountsAsyncTask.Type.REBLOGGED); diff --git a/app/src/main/java/app/fedilab/android/activities/WebviewActivity.java b/app/src/main/java/app/fedilab/android/activities/WebviewActivity.java index 551932969..fe9ec7ca2 100644 --- a/app/src/main/java/app/fedilab/android/activities/WebviewActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/WebviewActivity.java @@ -29,9 +29,11 @@ import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; + import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.appcompat.app.AlertDialog; + import android.view.Menu; import android.view.MenuItem; import android.view.View; @@ -80,7 +82,7 @@ public class WebviewActivity extends BaseActivity { super.onCreate(savedInstanceState); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme); break; @@ -97,14 +99,14 @@ public class WebviewActivity extends BaseActivity { setContentView(R.layout.activity_webview); Bundle b = getIntent().getExtras(); - if(b != null) { + if (b != null) { url = b.getString("url", null); peertubeLinkToFetch = b.getString("peertubeLinkToFetch", null); - peertubeLink = b.getBoolean("peertubeLink", false); + peertubeLink = b.getBoolean("peertubeLink", false); } - if( url == null) + if (url == null) finish(); - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); webView = Helper.initializeWebview(WebviewActivity.this, R.id.webview); @@ -115,13 +117,13 @@ public class WebviewActivity extends BaseActivity { boolean proxyEnabled = sharedpreferences.getBoolean(Helper.SET_PROXY_ENABLED, false); - if( proxyEnabled ){ + if (proxyEnabled) { String host = sharedpreferences.getString(Helper.SET_PROXY_HOST, "127.0.0.1"); int port = sharedpreferences.getInt(Helper.SET_PROXY_PORT, 8118); - ProxyHelper.setProxy(getApplicationContext(), webView,host, port,WebviewActivity.class.getName()); + ProxyHelper.setProxy(getApplicationContext(), webView, host, port, WebviewActivity.class.getName()); } - MastalabWebChromeClient mastalabWebChromeClient = new MastalabWebChromeClient(WebviewActivity.this, webView, webview_container, videoLayout); + MastalabWebChromeClient mastalabWebChromeClient = new MastalabWebChromeClient(WebviewActivity.this, webView, webview_container, videoLayout); mastalabWebChromeClient.setOnToggledFullscreen(new MastalabWebChromeClient.ToggledFullscreenCallback() { @Override public void toggledFullscreen(boolean fullscreen) { @@ -150,26 +152,26 @@ public class WebviewActivity extends BaseActivity { @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { - if(Build.VERSION.SDK_INT >= 23 ){ + if (Build.VERSION.SDK_INT >= 23) { if (ContextCompat.checkSelfPermission(WebviewActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(WebviewActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(WebviewActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, Helper.EXTERNAL_STORAGE_REQUEST_CODE); } else { Helper.manageDownloads(WebviewActivity.this, url); } - }else{ + } else { Helper.manageDownloads(WebviewActivity.this, url); } } }); - if( !url.startsWith("http://") && !url.startsWith("https://")) + if (!url.startsWith("http://") && !url.startsWith("https://")) url = "http://" + url; - if( trackingDomains == null){ + if (trackingDomains == null) { AsyncTask.execute(new Runnable() { @Override public void run() { SQLiteDatabase db = Sqlite.getInstance(WebviewActivity.this, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); trackingDomains = new DomainBlockDAO(WebviewActivity.this, db).getAll(); - if( trackingDomains == null) + if (trackingDomains == null) trackingDomains = new ArrayList<>(); // Get a handler that can be used to post to the main thread Handler mainHandler = new Handler(getMainLooper()); @@ -183,13 +185,13 @@ public class WebviewActivity extends BaseActivity { } }); - }else + } else webView.loadUrl(url); } public void setCount(Context context, String count) { - if( defaultMenu != null && !peertubeLink) { + if (defaultMenu != null && !peertubeLink) { MenuItem menuItem = defaultMenu.findItem(R.id.action_block); LayerDrawable icon = (LayerDrawable) menuItem.getIcon(); @@ -211,7 +213,7 @@ public class WebviewActivity extends BaseActivity { @Override public boolean onPrepareOptionsMenu(Menu menu) { - if(!peertubeLink) + if (!peertubeLink) setCount(this, "0"); defaultMenu = menu; return super.onPrepareOptionsMenu(menu); @@ -221,17 +223,18 @@ public class WebviewActivity extends BaseActivity { public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_webview, menu); defaultMenu = menu; - if( peertubeLink ){ + if (peertubeLink) { menu.findItem(R.id.action_go).setVisible(false); menu.findItem(R.id.action_block).setVisible(false); menu.findItem(R.id.action_comment).setVisible(true); } SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if( theme == Helper.THEME_LIGHT) + if (theme == Helper.THEME_LIGHT) Helper.colorizeIconMenu(menu, R.color.black); return true; } + @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { @@ -249,9 +252,9 @@ public class WebviewActivity extends BaseActivity { int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } AlertDialog.Builder builder = new AlertDialog.Builder(WebviewActivity.this, style); @@ -279,8 +282,8 @@ public class WebviewActivity extends BaseActivity { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); try { startActivity(browserIntent); - }catch (Exception e){ - Toasty.error(getApplicationContext(),getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + } catch (Exception e) { + Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); } return true; case R.id.action_comment: @@ -293,7 +296,7 @@ public class WebviewActivity extends BaseActivity { @Override protected Void doInBackground(Void... voids) { - if(url != null) { + if (url != null) { APIResponse search = new API(contextReference.get()).search(peertubeLinkToFetch); if (search != null && search.getResults() != null) { remoteStatuses = search.getResults().getStatuses(); @@ -306,46 +309,46 @@ public class WebviewActivity extends BaseActivity { protected void onPostExecute(Void result) { Intent intent = new Intent(contextReference.get(), TootActivity.class); Bundle b = new Bundle(); - if( remoteStatuses == null || remoteStatuses.size() == 0){ - Toasty.error(contextReference.get(),getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + if (remoteStatuses == null || remoteStatuses.size() == 0) { + Toasty.error(contextReference.get(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); return; } - if( remoteStatuses.get(0).getReblog() != null ) { + if (remoteStatuses.get(0).getReblog() != null) { b.putParcelable("tootReply", remoteStatuses.get(0).getReblog()); - }else { + } else { b.putParcelable("tootReply", remoteStatuses.get(0)); } intent.putExtras(b); //Put your id to your next Intent contextReference.get().startActivity(intent); } - }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR ); + }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); return true; default: return super.onOptionsItemSelected(item); } } - public void setUrl(String newUrl){ + public void setUrl(String newUrl) { this.url = newUrl; } @Override - public void onPause(){ + public void onPause() { super.onPause(); - if( webView != null) + if (webView != null) webView.onPause(); } @Override - public void onResume(){ + public void onResume() { super.onResume(); - if( webView != null) + if (webView != null) webView.onResume(); } @Override public void onBackPressed() { - if (webView.canGoBack()){ + if (webView.canGoBack()) { webView.goBack(); } else { super.onBackPressed(); @@ -353,9 +356,9 @@ public class WebviewActivity extends BaseActivity { } @Override - public void onDestroy(){ + public void onDestroy() { super.onDestroy(); - if( webView != null) + if (webView != null) webView.destroy(); } } diff --git a/app/src/main/java/app/fedilab/android/activities/WebviewConnectActivity.java b/app/src/main/java/app/fedilab/android/activities/WebviewConnectActivity.java index b2d1c9cda..962a3a60b 100644 --- a/app/src/main/java/app/fedilab/android/activities/WebviewConnectActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/WebviewConnectActivity.java @@ -23,9 +23,11 @@ import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; + import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.Toolbar; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -69,7 +71,7 @@ public class WebviewConnectActivity extends BaseActivity { super.onCreate(savedInstanceState); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme); break; @@ -85,19 +87,19 @@ public class WebviewConnectActivity extends BaseActivity { setContentView(R.layout.activity_webview_connect); Bundle b = getIntent().getExtras(); - if(b != null) { + if (b != null) { instance = b.getString("instance"); social = (UpdateAccountInfoAsyncTask.SOCIAL) b.getSerializable("social"); } - if( instance == null) + if (instance == null) finish(); clientId = sharedpreferences.getString(Helper.CLIENT_ID, null); clientSecret = sharedpreferences.getString(Helper.CLIENT_SECRET, null); ActionBar actionBar = getSupportActionBar(); - if( actionBar != null ) { + if (actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); assert inflater != null; - View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); + View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false); actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close); @@ -109,7 +111,7 @@ public class WebviewConnectActivity extends BaseActivity { } }); toolbar_title.setText(R.string.add_account); - if (theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { Toolbar toolbar = actionBar.getCustomView().findViewById(R.id.toolbar); Helper.colorizeToolbar(toolbar, R.color.black, WebviewConnectActivity.this); } @@ -139,20 +141,20 @@ public class WebviewConnectActivity extends BaseActivity { }); boolean proxyEnabled = sharedpreferences.getBoolean(Helper.SET_PROXY_ENABLED, false); - if( proxyEnabled ){ + if (proxyEnabled) { String host = sharedpreferences.getString(Helper.SET_PROXY_HOST, "127.0.0.1"); int port = sharedpreferences.getInt(Helper.SET_PROXY_PORT, 8118); - ProxyHelper.setProxy(getApplicationContext(), webView,host, port,WebviewConnectActivity.class.getName()); + ProxyHelper.setProxy(getApplicationContext(), webView, host, port, WebviewConnectActivity.class.getName()); } webView.setWebViewClient(new WebViewClient() { @SuppressWarnings("deprecation") @Override - public boolean shouldOverrideUrlLoading(WebView view, String url){ - super.shouldOverrideUrlLoading(view,url); - if( url.contains(Helper.REDIRECT_CONTENT_WEB)){ + public boolean shouldOverrideUrlLoading(WebView view, String url) { + super.shouldOverrideUrlLoading(view, url); + if (url.contains(Helper.REDIRECT_CONTENT_WEB)) { String val[] = url.split("code="); - if (val.length< 2){ + if (val.length < 2) { Toasty.error(getApplicationContext(), getString(R.string.toast_code_error), Toast.LENGTH_LONG).show(); Intent myIntent = new Intent(WebviewConnectActivity.this, LoginActivity.class); startActivity(myIntent); @@ -164,10 +166,10 @@ public class WebviewConnectActivity extends BaseActivity { final HashMap parameters = new HashMap<>(); parameters.put(Helper.CLIENT_ID, clientId); parameters.put(Helper.CLIENT_SECRET, clientSecret); - parameters.put(Helper.REDIRECT_URI,Helper.REDIRECT_CONTENT_WEB); + parameters.put(Helper.REDIRECT_URI, Helper.REDIRECT_CONTENT_WEB); parameters.put("grant_type", "authorization_code"); - parameters.put("code",code); - new Thread(new Runnable(){ + parameters.put("code", code); + new Thread(new Runnable() { @Override public void run() { try { @@ -177,7 +179,7 @@ public class WebviewConnectActivity extends BaseActivity { resobj = new JSONObject(response); String token = resobj.get("access_token").toString(); String refresh_token = null; - if( resobj.has("refresh_token")) + if (resobj.has("refresh_token")) refresh_token = resobj.get("refresh_token").toString(); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedpreferences.edit(); @@ -185,9 +187,12 @@ public class WebviewConnectActivity extends BaseActivity { editor.apply(); //Update the account with the token; new UpdateAccountInfoAsyncTask(WebviewConnectActivity.this, token, clientId, clientSecret, refresh_token, instance, social).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } catch (JSONException ignored) {} - } catch (Exception ignored) {} - }}).start(); + } catch (JSONException ignored) { + } + } catch (Exception ignored) { + } + } + }).start(); return true; } return false; @@ -208,8 +213,6 @@ public class WebviewConnectActivity extends BaseActivity { } - - @Override public void onDestroy() { super.onDestroy(); @@ -220,16 +223,15 @@ public class WebviewConnectActivity extends BaseActivity { } @SuppressWarnings("deprecation") - public static void clearCookies(Context context) - { + public static void clearCookies(Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { CookieManager.getInstance().removeAllCookies(null); CookieManager.getInstance().flush(); } else { - CookieSyncManager cookieSyncMngr=CookieSyncManager.createInstance(context); + CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(context); cookieSyncMngr.startSync(); - CookieManager cookieManager=CookieManager.getInstance(); + CookieManager cookieManager = CookieManager.getInstance(); cookieManager.removeAllCookie(); cookieManager.removeSessionCookie(); cookieSyncMngr.stopSync(); diff --git a/app/src/main/java/app/fedilab/android/activities/WhoToFollowActivity.java b/app/src/main/java/app/fedilab/android/activities/WhoToFollowActivity.java index 5c5307df6..0569e88c8 100644 --- a/app/src/main/java/app/fedilab/android/activities/WhoToFollowActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/WhoToFollowActivity.java @@ -19,8 +19,10 @@ import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; + import androidx.core.content.ContextCompat; import androidx.appcompat.widget.Toolbar; + import android.view.MenuItem; import android.view.View; import android.widget.Button; @@ -59,7 +61,6 @@ import app.fedilab.android.interfaces.OnRetrieveWhoToFollowInterface; public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoToFollowInterface, OnPostActionInterface, OnListActionInterface { - private String item; private List followedId; private List accountListId; @@ -75,7 +76,7 @@ public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoTo super.onCreate(savedInstanceState); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme_NoActionBar_Fedilab); break; @@ -92,30 +93,30 @@ public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoTo no_action = findViewById(R.id.no_action); Toolbar toolbar = findViewById(R.id.toolbar); progess_action = findViewById(R.id.progess_action); - if( theme == Helper.THEME_BLACK) + if (theme == Helper.THEME_BLACK) toolbar.setBackgroundColor(ContextCompat.getColor(WhoToFollowActivity.this, R.color.black)); setSupportActionBar(toolbar); - if( getSupportActionBar() != null) + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); mainLoader = findViewById(R.id.loader); Bundle b = getIntent().getExtras(); - if(b != null){ + if (b != null) { item = b.getString("item"); } followedId = new ArrayList<>(); - String lastDateListNameRefresh = sharedpreferences.getString(Helper.LAST_DATE_LIST_NAME_REFRESH+item, null); + String lastDateListNameRefresh = sharedpreferences.getString(Helper.LAST_DATE_LIST_NAME_REFRESH + item, null); Calendar cal = Calendar.getInstance(); - cal.setTime(new Date( )); + cal.setTime(new Date()); cal.add(Calendar.MINUTE, -5); Date dateAllowed = cal.getTime(); - if( lastDateListNameRefresh == null || Helper.stringToDate(WhoToFollowActivity.this, lastDateListNameRefresh).before(dateAllowed)) { + if (lastDateListNameRefresh == null || Helper.stringToDate(WhoToFollowActivity.this, lastDateListNameRefresh).before(dateAllowed)) { new WhoToFollowAsyncTask(WhoToFollowActivity.this, item, WhoToFollowActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); mainLoader.setVisibility(View.VISIBLE); - }else { + } else { String lastList = sharedpreferences.getString(Helper.LAST_LIST_NAME + item, null); List acctString = Helper.restoreArrayFromString(lastList); - if( acctString != null) { + if (acctString != null) { trunkAccounts = new ArrayList<>(); for (String acct : acctString) { TrunkAccount trunkAccount = new TrunkAccount(); @@ -129,19 +130,19 @@ public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoTo } - private void displayResults(){ + private void displayResults() { mainLoader.setVisibility(View.GONE); WhoToFollowAccountsAdapter whoToFollowAccountsAdapter; - if( trunkAccounts != null){ - if( trunkAccounts.size() > 0) { + if (trunkAccounts != null) { + if (trunkAccounts.size() > 0) { ListView lv_list = findViewById(R.id.lv_list); whoToFollowAccountsAdapter = new WhoToFollowAccountsAdapter(trunkAccounts); lv_list.setAdapter(whoToFollowAccountsAdapter); - }else { + } else { no_action.setVisibility(View.VISIBLE); return; } - }else{ + } else { Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_SHORT).show(); return; } @@ -150,15 +151,15 @@ public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoTo follow_accounts_select.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - if(follow_accounts_select.getText().equals(getString(R.string.select_all))){ + if (follow_accounts_select.getText().equals(getString(R.string.select_all))) { follow_accounts_select.setText(R.string.unselect_all); - for(TrunkAccount trunkAccount: trunkAccounts){ + for (TrunkAccount trunkAccount : trunkAccounts) { trunkAccount.setChecked(true); } whoToFollowAccountsAdapter.notifyDataSetChanged(); - }else { + } else { follow_accounts_select.setText(R.string.select_all); - for(TrunkAccount trunkAccount: trunkAccounts){ + for (TrunkAccount trunkAccount : trunkAccounts) { trunkAccount.setChecked(false); } whoToFollowAccountsAdapter.notifyDataSetChanged(); @@ -173,21 +174,21 @@ public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoTo follow_accounts_select.setEnabled(false); progess_action.setVisibility(View.VISIBLE); toFollowdId = new ArrayList<>(); - for(TrunkAccount trunkAccount: trunkAccounts){ - if( trunkAccount.isChecked()){ + for (TrunkAccount trunkAccount : trunkAccounts) { + if (trunkAccount.isChecked()) { toFollowdId.add(trunkAccount.getAcct()); } } - if(toFollowdId.size() > 0){ + if (toFollowdId.size() > 0) { Account account = new Account(); String[] val = toFollowdId.get(0).split("@"); progess_action.setText(getString(R.string.follow_trunk, toFollowdId.get(0))); - if( val.length > 1){ + if (val.length > 1) { account.setAcct(val[0]); account.setInstance(val[1]); new PostActionAsyncTask(WhoToFollowActivity.this, null, account, API.StatusAction.FOLLOW, WhoToFollowActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else { - Toasty.error(getApplicationContext(),getString(R.string.toast_impossible_to_follow), Toast.LENGTH_LONG).show(); + } else { + Toasty.error(getApplicationContext(), getString(R.string.toast_impossible_to_follow), Toast.LENGTH_LONG).show(); follow_accounts.setEnabled(true); follow_accounts_select.setEnabled(true); progess_action.setVisibility(View.GONE); @@ -216,12 +217,12 @@ public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoTo @Override public void onRetrieveWhoToFollowAccount(List trunkAccounts) { - if( trunkAccounts != null){ + if (trunkAccounts != null) { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(Helper.LAST_DATE_LIST_NAME_REFRESH + item, Helper.dateToString(new Date())); List accounts = new ArrayList<>(); - for(TrunkAccount trunkAccount: trunkAccounts) + for (TrunkAccount trunkAccount : trunkAccounts) accounts.add(trunkAccount.getAcct()); editor.putString(Helper.LAST_LIST_NAME + item, Helper.arrayToStringStorage(accounts)); editor.apply(); @@ -233,14 +234,14 @@ public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoTo @Override public void onPostAction(int statusCode, API.StatusAction statusAction, String userId, Error error) { followedId.add(userId); - if( followedId != null && followedId.size() >= toFollowdId.size()) { + if (followedId != null && followedId.size() >= toFollowdId.size()) { progess_action.setText(getString(R.string.create_list_trunk, item)); new ManageListsAsyncTask(WhoToFollowActivity.this, ManageListsAsyncTask.action.CREATE_LIST, null, null, null, item, WhoToFollowActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else { + } else { Account account = new Account(); String[] val = toFollowdId.get(followedId.size()).split("@"); progess_action.setText(getString(R.string.follow_trunk, toFollowdId.get(followedId.size()))); - if( val.length > 1){ + if (val.length > 1) { account.setAcct(val[0]); account.setInstance(val[1]); new PostActionAsyncTask(WhoToFollowActivity.this, null, account, API.StatusAction.FOLLOW, WhoToFollowActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); @@ -253,16 +254,16 @@ public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoTo public void onActionDone(ManageListsAsyncTask.action actionType, APIResponse apiResponse, int statusCode) { List lists = apiResponse.getLists(); - if( lists!= null && lists.size() > 0 && actionType == ManageListsAsyncTask.action.CREATE_LIST){ + if (lists != null && lists.size() > 0 && actionType == ManageListsAsyncTask.action.CREATE_LIST) { String[] accountsId = followedId.toArray(new String[0]); progess_action.setText(R.string.add_account_list_trunk); listId = lists.get(0).getId(); listTitle = lists.get(0).getTitle(); new ManageListsAsyncTask(WhoToFollowActivity.this, ManageListsAsyncTask.action.ADD_USERS, new String[]{followedId.get(0)}, null, lists.get(0).getId(), null, WhoToFollowActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); accountListId = new ArrayList<>(); - }else if(accountListId != null){ + } else if (accountListId != null) { - if( accountListId.size() >= followedId.size() -1) { + if (accountListId.size() >= followedId.size() - 1) { progess_action.setText(R.string.account_added_list_trunk); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @@ -274,12 +275,12 @@ public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoTo b.putString("title", listTitle); intent.putExtras(b); startActivity(intent); - finish(); + finish(); } }, 1000); - }else { + } else { accountListId.add(followedId.get(accountListId.size())); progess_action.setText(R.string.adding_account_list_trunk); String userIdToAdd = followedId.get(accountListId.size()); diff --git a/app/src/main/java/app/fedilab/android/animatemenu/model/SlideMenuItem.java b/app/src/main/java/app/fedilab/android/animatemenu/model/SlideMenuItem.java index 805517c16..443a43e59 100644 --- a/app/src/main/java/app/fedilab/android/animatemenu/model/SlideMenuItem.java +++ b/app/src/main/java/app/fedilab/android/animatemenu/model/SlideMenuItem.java @@ -24,7 +24,7 @@ public class SlideMenuItem implements Resourceble { @Override public ContentSettingsFragment.type getType() { - return this.type; + return this.type; } public void setImageRes(int imageRes) { diff --git a/app/src/main/java/app/fedilab/android/animatemenu/util/ViewAnimator.java b/app/src/main/java/app/fedilab/android/animatemenu/util/ViewAnimator.java index 387ff2e78..cf7aff362 100644 --- a/app/src/main/java/app/fedilab/android/animatemenu/util/ViewAnimator.java +++ b/app/src/main/java/app/fedilab/android/animatemenu/util/ViewAnimator.java @@ -36,7 +36,7 @@ public class ViewAnimator { public static final int CIRCULAR_REVEAL_ANIMATION_DURATION = 500; private AppCompatActivity appCompatActivity; - + private List list; private List viewList = new ArrayList<>(); @@ -59,7 +59,6 @@ public class ViewAnimator { } - public void showMenuContent() { setViewsClickable(false); viewList.clear(); @@ -67,20 +66,20 @@ public class ViewAnimator { for (int i = 0; i < size; i++) { @SuppressLint("InflateParams") View viewMenu = appCompatActivity.getLayoutInflater().inflate(R.layout.menu_list_item, null); - if( i == SettingsActivity.position){ + if (i == SettingsActivity.position) { viewMenu.setBackgroundColor(ContextCompat.getColor(appCompatActivity, R.color.mastodonC2)); - }else { + } else { SharedPreferences sharedpreferences = appCompatActivity.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); if (theme == Helper.THEME_DARK) { viewMenu.setBackgroundResource(R.drawable.menu_item_selector); - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { viewMenu.setBackgroundResource(R.drawable.menu_item_selector_black); - }else { + } else { viewMenu.setBackgroundResource(R.drawable.menu_item_selector_light); ImageView imageView = viewMenu.findViewById(R.id.menu_item_image); - if( imageView != null){ + if (imageView != null) { changeDrawableColor(appCompatActivity, imageView, R.color.black); } } @@ -104,7 +103,7 @@ public class ViewAnimator { animatorListener.addViewToContainer(viewMenu); final double position = i; final double delay = 3 * ANIMATION_DURATION * (position / size); - if( screenShotable != null) { + if (screenShotable != null) { new Handler().postDelayed(new Runnable() { public void run() { if (position < viewList.size()) { diff --git a/app/src/main/java/app/fedilab/android/asynctasks/CreateMastodonAccountAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/CreateMastodonAccountAsyncTask.java index 29f67a4df..5d436c981 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/CreateMastodonAccountAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/CreateMastodonAccountAsyncTask.java @@ -18,6 +18,7 @@ import android.content.Context; import android.os.AsyncTask; import java.lang.ref.WeakReference; + import app.fedilab.android.client.API; import app.fedilab.android.client.APIResponse; import app.fedilab.android.client.Entities.AccountCreation; @@ -38,7 +39,7 @@ public class CreateMastodonAccountAsyncTask extends AsyncTask private WeakReference contextReference; private String instance; - public CreateMastodonAccountAsyncTask(Context context, AccountCreation accountCreation, String instance, OnPostStatusActionInterface onPostStatusActionInterface){ + public CreateMastodonAccountAsyncTask(Context context, AccountCreation accountCreation, String instance, OnPostStatusActionInterface onPostStatusActionInterface) { this.contextReference = new WeakReference<>(context); this.listener = onPostStatusActionInterface; this.accountCreation = accountCreation; diff --git a/app/src/main/java/app/fedilab/android/asynctasks/CustomSharingAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/CustomSharingAsyncTask.java index eed54b699..cd1a7d7b3 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/CustomSharingAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/CustomSharingAsyncTask.java @@ -36,7 +36,7 @@ public class CustomSharingAsyncTask extends AsyncTask { private OnCustomSharingInterface listener; private WeakReference contextReference; - public CustomSharingAsyncTask(Context context, String encodedCustomSharingURL, OnCustomSharingInterface onCustomSharingInterface){ + public CustomSharingAsyncTask(Context context, String encodedCustomSharingURL, OnCustomSharingInterface onCustomSharingInterface) { this.contextReference = new WeakReference<>(context); this.encodedCustomSharingURL = encodedCustomSharingURL; this.listener = onCustomSharingInterface; diff --git a/app/src/main/java/app/fedilab/android/asynctasks/DeleteDomainsAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/DeleteDomainsAsyncTask.java index c574e03ac..687418135 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/DeleteDomainsAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/DeleteDomainsAsyncTask.java @@ -36,7 +36,7 @@ public class DeleteDomainsAsyncTask extends AsyncTask { private int response; private String domainName; - public DeleteDomainsAsyncTask(Context context, String domainName, OnRetrieveDomainsInterface onRetrieveDomainsInterface){ + public DeleteDomainsAsyncTask(Context context, String domainName, OnRetrieveDomainsInterface onRetrieveDomainsInterface) { this.contextReference = new WeakReference<>(context); this.listener = onRetrieveDomainsInterface; this.domainName = domainName; diff --git a/app/src/main/java/app/fedilab/android/asynctasks/DownloadTrackingDomainsAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/DownloadTrackingDomainsAsyncTask.java index 0ef71becd..3e5a5bcd2 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/DownloadTrackingDomainsAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/DownloadTrackingDomainsAsyncTask.java @@ -93,7 +93,7 @@ public class DownloadTrackingDomainsAsyncTask extends AsyncTask Toasty.success(context.get(), context.get().getString(R.string.tracking_db_updated), Toast.LENGTH_LONG).show()); else mainHandler.post(() -> Toasty.error(context.get(), context.get().getString(R.string.toast_error), Toast.LENGTH_LONG).show()); - if( update_tracking_domains != null && update_tracking_domains.get() != null) { + if (update_tracking_domains != null && update_tracking_domains.get() != null) { update_tracking_domains.get().setEnabled(true); } } diff --git a/app/src/main/java/app/fedilab/android/asynctasks/ManageCachedStatusAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/ManageCachedStatusAsyncTask.java index 4fbf6de66..60189dc59 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/ManageCachedStatusAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/ManageCachedStatusAsyncTask.java @@ -36,9 +36,7 @@ public class ManageCachedStatusAsyncTask extends AsyncTask { private WeakReference contextReference; - - - public ManageCachedStatusAsyncTask(Context context, String statusId, OnRefreshCachedStatusInterface onRefreshCachedStatusInterface){ + public ManageCachedStatusAsyncTask(Context context, String statusId, OnRefreshCachedStatusInterface onRefreshCachedStatusInterface) { this.contextReference = new WeakReference<>(context); this.listener = onRefreshCachedStatusInterface; this.statusId = statusId; @@ -48,12 +46,12 @@ public class ManageCachedStatusAsyncTask extends AsyncTask { @Override protected Void doInBackground(Void... params) { APIResponse apiResponse = new API(contextReference.get()).getStatusbyIdAndCache(statusId); - if( apiResponse.getStatuses().size() > 0){ + if (apiResponse.getStatuses().size() > 0) { refreshedStatus = apiResponse.getStatuses().get(0); - if( refreshedStatus != null){ + if (refreshedStatus != null) { refreshedStatus.setcached(true); } - }else { + } else { refreshedStatus = new app.fedilab.android.client.Entities.Status(); refreshedStatus.setId(statusId); diff --git a/app/src/main/java/app/fedilab/android/asynctasks/ManageFiltersAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/ManageFiltersAsyncTask.java index e7151dae7..55d975692 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/ManageFiltersAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/ManageFiltersAsyncTask.java @@ -32,7 +32,7 @@ import app.fedilab.android.interfaces.OnFilterActionInterface; public class ManageFiltersAsyncTask extends AsyncTask { - public enum action{ + public enum action { GET_FILTER, GET_ALL_FILTER, CREATE_FILTER, @@ -47,7 +47,7 @@ public class ManageFiltersAsyncTask extends AsyncTask { private WeakReference contextReference; private Filters filter; - public ManageFiltersAsyncTask(Context context, action apiAction, Filters filter, OnFilterActionInterface onFilterActionInterface){ + public ManageFiltersAsyncTask(Context context, action apiAction, Filters filter, OnFilterActionInterface onFilterActionInterface) { contextReference = new WeakReference<>(context); this.listener = onFilterActionInterface; this.filter = filter; @@ -59,13 +59,13 @@ public class ManageFiltersAsyncTask extends AsyncTask { protected Void doInBackground(Void... params) { if (apiAction == action.GET_ALL_FILTER) { apiResponse = new API(contextReference.get()).getFilters(); - }else if(apiAction == action.GET_FILTER){ + } else if (apiAction == action.GET_FILTER) { apiResponse = new API(contextReference.get()).getFilters(filter.getId()); - }else if(apiAction == action.CREATE_FILTER){ + } else if (apiAction == action.CREATE_FILTER) { apiResponse = new API(contextReference.get()).addFilters(filter); - }else if( apiAction == action.UPDATE_FILTER){ + } else if (apiAction == action.UPDATE_FILTER) { apiResponse = new API(contextReference.get()).updateFilters(filter); - }else if(apiAction == action.DELETE_FILTER){ + } else if (apiAction == action.DELETE_FILTER) { statusCode = new API(contextReference.get()).deleteFilters(filter); } return null; diff --git a/app/src/main/java/app/fedilab/android/asynctasks/ManageListsAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/ManageListsAsyncTask.java index f6ecac567..a71565434 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/ManageListsAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/ManageListsAsyncTask.java @@ -31,7 +31,7 @@ import app.fedilab.android.interfaces.OnListActionInterface; public class ManageListsAsyncTask extends AsyncTask { - public enum action{ + public enum action { GET_LIST, GET_LIST_TIMELINE, GET_LIST_ACCOUNT, @@ -56,7 +56,7 @@ public class ManageListsAsyncTask extends AsyncTask { private int limit; private String search; - public ManageListsAsyncTask(Context context, action apiAction, String[] accountsId, String targetedId, String listId, String title, OnListActionInterface onListActionInterface){ + public ManageListsAsyncTask(Context context, action apiAction, String[] accountsId, String targetedId, String listId, String title, OnListActionInterface onListActionInterface) { contextReference = new WeakReference<>(context); this.listener = onListActionInterface; this.listId = listId; @@ -66,7 +66,7 @@ public class ManageListsAsyncTask extends AsyncTask { this.targetedId = targetedId; } - public ManageListsAsyncTask(Context context, String listId, String max_id, String since_id, OnListActionInterface onListActionInterface){ + public ManageListsAsyncTask(Context context, String listId, String max_id, String since_id, OnListActionInterface onListActionInterface) { contextReference = new WeakReference<>(context); this.listener = onListActionInterface; this.listId = listId; @@ -76,7 +76,7 @@ public class ManageListsAsyncTask extends AsyncTask { this.apiAction = action.GET_LIST_TIMELINE; } - public ManageListsAsyncTask(Context context, String search, OnListActionInterface onListActionInterface){ + public ManageListsAsyncTask(Context context, String search, OnListActionInterface onListActionInterface) { contextReference = new WeakReference<>(context); this.listener = onListActionInterface; this.search = search; @@ -87,21 +87,21 @@ public class ManageListsAsyncTask extends AsyncTask { protected Void doInBackground(Void... params) { if (apiAction == action.GET_LIST) { apiResponse = new API(contextReference.get()).getLists(); - }else if(apiAction == action.GET_LIST_TIMELINE){ + } else if (apiAction == action.GET_LIST_TIMELINE) { apiResponse = new API(contextReference.get()).getListTimeline(this.listId, this.max_id, this.since_id, this.limit); - }else if(apiAction == action.GET_LIST_ACCOUNT){ - apiResponse = new API(contextReference.get()).getAccountsInList(this.listId,0); - }else if( apiAction == action.CREATE_LIST){ + } else if (apiAction == action.GET_LIST_ACCOUNT) { + apiResponse = new API(contextReference.get()).getAccountsInList(this.listId, 0); + } else if (apiAction == action.CREATE_LIST) { apiResponse = new API(contextReference.get()).createList(this.title); - }else if(apiAction == action.DELETE_LIST){ + } else if (apiAction == action.DELETE_LIST) { statusCode = new API(contextReference.get()).deleteList(this.listId); - }else if(apiAction == action.UPDATE_LIST){ + } else if (apiAction == action.UPDATE_LIST) { apiResponse = new API(contextReference.get()).updateList(this.listId, this.title); - }else if(apiAction == action.ADD_USERS){ + } else if (apiAction == action.ADD_USERS) { apiResponse = new API(contextReference.get()).addAccountToList(this.listId, this.accountsId); - }else if(apiAction == action.DELETE_USERS){ + } else if (apiAction == action.DELETE_USERS) { statusCode = new API(contextReference.get()).deleteAccountFromList(this.listId, this.accountsId); - }else if( apiAction == action.SEARCH_USER){ + } else if (apiAction == action.SEARCH_USER) { apiResponse = new API(contextReference.get()).searchAccounts(this.search, 20, true); } return null; diff --git a/app/src/main/java/app/fedilab/android/asynctasks/ManagePlaylistsAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/ManagePlaylistsAsyncTask.java index 6d7d0a1da..97300c7e5 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/ManagePlaylistsAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/ManagePlaylistsAsyncTask.java @@ -39,7 +39,7 @@ import app.fedilab.android.sqlite.Sqlite; public class ManagePlaylistsAsyncTask extends AsyncTask { - public enum action{ + public enum action { GET_PLAYLIST, GET_LIST_VIDEOS, CREATE_PLAYLIST, @@ -59,7 +59,7 @@ public class ManagePlaylistsAsyncTask extends AsyncTask { private Playlist playlist; private String videoId; - public ManagePlaylistsAsyncTask(Context context, action apiAction, Playlist playlist, String videoId, String max_id, OnPlaylistActionInterface onPlaylistActionInterface){ + public ManagePlaylistsAsyncTask(Context context, action apiAction, Playlist playlist, String videoId, String max_id, OnPlaylistActionInterface onPlaylistActionInterface) { contextReference = new WeakReference<>(context); this.listener = onPlaylistActionInterface; this.apiAction = apiAction; @@ -78,15 +78,15 @@ public class ManagePlaylistsAsyncTask extends AsyncTask { Account account = new AccountDAO(contextReference.get(), db).getUniqAccount(userId, instance); if (apiAction == action.GET_PLAYLIST) { apiResponse = new PeertubeAPI(contextReference.get()).getPlayists(account.getUsername()); - }else if(apiAction == action.GET_LIST_VIDEOS){ - apiResponse = new PeertubeAPI(contextReference.get()).getPlaylistVideos(playlist.getId(),max_id, null); - }else if(apiAction == action.DELETE_PLAYLIST){ + } else if (apiAction == action.GET_LIST_VIDEOS) { + apiResponse = new PeertubeAPI(contextReference.get()).getPlaylistVideos(playlist.getId(), max_id, null); + } else if (apiAction == action.DELETE_PLAYLIST) { statusCode = new PeertubeAPI(contextReference.get()).deletePlaylist(playlist.getId()); - }else if(apiAction == action.ADD_VIDEOS){ - statusCode = new PeertubeAPI(contextReference.get()).addVideoPlaylist(playlist.getId(),videoId); - }else if(apiAction == action.DELETE_VIDEOS){ - statusCode = new PeertubeAPI(contextReference.get()).deleteVideoPlaylist(playlist.getId(),videoId); - }else if(apiAction == action.GET_PLAYLIST_FOR_VIDEO){ + } else if (apiAction == action.ADD_VIDEOS) { + statusCode = new PeertubeAPI(contextReference.get()).addVideoPlaylist(playlist.getId(), videoId); + } else if (apiAction == action.DELETE_VIDEOS) { + statusCode = new PeertubeAPI(contextReference.get()).deleteVideoPlaylist(playlist.getId(), videoId); + } else if (apiAction == action.GET_PLAYLIST_FOR_VIDEO) { apiResponse = new PeertubeAPI(contextReference.get()).getPlaylistForVideo(videoId); } return null; diff --git a/app/src/main/java/app/fedilab/android/asynctasks/ManagePollAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/ManagePollAsyncTask.java index 37de25bf6..9f23e061d 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/ManagePollAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/ManagePollAsyncTask.java @@ -16,6 +16,7 @@ package app.fedilab.android.asynctasks; import android.content.Context; import android.os.AsyncTask; + import java.lang.ref.WeakReference; import app.fedilab.android.client.API; @@ -38,12 +39,12 @@ public class ManagePollAsyncTask extends AsyncTask { private Poll poll; private type_s type; - public enum type_s{ + public enum type_s { SUBMIT, REFRESH } - public ManagePollAsyncTask(Context context, type_s type, app.fedilab.android.client.Entities.Status status, int[] choices, OnPollInterface onPollInterface){ + public ManagePollAsyncTask(Context context, type_s type, app.fedilab.android.client.Entities.Status status, int[] choices, OnPollInterface onPollInterface) { this.contextReference = new WeakReference<>(context); this.listener = onPollInterface; this.status = status; @@ -54,16 +55,16 @@ public class ManagePollAsyncTask extends AsyncTask { @Override protected Void doInBackground(Void... params) { Poll _poll; - if( status.getReblog() != null) + if (status.getReblog() != null) _poll = status.getReblog().getPoll(); else _poll = status.getPoll(); - if( _poll.getId() == null) + if (_poll.getId() == null) return null; - if (type == type_s.SUBMIT){ - poll = new API(contextReference.get()).submiteVote(_poll.getId(),choices); - }else if( type == type_s.REFRESH){ + if (type == type_s.SUBMIT) { + poll = new API(contextReference.get()).submiteVote(_poll.getId(), choices); + } else if (type == type_s.REFRESH) { poll = new API(contextReference.get()).getPoll(status); } return null; diff --git a/app/src/main/java/app/fedilab/android/asynctasks/PostActionAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/PostActionAsyncTask.java index 3f4cb538b..1f219fd8d 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/PostActionAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/PostActionAsyncTask.java @@ -52,21 +52,21 @@ public class PostActionAsyncTask extends AsyncTask { private Error error; private StoredStatus storedStatus; - public PostActionAsyncTask(Context context, API.StatusAction apiAction, StoredStatus storedStatus, OnPostActionInterface onPostActionInterface){ + public PostActionAsyncTask(Context context, API.StatusAction apiAction, StoredStatus storedStatus, OnPostActionInterface onPostActionInterface) { this.contextReference = new WeakReference<>(context); this.listener = onPostActionInterface; this.apiAction = apiAction; this.storedStatus = storedStatus; } - public PostActionAsyncTask(Context context, API.StatusAction apiAction, String targetedId, OnPostActionInterface onPostActionInterface){ + public PostActionAsyncTask(Context context, API.StatusAction apiAction, String targetedId, OnPostActionInterface onPostActionInterface) { this.contextReference = new WeakReference<>(context); this.listener = onPostActionInterface; this.apiAction = apiAction; this.targetedId = targetedId; } - public PostActionAsyncTask(Context context, Account account, API.StatusAction apiAction, String targetedId, OnPostActionInterface onPostActionInterface){ + public PostActionAsyncTask(Context context, Account account, API.StatusAction apiAction, String targetedId, OnPostActionInterface onPostActionInterface) { this.contextReference = new WeakReference<>(context); this.listener = onPostActionInterface; this.apiAction = apiAction; @@ -74,7 +74,7 @@ public class PostActionAsyncTask extends AsyncTask { this.account = account; } - public PostActionAsyncTask(Context context, Account account, app.fedilab.android.client.Entities.Status remoteStatus, API.StatusAction apiAction, OnPostActionInterface onPostActionInterface){ + public PostActionAsyncTask(Context context, Account account, app.fedilab.android.client.Entities.Status remoteStatus, API.StatusAction apiAction, OnPostActionInterface onPostActionInterface) { this.contextReference = new WeakReference<>(context); this.listener = onPostActionInterface; this.apiAction = apiAction; @@ -82,7 +82,7 @@ public class PostActionAsyncTask extends AsyncTask { this.account = account; } - public PostActionAsyncTask(Context context, Account account, Account remoteAccount, API.StatusAction apiAction, OnPostActionInterface onPostActionInterface){ + public PostActionAsyncTask(Context context, Account account, Account remoteAccount, API.StatusAction apiAction, OnPostActionInterface onPostActionInterface) { this.contextReference = new WeakReference<>(context); this.listener = onPostActionInterface; this.apiAction = apiAction; @@ -90,7 +90,7 @@ public class PostActionAsyncTask extends AsyncTask { this.account = account; } - public PostActionAsyncTask(Context context, API.StatusAction apiAction, String targetedId, app.fedilab.android.client.Entities.Status status, String comment, OnPostActionInterface onPostActionInterface){ + public PostActionAsyncTask(Context context, API.StatusAction apiAction, String targetedId, app.fedilab.android.client.Entities.Status status, String comment, OnPostActionInterface onPostActionInterface) { contextReference = new WeakReference<>(context); this.listener = onPostActionInterface; this.apiAction = apiAction; @@ -98,7 +98,8 @@ public class PostActionAsyncTask extends AsyncTask { this.comment = comment; this.status = status; } - public PostActionAsyncTask(Context context, API.StatusAction apiAction, String targetedId, boolean muteNotifications, OnPostActionInterface onPostActionInterface){ + + public PostActionAsyncTask(Context context, API.StatusAction apiAction, String targetedId, boolean muteNotifications, OnPostActionInterface onPostActionInterface) { this.contextReference = new WeakReference<>(context); this.listener = onPostActionInterface; this.apiAction = apiAction; @@ -107,7 +108,7 @@ public class PostActionAsyncTask extends AsyncTask { } - public PostActionAsyncTask(Context context, String targetedId, String comment, String targetedComment, OnPostActionInterface onPostActionInterface){ + public PostActionAsyncTask(Context context, String targetedId, String comment, String targetedComment, OnPostActionInterface onPostActionInterface) { this.contextReference = new WeakReference<>(context); this.listener = onPostActionInterface; this.apiAction = API.StatusAction.PEERTUBEREPLY; @@ -119,7 +120,7 @@ public class PostActionAsyncTask extends AsyncTask { @Override protected Void doInBackground(Void... params) { - if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) { //Remote action API api; if (account != null) @@ -162,26 +163,24 @@ public class PostActionAsyncTask extends AsyncTask { } } else { if (apiAction == API.StatusAction.REPORT) { - if( status != null ) { + if (status != null) { statusCode = api.reportAction(status, comment); - }else{ + } else { statusCode = api.reportAction(targetedId, comment); } - } - else if (apiAction == API.StatusAction.CREATESTATUS) + } else if (apiAction == API.StatusAction.CREATESTATUS) statusCode = api.statusAction(status); - else if(apiAction == API.StatusAction.UPDATESERVERSCHEDULE) { + else if (apiAction == API.StatusAction.UPDATESERVERSCHEDULE) { api.scheduledAction("PUT", storedStatus.getStatus(), null, storedStatus.getScheduledServerdId()); - } - else if(apiAction == API.StatusAction.DELETESCHEDULED) { + } else if (apiAction == API.StatusAction.DELETESCHEDULED) { api.scheduledAction("DELETE", null, null, storedStatus.getScheduledServerdId()); - }else if (apiAction == API.StatusAction.MUTE_NOTIFICATIONS) + } else if (apiAction == API.StatusAction.MUTE_NOTIFICATIONS) statusCode = api.muteNotifications(targetedId, muteNotifications); else statusCode = api.postAction(apiAction, targetedId); } error = api.getError(); - }else if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE){ + } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { //Remote action PeertubeAPI peertubeAPI; if (account != null) @@ -189,22 +188,22 @@ public class PostActionAsyncTask extends AsyncTask { else peertubeAPI = new PeertubeAPI(contextReference.get()); - if( apiAction == API.StatusAction.FOLLOW || apiAction == API.StatusAction.UNFOLLOW) + if (apiAction == API.StatusAction.FOLLOW || apiAction == API.StatusAction.UNFOLLOW) statusCode = peertubeAPI.postAction(apiAction, targetedId); - else if( apiAction == API.StatusAction.RATEVIDEO ) + else if (apiAction == API.StatusAction.RATEVIDEO) statusCode = peertubeAPI.postRating(targetedId, comment); - else if( apiAction == API.StatusAction.PEERTUBECOMMENT) + else if (apiAction == API.StatusAction.PEERTUBECOMMENT) statusCode = peertubeAPI.postComment(targetedId, comment); - else if( apiAction == API.StatusAction.PEERTUBEREPLY) + else if (apiAction == API.StatusAction.PEERTUBEREPLY) statusCode = peertubeAPI.postReply(targetedId, comment, targetedComment); - else if( apiAction == API.StatusAction.PEERTUBEDELETECOMMENT) { + else if (apiAction == API.StatusAction.PEERTUBEDELETECOMMENT) { statusCode = peertubeAPI.deleteComment(targetedId, comment); targetedId = comment; - } else if( apiAction == API.StatusAction.PEERTUBEDELETEVIDEO) { + } else if (apiAction == API.StatusAction.PEERTUBEDELETEVIDEO) { statusCode = peertubeAPI.deleteVideo(targetedId); } error = peertubeAPI.getError(); - }else if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA){ + } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { GNUAPI gnuapi; if (account != null) gnuapi = new GNUAPI(contextReference.get(), account.getInstance(), account.getToken()); diff --git a/app/src/main/java/app/fedilab/android/asynctasks/PostAdminActionAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/PostAdminActionAsyncTask.java index eb7a5f7e6..5fb851811 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/PostAdminActionAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/PostAdminActionAsyncTask.java @@ -18,6 +18,7 @@ import android.content.Context; import android.os.AsyncTask; import java.lang.ref.WeakReference; + import app.fedilab.android.client.API; import app.fedilab.android.client.APIResponse; import app.fedilab.android.client.Entities.AdminAction; @@ -25,7 +26,6 @@ import app.fedilab.android.helper.Helper; import app.fedilab.android.interfaces.OnAdminActionInterface; - /** * Created by Thomas on 18/06/2019. * Makes actions for post admin calls @@ -41,8 +41,7 @@ public class PostAdminActionAsyncTask extends AsyncTask { private AdminAction adminAction; - - public PostAdminActionAsyncTask(Context context, API.adminAction action, String id, AdminAction adminAction, OnAdminActionInterface onAdminActionInterface){ + public PostAdminActionAsyncTask(Context context, API.adminAction action, String id, AdminAction adminAction, OnAdminActionInterface onAdminActionInterface) { this.contextReference = new WeakReference<>(context); this.listener = onAdminActionInterface; this.action = action; @@ -53,7 +52,7 @@ public class PostAdminActionAsyncTask extends AsyncTask { @Override protected Void doInBackground(Void... params) { - switch (action){ + switch (action) { case GET_ACCOUNTS: case GET_ONE_ACCOUNT: case GET_REPORTS: diff --git a/app/src/main/java/app/fedilab/android/asynctasks/PostNotificationsAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/PostNotificationsAsyncTask.java index 47426d193..4e056ce81 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/PostNotificationsAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/PostNotificationsAsyncTask.java @@ -36,7 +36,7 @@ public class PostNotificationsAsyncTask extends AsyncTask { private String targetedId; private WeakReference contextReference; - public PostNotificationsAsyncTask(Context context, String targetedId, OnPostNotificationsActionInterface onPostNotificationsActionInterface){ + public PostNotificationsAsyncTask(Context context, String targetedId, OnPostNotificationsActionInterface onPostNotificationsActionInterface) { this.contextReference = new WeakReference<>(context); this.listener = onPostNotificationsActionInterface; this.targetedId = targetedId; @@ -44,7 +44,7 @@ public class PostNotificationsAsyncTask extends AsyncTask { @Override protected Void doInBackground(Void... params) { - if( targetedId != null) + if (targetedId != null) apiResponse = new API(this.contextReference.get()).postNoticationAction(targetedId); else //Delete all notifications apiResponse = new API(this.contextReference.get()).postNoticationAction(null); diff --git a/app/src/main/java/app/fedilab/android/asynctasks/PostPeertubeAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/PostPeertubeAsyncTask.java index 1017c2109..fff8ce4d1 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/PostPeertubeAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/PostPeertubeAsyncTask.java @@ -33,27 +33,24 @@ import app.fedilab.android.interfaces.OnRetrievePeertubeInterface; public class PostPeertubeAsyncTask extends AsyncTask { - private APIResponse apiResponse; private OnRetrievePeertubeInterface listener; private WeakReference contextReference; private Peertube peertube; - - public PostPeertubeAsyncTask(Context context, Peertube peertube, OnRetrievePeertubeInterface onRetrievePeertubeInterface){ + public PostPeertubeAsyncTask(Context context, Peertube peertube, OnRetrievePeertubeInterface onRetrievePeertubeInterface) { this.contextReference = new WeakReference<>(context); this.listener = onRetrievePeertubeInterface; this.peertube = peertube; } - @Override protected Void doInBackground(Void... params) { PeertubeAPI peertubeAPI = new PeertubeAPI(this.contextReference.get()); apiResponse = peertubeAPI.updateVideo(peertube); - if( apiResponse != null && apiResponse.getPeertubes() != null && apiResponse.getPeertubes().size() > 0) + if (apiResponse != null && apiResponse.getPeertubes() != null && apiResponse.getPeertubes().size() > 0) apiResponse.getPeertubes().get(0).setUpdate(true); return null; } diff --git a/app/src/main/java/app/fedilab/android/asynctasks/PostStatusAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/PostStatusAsyncTask.java index 2b8ba2c32..eca84ff98 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/PostStatusAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/PostStatusAsyncTask.java @@ -48,7 +48,7 @@ public class PostStatusAsyncTask extends AsyncTask { private WeakReference contextReference; private UpdateAccountInfoAsyncTask.SOCIAL social; - public PostStatusAsyncTask(Context context, UpdateAccountInfoAsyncTask.SOCIAL social, Account account, app.fedilab.android.client.Entities.Status status, OnPostStatusActionInterface onPostStatusActionInterface){ + public PostStatusAsyncTask(Context context, UpdateAccountInfoAsyncTask.SOCIAL social, Account account, app.fedilab.android.client.Entities.Status status, OnPostStatusActionInterface onPostStatusActionInterface) { this.contextReference = new WeakReference<>(context); this.listener = onPostStatusActionInterface; this.status = status; @@ -59,28 +59,28 @@ public class PostStatusAsyncTask extends AsyncTask { @Override protected Void doInBackground(Void... params) { - if(social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA){ + if (social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { boolean isconnected = Helper.isConnectedToInternet(contextReference.get(), Helper.getLiveInstance(contextReference.get())); - if( isconnected) { + if (isconnected) { if (account == null) { apiResponse = new API(this.contextReference.get()).postStatusAction(status); } else apiResponse = new API(this.contextReference.get(), account.getInstance(), account.getToken()).postStatusAction(status); - }else { + } else { apiResponse = new APIResponse(); Error error = new Error(); error.setError(contextReference.get().getString(R.string.no_internet)); error.setStatusCode(-33); apiResponse.setError(error); } - }else { + } else { boolean isconnected = Helper.isConnectedToInternet(contextReference.get(), Helper.getLiveInstance(contextReference.get())); - if( isconnected) { + if (isconnected) { if (account == null) { apiResponse = new GNUAPI(this.contextReference.get()).postStatusAction(status); } else apiResponse = new GNUAPI(this.contextReference.get(), account.getInstance(), account.getToken()).postStatusAction(status); - }else { + } else { apiResponse = new APIResponse(); Error error = new Error(); error.setError(contextReference.get().getString(R.string.no_internet)); @@ -90,7 +90,6 @@ public class PostStatusAsyncTask extends AsyncTask { } - return null; } @@ -102,21 +101,21 @@ public class PostStatusAsyncTask extends AsyncTask { @Override public void run() { String content = status.getContent(); - if( content != null && content.length() > 0){ + if (content != null && content.length() > 0) { SQLiteDatabase db = Sqlite.getInstance(contextReference.get(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); Matcher matcher = Helper.hashtagPattern.matcher(content); - while (matcher.find()){ + while (matcher.find()) { int matchStart = matcher.start(1); int matchEnd = matcher.end(); //Get cached tags List cachedTag = new TagsCacheDAO(contextReference.get(), db).getAll(); String tag = content.substring(matchStart, matchEnd); - tag = tag.replace("#",""); - if( cachedTag == null){ + tag = tag.replace("#", ""); + if (cachedTag == null) { new TagsCacheDAO(contextReference.get(), db).insert(tag); - }else { + } else { //If cache doesn't contain the tag and the tag has upper case - if(!cachedTag.contains(tag) && !tag.toLowerCase().equals(tag)){ + if (!cachedTag.contains(tag) && !tag.toLowerCase().equals(tag)) { new TagsCacheDAO(contextReference.get(), db).insert(tag); } } diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RemoveAccountAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RemoveAccountAsyncTask.java index 07ed716a4..cb6fc7bb4 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RemoveAccountAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RemoveAccountAsyncTask.java @@ -34,7 +34,7 @@ public class RemoveAccountAsyncTask extends AsyncTask { private WeakReference activityReference; private Account account; - public RemoveAccountAsyncTask(Activity activity, Account account){ + public RemoveAccountAsyncTask(Activity activity, Account account) { activityReference = new WeakReference<>(activity); this.account = account; } diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveAccountAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveAccountAsyncTask.java index 3575dd528..6b6f03459 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveAccountAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveAccountAsyncTask.java @@ -42,7 +42,7 @@ public class RetrieveAccountAsyncTask extends AsyncTask { private Error error; private WeakReference contextReference; - public RetrieveAccountAsyncTask(Context context, String targetedId, OnRetrieveAccountInterface onRetrieveAccountInterface){ + public RetrieveAccountAsyncTask(Context context, String targetedId, OnRetrieveAccountInterface onRetrieveAccountInterface) { this.contextReference = new WeakReference<>(context); this.targetedId = targetedId; this.listener = onRetrieveAccountInterface; @@ -50,15 +50,15 @@ public class RetrieveAccountAsyncTask extends AsyncTask { @Override protected Void doInBackground(Void... params) { - if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { API api = new API(this.contextReference.get()); account = api.getAccount(targetedId); error = api.getError(); - }else if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { + } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { PeertubeAPI peertubeAPI = new PeertubeAPI(this.contextReference.get()); account = peertubeAPI.getAccount(targetedId); error = peertubeAPI.getError(); - }else if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU|| MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { GNUAPI gnuapi = new GNUAPI(this.contextReference.get()); account = gnuapi.getAccount(targetedId); error = gnuapi.getError(); diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveAccountInfoAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveAccountInfoAsyncTask.java index 90e5f8f7e..5d9f091a9 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveAccountInfoAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveAccountInfoAsyncTask.java @@ -36,7 +36,7 @@ public class RetrieveAccountInfoAsyncTask extends AsyncTask { private API api; private WeakReference contextReference; - public RetrieveAccountInfoAsyncTask(Context context, OnRetrieveAccountInterface onRetrieveAccountInterface){ + public RetrieveAccountInfoAsyncTask(Context context, OnRetrieveAccountInterface onRetrieveAccountInterface) { this.contextReference = new WeakReference<>(context); this.listener = onRetrieveAccountInterface; } diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveAccountsAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveAccountsAsyncTask.java index e5c857833..fb88ca2ef 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveAccountsAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveAccountsAsyncTask.java @@ -41,7 +41,7 @@ public class RetrieveAccountsAsyncTask extends AsyncTask { private WeakReference contextReference; private String instance, name; - public enum Type{ + public enum Type { BLOCKED, MUTED, FOLLOWING, @@ -53,7 +53,7 @@ public class RetrieveAccountsAsyncTask extends AsyncTask { GROUPS } - public RetrieveAccountsAsyncTask(Context context, String instance, String name, OnRetrieveAccountsInterface onRetrieveAccountsInterface){ + public RetrieveAccountsAsyncTask(Context context, String instance, String name, OnRetrieveAccountsInterface onRetrieveAccountsInterface) { this.contextReference = new WeakReference<>(context); this.instance = instance; this.name = name; @@ -61,7 +61,7 @@ public class RetrieveAccountsAsyncTask extends AsyncTask { this.action = Type.CHANNELS; } - public RetrieveAccountsAsyncTask(Context context, Type action, String targetedId, String max_id, OnRetrieveAccountsInterface onRetrieveAccountsInterface){ + public RetrieveAccountsAsyncTask(Context context, Type action, String targetedId, String max_id, OnRetrieveAccountsInterface onRetrieveAccountsInterface) { this.contextReference = new WeakReference<>(context); this.action = action; this.max_id = max_id; @@ -69,7 +69,7 @@ public class RetrieveAccountsAsyncTask extends AsyncTask { this.targetedId = targetedId; } - public RetrieveAccountsAsyncTask(Context context, Type action, String max_id, OnRetrieveAccountsInterface onRetrieveAccountsInterface){ + public RetrieveAccountsAsyncTask(Context context, Type action, String max_id, OnRetrieveAccountsInterface onRetrieveAccountsInterface) { this.contextReference = new WeakReference<>(context); this.action = action; this.max_id = max_id; @@ -80,16 +80,16 @@ public class RetrieveAccountsAsyncTask extends AsyncTask { protected Void doInBackground(Void... params) { API api = null; GNUAPI gnuapi = null; - if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) api = new API(this.contextReference.get()); else gnuapi = new GNUAPI(this.contextReference.get()); - switch (action){ + switch (action) { case REBLOGGED: - if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA){ + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { assert api != null; apiResponse = api.getRebloggedBy(targetedId, max_id); - }else { + } else { assert gnuapi != null; apiResponse = gnuapi.getRebloggedBy(targetedId, max_id); } @@ -99,47 +99,46 @@ public class RetrieveAccountsAsyncTask extends AsyncTask { apiResponse = api.search2(targetedId, API.searchType.ACCOUNTS, max_id); break; case FAVOURITED: - if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA){ + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { assert api != null; apiResponse = api.getFavouritedBy(targetedId, max_id); - }else { + } else { assert gnuapi != null; apiResponse = gnuapi.getFavouritedBy(targetedId, max_id); } break; case BLOCKED: - if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { assert api != null; apiResponse = api.getBlocks(max_id); - }else { + } else { assert gnuapi != null; apiResponse = gnuapi.getBlocks(max_id); } break; case MUTED: - if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { assert api != null; apiResponse = api.getMuted(max_id); - }else { + } else { assert gnuapi != null; apiResponse = gnuapi.getMuted(max_id); } break; case FOLLOWING: - if(MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { assert api != null; apiResponse = api.getFollowing(targetedId, max_id); - } - else { + } else { assert gnuapi != null; apiResponse = gnuapi.getFollowing(targetedId, max_id); } break; case FOLLOWERS: - if(MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { assert api != null; apiResponse = api.getFollowers(targetedId, max_id); - }else { + } else { assert gnuapi != null; apiResponse = gnuapi.getFollowers(targetedId, max_id); } diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveAccountsForReplyAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveAccountsForReplyAsyncTask.java index 24688eaa1..6a02c8910 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveAccountsForReplyAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveAccountsForReplyAsyncTask.java @@ -43,7 +43,7 @@ public class RetrieveAccountsForReplyAsyncTask extends AsyncTask accounts; private WeakReference contextReference; - public RetrieveAccountsForReplyAsyncTask(Context context, app.fedilab.android.client.Entities.Status status, OnRetrieveAccountsReplyInterface onRetrieveAccountsReplyInterface){ + public RetrieveAccountsForReplyAsyncTask(Context context, app.fedilab.android.client.Entities.Status status, OnRetrieveAccountsReplyInterface onRetrieveAccountsReplyInterface) { this.contextReference = new WeakReference<>(context); this.status = status; this.listener = onRetrieveAccountsReplyInterface; @@ -59,20 +59,20 @@ public class RetrieveAccountsForReplyAsyncTask extends AsyncTask 0 ) { + if (statusContext.getAncestors().size() > 0) { statusContext = api.getStatusContext(statusContext.getAncestors().get(0).getId()); } - if( statusContext != null && statusContext.getDescendants().size() > 0){ - for(app.fedilab.android.client.Entities.Status status : statusContext.getDescendants()){ - if( canBeAdded(status.getAccount().getAcct())){ + if (statusContext != null && statusContext.getDescendants().size() > 0) { + for (app.fedilab.android.client.Entities.Status status : statusContext.getDescendants()) { + if (canBeAdded(status.getAccount().getAcct())) { accounts.add(status.getAccount()); addedAccounts.add(status.getAccount().getAcct()); } } } - if( statusContext != null && statusContext.getAncestors().size() > 0){ - for(app.fedilab.android.client.Entities.Status status : statusContext.getAncestors()){ - if( canBeAdded(status.getAccount().getAcct())){ + if (statusContext != null && statusContext.getAncestors().size() > 0) { + for (app.fedilab.android.client.Entities.Status status : statusContext.getAncestors()) { + if (canBeAdded(status.getAccount().getAcct())) { accounts.add(status.getAccount()); addedAccounts.add(status.getAccount().getAcct()); } @@ -81,7 +81,7 @@ public class RetrieveAccountsForReplyAsyncTask extends AsyncTask { private Date dateIni; private Date dateEnd; - public RetrieveChartsAsyncTask(Context context, Date dateIni, Date dateEnd, OnRetrieveChartsInterface onRetrieveChartsInterface){ + public RetrieveChartsAsyncTask(Context context, Date dateIni, Date dateEnd, OnRetrieveChartsInterface onRetrieveChartsInterface) { this.contextReference = new WeakReference<>(context); this.listener = onRetrieveChartsInterface; this.dateIni = dateIni; diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveContextAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveContextAsyncTask.java index e2f10d3f9..5041d4f1f 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveContextAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveContextAsyncTask.java @@ -42,7 +42,7 @@ public class RetrieveContextAsyncTask extends AsyncTask { private boolean directtimeline; - public RetrieveContextAsyncTask(Context context, boolean expanded, boolean directtimeline, String statusId, OnRetrieveContextInterface onRetrieveContextInterface){ + public RetrieveContextAsyncTask(Context context, boolean expanded, boolean directtimeline, String statusId, OnRetrieveContextInterface onRetrieveContextInterface) { this.contextReference = new WeakReference<>(context); this.statusId = statusId; this.listener = onRetrieveContextInterface; @@ -52,7 +52,7 @@ public class RetrieveContextAsyncTask extends AsyncTask { @Override protected Void doInBackground(Void... params) { - if(MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { API api = new API(this.contextReference.get()); statusContext = api.getStatusContext(statusId); //Retrieves the first toot @@ -60,7 +60,7 @@ public class RetrieveContextAsyncTask extends AsyncTask { statusContext = api.getStatusContext(statusContext.getAncestors().get(0).getId()); } error = api.getError(); - }else{ + } else { GNUAPI gnuapi = new GNUAPI(this.contextReference.get()); statusContext = gnuapi.getStatusContext(statusId, directtimeline); //Retrieves the first toot diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveDomainsAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveDomainsAsyncTask.java index aa019c80d..627afe849 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveDomainsAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveDomainsAsyncTask.java @@ -37,7 +37,7 @@ public class RetrieveDomainsAsyncTask extends AsyncTask { private APIResponse apiResponse; private String max_id; - public RetrieveDomainsAsyncTask(Context context, String max_id, OnRetrieveDomainsInterface onRetrieveDomainsInterface){ + public RetrieveDomainsAsyncTask(Context context, String max_id, OnRetrieveDomainsInterface onRetrieveDomainsInterface) { this.contextReference = new WeakReference<>(context); this.listener = onRetrieveDomainsInterface; this.max_id = max_id; diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveEmojiAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveEmojiAsyncTask.java index c24657b37..b68eb1a63 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveEmojiAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveEmojiAsyncTask.java @@ -39,7 +39,7 @@ public class RetrieveEmojiAsyncTask extends AsyncTask { private OnRetrieveEmojiInterface listener; private WeakReference contextReference; - public RetrieveEmojiAsyncTask(Context context, String shortcode, OnRetrieveEmojiInterface onRetrieveEmojiInterface){ + public RetrieveEmojiAsyncTask(Context context, String shortcode, OnRetrieveEmojiInterface onRetrieveEmojiInterface) { this.contextReference = new WeakReference<>(context); this.shortcode = shortcode; this.listener = onRetrieveEmojiInterface; diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveFeedsAfterBookmarkAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveFeedsAfterBookmarkAsyncTask.java index 520f9d1bc..50d72cc39 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveFeedsAfterBookmarkAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveFeedsAfterBookmarkAsyncTask.java @@ -39,7 +39,7 @@ public class RetrieveFeedsAfterBookmarkAsyncTask extends AsyncTask(context); this.listener = onRetrieveFeedsAfterBookmarkInterface; this.max_id = max_id; diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveFeedsAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveFeedsAsyncTask.java index 2768354a9..ecfd032cb 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveFeedsAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveFeedsAsyncTask.java @@ -64,13 +64,13 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { private boolean showReply = false; private WeakReference contextReference; private FilterToots filterToots; - private String instanceName,remoteInstance, name; + private String instanceName, remoteInstance, name; private boolean cached = false; private int timelineId; private String currentfilter; private String social; - public enum Type{ + public enum Type { HOME, LOCAL, DIRECT, @@ -125,7 +125,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { } - public RetrieveFeedsAsyncTask(Context context, FilterToots filterToots, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface){ + public RetrieveFeedsAsyncTask(Context context, FilterToots filterToots, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface) { this.contextReference = new WeakReference<>(context); this.action = Type.CACHE_STATUS; this.max_id = max_id; @@ -134,14 +134,14 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { } - public RetrieveFeedsAsyncTask(Context context, Type action, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface){ + public RetrieveFeedsAsyncTask(Context context, Type action, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface) { this.contextReference = new WeakReference<>(context); this.action = action; this.max_id = max_id; this.listener = onRetrieveFeedsInterface; } - public RetrieveFeedsAsyncTask(Context context, Type action, String instanceName, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface){ + public RetrieveFeedsAsyncTask(Context context, Type action, String instanceName, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface) { this.contextReference = new WeakReference<>(context); this.action = action; this.max_id = max_id; @@ -149,7 +149,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { this.instanceName = instanceName; } - public RetrieveFeedsAsyncTask(Context context, Type action, int timelineId, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface){ + public RetrieveFeedsAsyncTask(Context context, Type action, int timelineId, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface) { this.contextReference = new WeakReference<>(context); this.action = action; this.max_id = max_id; @@ -157,7 +157,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { this.timelineId = timelineId; } - public RetrieveFeedsAsyncTask(Context context, Type action, String targetedID, String max_id, boolean showMediaOnly, boolean showPinned, OnRetrieveFeedsInterface onRetrieveFeedsInterface){ + public RetrieveFeedsAsyncTask(Context context, Type action, String targetedID, String max_id, boolean showMediaOnly, boolean showPinned, OnRetrieveFeedsInterface onRetrieveFeedsInterface) { this.contextReference = new WeakReference<>(context); this.action = action; this.max_id = max_id; @@ -166,7 +166,8 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { this.showMediaOnly = showMediaOnly; this.showPinned = showPinned; } - public RetrieveFeedsAsyncTask(Context context, Type action, String targetedID, String max_id, boolean showMediaOnly, boolean showPinned, boolean showReply, OnRetrieveFeedsInterface onRetrieveFeedsInterface){ + + public RetrieveFeedsAsyncTask(Context context, Type action, String targetedID, String max_id, boolean showMediaOnly, boolean showPinned, boolean showReply, OnRetrieveFeedsInterface onRetrieveFeedsInterface) { this.contextReference = new WeakReference<>(context); this.action = action; this.max_id = max_id; @@ -176,7 +177,8 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { this.showPinned = showPinned; this.showReply = showReply; } - public RetrieveFeedsAsyncTask(Context context, Type action, String tag, String targetedID, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface){ + + public RetrieveFeedsAsyncTask(Context context, Type action, String tag, String targetedID, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface) { this.contextReference = new WeakReference<>(context); this.action = action; this.max_id = max_id; @@ -185,7 +187,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { this.tag = tag; } - public RetrieveFeedsAsyncTask(Context context, String remoteInstance, String name, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface){ + public RetrieveFeedsAsyncTask(Context context, String remoteInstance, String name, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface) { this.contextReference = new WeakReference<>(context); this.remoteInstance = remoteInstance; this.max_id = max_id; @@ -194,7 +196,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { this.action = Type.REMOTE_INSTANCE; } - public RetrieveFeedsAsyncTask(Context context, RetrieveFeedsParam retrieveFeedsParam, OnRetrieveFeedsInterface onRetrieveFeedsInterface){ + public RetrieveFeedsAsyncTask(Context context, RetrieveFeedsParam retrieveFeedsParam, OnRetrieveFeedsInterface onRetrieveFeedsInterface) { this.contextReference = new WeakReference<>(context); this.listener = onRetrieveFeedsInterface; this.action = retrieveFeedsParam.getAction(); @@ -216,9 +218,9 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { protected Void doInBackground(Void... params) { API api = new API(this.contextReference.get()); SQLiteDatabase db = Sqlite.getInstance(this.contextReference.get(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - if( action == null ) + if (action == null) return null; - switch (action){ + switch (action) { case HOME: apiResponse = api.getHomeTimelineCache(max_id); break; @@ -241,70 +243,70 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { apiResponse = api.getConversationTimeline(max_id); break; case REMOTE_INSTANCE_FILTERED: - if( this.social != null && this.social.equals("MASTODON")) { - apiResponse = api.getPublicTimelineTag(this.currentfilter, true, max_id,this.remoteInstance); - if( apiResponse != null){ + if (this.social != null && this.social.equals("MASTODON")) { + apiResponse = api.getPublicTimelineTag(this.currentfilter, true, max_id, this.remoteInstance); + if (apiResponse != null) { List statusesTemp = apiResponse.getStatuses(); - if( statusesTemp != null){ - for(app.fedilab.android.client.Entities.Status status: statusesTemp){ + if (statusesTemp != null) { + for (app.fedilab.android.client.Entities.Status status : statusesTemp) { status.setType(action); } } } - } else if(this.social != null && this.social.equals("GNU") ) { + } else if (this.social != null && this.social.equals("GNU")) { GNUAPI gnuapi = new GNUAPI(this.contextReference.get()); - apiResponse = gnuapi.searchRemote(this.remoteInstance,currentfilter,max_id); - }else { + apiResponse = gnuapi.searchRemote(this.remoteInstance, currentfilter, max_id); + } else { apiResponse = api.searchPeertube(this.remoteInstance, currentfilter); } break; case REMOTE_INSTANCE: - if( this.name != null && this.remoteInstance != null){ //For Peertube channels + if (this.name != null && this.remoteInstance != null) { //For Peertube channels apiResponse = api.getPeertubeChannelVideos(this.remoteInstance, this.name); - }else{ //For other remote instance + } else { //For other remote instance List remoteInstanceObj = new InstancesDAO(this.contextReference.get(), db).getInstanceByName(this.instanceName); - if( remoteInstanceObj != null && remoteInstanceObj.size() > 0 && remoteInstanceObj.get(0).getType().equals("MASTODON")) { + if (remoteInstanceObj != null && remoteInstanceObj.size() > 0 && remoteInstanceObj.get(0).getType().equals("MASTODON")) { apiResponse = api.getPublicTimeline(this.instanceName, true, max_id); List statusesTemp = apiResponse.getStatuses(); - if( statusesTemp != null){ - for(app.fedilab.android.client.Entities.Status status: statusesTemp){ + if (statusesTemp != null) { + for (app.fedilab.android.client.Entities.Status status : statusesTemp) { status.setType(action); } } - }else if(remoteInstanceObj != null && remoteInstanceObj.size() > 0 && remoteInstanceObj.get(0).getType().equals("MISSKEY")){ + } else if (remoteInstanceObj != null && remoteInstanceObj.size() > 0 && remoteInstanceObj.get(0).getType().equals("MISSKEY")) { apiResponse = api.getMisskey(this.instanceName, max_id); List statusesTemp = apiResponse.getStatuses(); - if( statusesTemp != null){ - for(app.fedilab.android.client.Entities.Status status: statusesTemp){ + if (statusesTemp != null) { + for (app.fedilab.android.client.Entities.Status status : statusesTemp) { status.setType(action); } } - } else if(remoteInstanceObj != null && remoteInstanceObj.size() > 0 && remoteInstanceObj.get(0).getType().equals("PIXELFED") ) { + } else if (remoteInstanceObj != null && remoteInstanceObj.size() > 0 && remoteInstanceObj.get(0).getType().equals("PIXELFED")) { apiResponse = api.getPixelfedTimeline(instanceName, max_id); - } else if(remoteInstanceObj != null && remoteInstanceObj.size() > 0 && remoteInstanceObj.get(0).getType().equals("GNU") ) { + } else if (remoteInstanceObj != null && remoteInstanceObj.size() > 0 && remoteInstanceObj.get(0).getType().equals("GNU")) { apiResponse = api.getGNUTimeline(instanceName, max_id); - }else { + } else { apiResponse = api.getPeertube(this.instanceName, max_id); } } break; case FAVOURITES: - if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { apiResponse = api.getFavourites(max_id); - }else{ + } else { GNUAPI gnuapi = new GNUAPI(this.contextReference.get()); apiResponse = gnuapi.getFavourites(max_id); } break; case USER: - if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { if (showMediaOnly) apiResponse = api.getStatusWithMedia(targetedID, max_id); else if (showPinned) apiResponse = api.getPinnedStatuses(targetedID, max_id); else apiResponse = api.getAccountTLStatuses(targetedID, max_id, !showReply); - }else if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA){ + } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { GNUAPI gnuapi = new GNUAPI(this.contextReference.get()); if (showMediaOnly) apiResponse = gnuapi.getStatusWithMedia(targetedID, max_id); @@ -312,7 +314,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { apiResponse = gnuapi.getPinnedStatuses(targetedID, max_id); else apiResponse = gnuapi.getAccountTLStatuses(targetedID, max_id, !showReply); - }else if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE){ + } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { PeertubeAPI peertubeAPI = new PeertubeAPI(this.contextReference.get()); apiResponse = peertubeAPI.getVideos(targetedID, max_id); } @@ -334,20 +336,20 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { break; case SEARCH: - if( !tag.contains("_cache_")) { + if (!tag.contains("_cache_")) { apiResponse = api.search2(tag, API.searchType.STATUSES, max_id); - }else{ - tag = tag.replace("_cache_",""); + } else { + tag = tag.replace("_cache_", ""); apiResponse = new APIResponse(); Results results = new Results(); List statuses = new TimelineCacheDAO(contextReference.get(), db).search(tag, max_id); - if( statuses != null && statuses.size() > 0 ) { + if (statuses != null && statuses.size() > 0) { apiResponse.setMax_id(statuses.get(statuses.size() - 1).getId()); } List statusesNew = null; - if( statuses != null){ + if (statuses != null) { statusesNew = new ArrayList<>(); - for(app.fedilab.android.client.Entities.Status status: statuses){ + for (app.fedilab.android.client.Entities.Status status : statuses) { if (tag != null && !tag.contains("\"")) { String[] searches = tag.split(" "); for (String search : searches) { @@ -355,7 +357,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { statusesNew.add(status); } } - }else{ + } else { statusesNew.addAll(statuses); } } @@ -366,20 +368,20 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { } break; case TAG: - if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { ManageTimelines manageTimelines = new TimelinesDAO(contextReference.get(), db).getById(timelineId); - if( manageTimelines != null && manageTimelines.getTagTimeline() != null){ + if (manageTimelines != null && manageTimelines.getTagTimeline() != null) { boolean isArt = manageTimelines.getTagTimeline().isART(); if (isArt) - apiResponse = api.getCustomArtTimeline(false, manageTimelines.getTagTimeline().getName(), max_id, manageTimelines.getTagTimeline().getAny(), manageTimelines.getTagTimeline().getAll(), manageTimelines.getTagTimeline().getNone()); + apiResponse = api.getCustomArtTimeline(false, manageTimelines.getTagTimeline().getName(), max_id, manageTimelines.getTagTimeline().getAny(), manageTimelines.getTagTimeline().getAll(), manageTimelines.getTagTimeline().getNone()); else apiResponse = api.getPublicTimelineTag(manageTimelines.getTagTimeline().getName(), false, max_id, manageTimelines.getTagTimeline().getAny(), manageTimelines.getTagTimeline().getAll(), manageTimelines.getTagTimeline().getNone()); - }else{ + } else { apiResponse = api.getPublicTimelineTag(tag, false, max_id, null, null, null); } - }else{ + } else { GNUAPI gnuapi = new GNUAPI(this.contextReference.get()); - apiResponse = gnuapi.search(tag,max_id); + apiResponse = gnuapi.search(tag, max_id); } break; @@ -402,11 +404,11 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { apiResponse = new APIResponse(); db = Sqlite.getInstance(contextReference.get(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); statuses = new StatusCacheDAO(contextReference.get(), db).getStatusFromID(StatusCacheDAO.ARCHIVE_CACHE, filterToots, max_id); - if( statuses != null && statuses.size() > 0) { + if (statuses != null && statuses.size() > 0) { apiResponse.setStatuses(statuses); apiResponse.setSince_id(statuses.get(0).getId()); apiResponse.setMax_id(statuses.get(statuses.size() - 1).getId()); - }else{ + } else { apiResponse.setStatuses(null); apiResponse.setMax_id(null); apiResponse.setSince_id(null); @@ -443,10 +445,10 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { break; case PF_LOCAL: api = new API(this.contextReference.get()); - apiResponse = api.getPublicTimeline(true,max_id); + apiResponse = api.getPublicTimeline(true, max_id); case PF_DISCOVER: api = new API(this.contextReference.get()); - apiResponse = api.getDiscoverTimeline(true,max_id); + apiResponse = api.getDiscoverTimeline(true, max_id); break; case HASHTAG: break; @@ -457,11 +459,11 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { break; case GNU_LOCAL: gnuAPI = new GNUAPI(this.contextReference.get()); - apiResponse = gnuAPI.getPublicTimeline(true,max_id); + apiResponse = gnuAPI.getPublicTimeline(true, max_id); break; case GNU_WHOLE: gnuAPI = new GNUAPI(this.contextReference.get()); - apiResponse = gnuAPI.getPublicTimeline(false,max_id); + apiResponse = gnuAPI.getPublicTimeline(false, max_id); break; case GNU_DM: gnuAPI = new GNUAPI(this.contextReference.get()); @@ -472,7 +474,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { apiResponse = gnuAPI.getGroupTimeline(tag.trim(), max_id); break; } - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { List bookmarks = new StatusCacheDAO(contextReference.get(), db).getAllStatusId(StatusCacheDAO.BOOKMARK_CACHE); if (apiResponse != null && apiResponse.getStatuses() != null && bookmarks != null && apiResponse.getStatuses().size() > 0) { List statuses = apiResponse.getStatuses(); diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveFollowRequestSentAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveFollowRequestSentAsyncTask.java index 8cbc3f05b..c6bbb3885 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveFollowRequestSentAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveFollowRequestSentAsyncTask.java @@ -37,7 +37,7 @@ public class RetrieveFollowRequestSentAsyncTask extends AsyncTask contextReference; - public RetrieveFollowRequestSentAsyncTask(Context context, String max_id, OnRetrieveAccountsInterface onRetrieveAccountsInterface){ + public RetrieveFollowRequestSentAsyncTask(Context context, String max_id, OnRetrieveAccountsInterface onRetrieveAccountsInterface) { this.contextReference = new WeakReference<>(context); this.max_id = max_id; this.listener = onRetrieveAccountsInterface; diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveHowToAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveHowToAsyncTask.java index 7da41ec45..3c454802a 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveHowToAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveHowToAsyncTask.java @@ -16,6 +16,7 @@ package app.fedilab.android.asynctasks; import android.content.Context; import android.os.AsyncTask; + import java.lang.ref.WeakReference; import app.fedilab.android.client.API; @@ -36,8 +37,7 @@ public class RetrieveHowToAsyncTask extends AsyncTask { private WeakReference contextReference; - - public RetrieveHowToAsyncTask(Context context, OnRetrieveHowToInterface onRetrieveHowToInterface){ + public RetrieveHowToAsyncTask(Context context, OnRetrieveHowToInterface onRetrieveHowToInterface) { this.contextReference = new WeakReference<>(context); this.listener = onRetrieveHowToInterface; } diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveInstanceAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveInstanceAsyncTask.java index fb39f8ee6..099d62777 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveInstanceAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveInstanceAsyncTask.java @@ -35,7 +35,7 @@ public class RetrieveInstanceAsyncTask extends AsyncTask { private APIResponse apiResponse; private WeakReference contextReference; - public RetrieveInstanceAsyncTask(Context context, OnRetrieveInstanceInterface onRetrieveInstanceInterface){ + public RetrieveInstanceAsyncTask(Context context, OnRetrieveInstanceInterface onRetrieveInstanceInterface) { this.contextReference = new WeakReference<>(context); this.listener = onRetrieveInstanceInterface; } diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveInstanceRegAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveInstanceRegAsyncTask.java index e1c001b3e..7a1e74704 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveInstanceRegAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveInstanceRegAsyncTask.java @@ -36,7 +36,7 @@ public class RetrieveInstanceRegAsyncTask extends AsyncTask { private WeakReference contextReference; private String category; - public RetrieveInstanceRegAsyncTask(Context context, String category, OnRetrieveInstanceInterface onRetrieveInstanceInterface){ + public RetrieveInstanceRegAsyncTask(Context context, String category, OnRetrieveInstanceInterface onRetrieveInstanceInterface) { this.contextReference = new WeakReference<>(context); this.listener = onRetrieveInstanceInterface; this.category = category; diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveManyRelationshipsAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveManyRelationshipsAsyncTask.java index 94b38e6ab..735c6bfc2 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveManyRelationshipsAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveManyRelationshipsAsyncTask.java @@ -40,7 +40,7 @@ public class RetrieveManyRelationshipsAsyncTask extends AsyncTask contextReference; - public RetrieveManyRelationshipsAsyncTask(Context context, List accounts, OnRetrieveManyRelationshipsInterface onRetrieveManyRelationshipsInterface){ + public RetrieveManyRelationshipsAsyncTask(Context context, List accounts, OnRetrieveManyRelationshipsInterface onRetrieveManyRelationshipsInterface) { this.contextReference = new WeakReference<>(context); this.listener = onRetrieveManyRelationshipsInterface; this.accounts = accounts; @@ -48,7 +48,7 @@ public class RetrieveManyRelationshipsAsyncTask extends AsyncTask { private String image, title, description, sharedSubject, sharedText; private WeakReference contextWeakReference; private boolean shouldFetchMetaData = true; - public RetrieveMetaDataAsyncTask(Context context,boolean shouldFetchMetaData, String sharedSubject, String sharedText,String url, OnRetrieveMetaDataInterface onRetrieveRemoteAccountInterface){ + + public RetrieveMetaDataAsyncTask(Context context, boolean shouldFetchMetaData, String sharedSubject, String sharedText, String url, OnRetrieveMetaDataInterface onRetrieveRemoteAccountInterface) { this.url = url; this.listener = onRetrieveRemoteAccountInterface; this.sharedText = sharedText; @@ -56,12 +57,13 @@ public class RetrieveMetaDataAsyncTask extends AsyncTask { @Override protected Void doInBackground(Void... params) { - if(shouldFetchMetaData) + if (shouldFetchMetaData) return execRetrieveMetaDataInBackground(); else return null; } - private Void execRetrieveMetaDataInBackground(){ + + private Void execRetrieveMetaDataInBackground() { String potentialUrl = ""; if (url == null) { @@ -77,10 +79,10 @@ public class RetrieveMetaDataAsyncTask extends AsyncTask { matcher = Patterns.WEB_URL.matcher(url); else matcher = Helper.urlPattern.matcher(url); - while (matcher.find()){ + while (matcher.find()) { int matchStart = matcher.start(1); int matchEnd = matcher.end(); - if(matchStart < matchEnd && url.length() >= matchEnd) + if (matchStart < matchEnd && url.length() >= matchEnd) potentialUrl = url.substring(matchStart, matchEnd); } // If we actually have a URL then make use of it. @@ -103,15 +105,15 @@ public class RetrieveMetaDataAsyncTask extends AsyncTask { image = matcherImage.group(1); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - if( titleEncoded != null) + if (titleEncoded != null) title = Html.fromHtml(titleEncoded, Html.FROM_HTML_MODE_LEGACY).toString(); - if( descriptionEncoded != null) + if (descriptionEncoded != null) description = Html.fromHtml(descriptionEncoded, Html.FROM_HTML_MODE_LEGACY).toString(); - }else { + } else { //noinspection deprecation - if( titleEncoded != null) + if (titleEncoded != null) title = Html.fromHtml(titleEncoded).toString(); - if( descriptionEncoded != null) + if (descriptionEncoded != null) description = Html.fromHtml(descriptionEncoded).toString(); } } catch (NoSuchAlgorithmException e) { @@ -127,6 +129,7 @@ public class RetrieveMetaDataAsyncTask extends AsyncTask { } return null; } + @Override protected void onPostExecute(Void result) { listener.onRetrieveMetaData(error, sharedSubject, sharedText, image, title, description); diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveMissingFeedsAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveMissingFeedsAsyncTask.java index cfb04f3fd..6a3e72598 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveMissingFeedsAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveMissingFeedsAsyncTask.java @@ -51,14 +51,14 @@ public class RetrieveMissingFeedsAsyncTask extends AsyncTask { private String remoteInstance; private int timelineId; - public RetrieveMissingFeedsAsyncTask(Context context, String since_id, RetrieveFeedsAsyncTask.Type type, OnRetrieveMissingFeedsInterface onRetrieveMissingFeedsInterface){ + public RetrieveMissingFeedsAsyncTask(Context context, String since_id, RetrieveFeedsAsyncTask.Type type, OnRetrieveMissingFeedsInterface onRetrieveMissingFeedsInterface) { this.contextReference = new WeakReference<>(context); this.since_id = since_id; this.listener = onRetrieveMissingFeedsInterface; this.type = type; } - public RetrieveMissingFeedsAsyncTask(Context context, String remoteInstance, String since_id, RetrieveFeedsAsyncTask.Type type, OnRetrieveMissingFeedsInterface onRetrieveMissingFeedsInterface){ + public RetrieveMissingFeedsAsyncTask(Context context, String remoteInstance, String since_id, RetrieveFeedsAsyncTask.Type type, OnRetrieveMissingFeedsInterface onRetrieveMissingFeedsInterface) { this.contextReference = new WeakReference<>(context); this.since_id = since_id; this.listener = onRetrieveMissingFeedsInterface; @@ -66,7 +66,7 @@ public class RetrieveMissingFeedsAsyncTask extends AsyncTask { this.remoteInstance = remoteInstance; } - public RetrieveMissingFeedsAsyncTask(Context context, int timelineId, String since_id, RetrieveFeedsAsyncTask.Type type, OnRetrieveMissingFeedsInterface onRetrieveMissingFeedsInterface){ + public RetrieveMissingFeedsAsyncTask(Context context, int timelineId, String since_id, RetrieveFeedsAsyncTask.Type type, OnRetrieveMissingFeedsInterface onRetrieveMissingFeedsInterface) { this.contextReference = new WeakReference<>(context); this.since_id = since_id; this.listener = onRetrieveMissingFeedsInterface; @@ -77,9 +77,9 @@ public class RetrieveMissingFeedsAsyncTask extends AsyncTask { @Override protected Void doInBackground(Void... params) { - if( this.contextReference.get() == null) + if (this.contextReference.get() == null) return null; - if(MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { API api = new API(this.contextReference.get()); List tempStatus = null; APIResponse apiResponse = null; @@ -98,7 +98,7 @@ public class RetrieveMissingFeedsAsyncTask extends AsyncTask { else if (type == RetrieveFeedsAsyncTask.Type.TAG) { SQLiteDatabase db = Sqlite.getInstance(contextReference.get(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); ManageTimelines manageTimelines = new TimelinesDAO(contextReference.get(), db).getById(timelineId); - if( manageTimelines != null && manageTimelines.getTagTimeline() != null){ + if (manageTimelines != null && manageTimelines.getTagTimeline() != null) { TagTimeline tagTimeline = manageTimelines.getTagTimeline(); boolean isArt = tagTimeline.isART(); if (isArt) @@ -117,7 +117,7 @@ public class RetrieveMissingFeedsAsyncTask extends AsyncTask { if (conversations != null && conversations.size() > 0) { for (Conversation conversation : conversations) { app.fedilab.android.client.Entities.Status status = conversation.getLast_status(); - if( status != null) { + if (status != null) { List ppConversation = new ArrayList<>(); for (Account account : conversation.getAccounts()) ppConversation.add(account.getAvatar()); @@ -135,13 +135,13 @@ public class RetrieveMissingFeedsAsyncTask extends AsyncTask { if (type == RetrieveFeedsAsyncTask.Type.HOME && statuses.size() > 0) { MainActivity.lastHomeId = statuses.get(0).getId(); } - }else{ + } else { GNUAPI gnuapi = new GNUAPI(this.contextReference.get()); List tempStatus = null; APIResponse apiResponse = null; if (type == RetrieveFeedsAsyncTask.Type.GNU_HOME) { apiResponse = gnuapi.getHomeTimelineSinceId(since_id); - }else if (type == RetrieveFeedsAsyncTask.Type.GNU_LOCAL) + } else if (type == RetrieveFeedsAsyncTask.Type.GNU_LOCAL) apiResponse = gnuapi.getPublicTimelineSinceId(true, since_id); else if (type == RetrieveFeedsAsyncTask.Type.GNU_WHOLE) apiResponse = gnuapi.getPublicTimelineSinceId(false, since_id); diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveMissingNotificationsAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveMissingNotificationsAsyncTask.java index 1605c1cdd..d8ce86374 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveMissingNotificationsAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveMissingNotificationsAsyncTask.java @@ -44,7 +44,7 @@ public class RetrieveMissingNotificationsAsyncTask extends AsyncTask(context); this.since_id = since_id; this.listener = onRetrieveMissingNotifications; @@ -59,7 +59,7 @@ public class RetrieveMissingNotificationsAsyncTask extends AsyncTask 0) { + if (notifications != null && notifications.size() > 0) { MainActivity.lastNotificationId = notifications.get(0).getId(); } return null; @@ -67,7 +67,7 @@ public class RetrieveMissingNotificationsAsyncTask extends AsyncTask(context); this.listener = onRetrieveNotificationChartsInterface; this.dateIni = dateIni; diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveNotificationStatsAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveNotificationStatsAsyncTask.java index 306337da3..adeca8664 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveNotificationStatsAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveNotificationStatsAsyncTask.java @@ -38,7 +38,7 @@ public class RetrieveNotificationStatsAsyncTask extends AsyncTask contextReference; private StatisticsNotification statistics; - public RetrieveNotificationStatsAsyncTask(Context context, OnRetrieveNotificationStatsInterface onRetrieveNotificationStatsInterface){ + public RetrieveNotificationStatsAsyncTask(Context context, OnRetrieveNotificationStatsInterface onRetrieveNotificationStatsInterface) { this.contextReference = new WeakReference<>(context); this.listener = onRetrieveNotificationStatsInterface; } diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveNotificationsAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveNotificationsAsyncTask.java index fad539e3c..ccef8ebd9 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveNotificationsAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveNotificationsAsyncTask.java @@ -29,7 +29,6 @@ import app.fedilab.android.activities.MainActivity; import app.fedilab.android.interfaces.OnRetrieveNotificationsInterface; - /** * Created by Thomas on 28/04/2017. * Retrieves notifications on the instance @@ -47,7 +46,7 @@ public class RetrieveNotificationsAsyncTask extends AsyncTask private boolean display; private DisplayNotificationsFragment.Type type; - public RetrieveNotificationsAsyncTask(Context context, DisplayNotificationsFragment.Type type, boolean display, Account account, String max_id, OnRetrieveNotificationsInterface onRetrieveNotificationsInterface){ + public RetrieveNotificationsAsyncTask(Context context, DisplayNotificationsFragment.Type type, boolean display, Account account, String max_id, OnRetrieveNotificationsInterface onRetrieveNotificationsInterface) { this.contextReference = new WeakReference<>(context); this.max_id = max_id; this.listener = onRetrieveNotificationsInterface; @@ -60,7 +59,7 @@ public class RetrieveNotificationsAsyncTask extends AsyncTask @Override protected Void doInBackground(Void... params) { - if(MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { API api; if (account == null) { api = new API(this.contextReference.get()); @@ -73,7 +72,7 @@ public class RetrieveNotificationsAsyncTask extends AsyncTask api = new API(this.contextReference.get(), account.getInstance(), account.getToken()); apiResponse = api.getNotificationsSince(type, max_id, display); } - }else{ + } else { GNUAPI gnuapi; if (account == null) { gnuapi = new GNUAPI(this.contextReference.get()); diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveNotificationsCacheAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveNotificationsCacheAsyncTask.java index e7e645db5..1e30208e9 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveNotificationsCacheAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveNotificationsCacheAsyncTask.java @@ -43,7 +43,7 @@ public class RetrieveNotificationsCacheAsyncTask extends AsyncTask contextReference; private FilterNotifications filterNotifications; - public RetrieveNotificationsCacheAsyncTask(Context context, FilterNotifications filterNotifications, String max_id, OnRetrieveCacheNotificationsInterface onRetrieveNotificationsInterface){ + public RetrieveNotificationsCacheAsyncTask(Context context, FilterNotifications filterNotifications, String max_id, OnRetrieveCacheNotificationsInterface onRetrieveNotificationsInterface) { this.contextReference = new WeakReference<>(context); this.max_id = max_id; this.listener = onRetrieveNotificationsInterface; @@ -56,7 +56,7 @@ public class RetrieveNotificationsCacheAsyncTask extends AsyncTask notifications = new NotificationCacheDAO(contextReference.get(), db).getNotificationsFromID(filterNotifications, max_id); apiResponse = new APIResponse(); apiResponse.setNotifications(notifications); - if( notifications != null && notifications.size() > 0 ) { + if (notifications != null && notifications.size() > 0) { apiResponse.setMax_id(notifications.get(notifications.size() - 1).getId()); } return null; diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveOpenCollectiveAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveOpenCollectiveAsyncTask.java index c7f73626d..0eded47e7 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveOpenCollectiveAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveOpenCollectiveAsyncTask.java @@ -38,12 +38,12 @@ public class RetrieveOpenCollectiveAsyncTask extends AsyncTask private WeakReference contextReference; private Type type; - public enum Type{ + public enum Type { BACKERS, SPONSORS } - public RetrieveOpenCollectiveAsyncTask(Context context, Type type, OnRetrieveRemoteAccountInterface onRetrieveRemoteAccountInterface){ + public RetrieveOpenCollectiveAsyncTask(Context context, Type type, OnRetrieveRemoteAccountInterface onRetrieveRemoteAccountInterface) { this.type = type; this.listener = onRetrieveRemoteAccountInterface; this.contextReference = new WeakReference<>(context); diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrievePeertubeChannelsAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrievePeertubeChannelsAsyncTask.java index 250e305a1..946b453f7 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrievePeertubeChannelsAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrievePeertubeChannelsAsyncTask.java @@ -38,15 +38,12 @@ import app.fedilab.android.interfaces.OnRetrievePeertubeInterface; public class RetrievePeertubeChannelsAsyncTask extends AsyncTask { - private APIResponse apiResponse; private OnRetrievePeertubeInterface listener; private WeakReference contextReference; - - - public RetrievePeertubeChannelsAsyncTask(Context context, OnRetrievePeertubeInterface onRetrievePeertubeInterface){ + public RetrievePeertubeChannelsAsyncTask(Context context, OnRetrievePeertubeInterface onRetrievePeertubeInterface) { this.contextReference = new WeakReference<>(context); this.listener = onRetrievePeertubeInterface; } diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrievePeertubeInformationAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrievePeertubeInformationAsyncTask.java index 0f44d8571..d3acb2cf9 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrievePeertubeInformationAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrievePeertubeInformationAsyncTask.java @@ -32,13 +32,11 @@ import app.fedilab.android.client.PeertubeAPI; public class RetrievePeertubeInformationAsyncTask extends AsyncTask { - private WeakReference contextReference; public static PeertubeInformation peertubeInformation; - - public RetrievePeertubeInformationAsyncTask(Context context){ + public RetrievePeertubeInformationAsyncTask(Context context) { this.contextReference = new WeakReference<>(context); } diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrievePeertubeNotificationsAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrievePeertubeNotificationsAsyncTask.java index 13d44aae5..3b11a0629 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrievePeertubeNotificationsAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrievePeertubeNotificationsAsyncTask.java @@ -40,7 +40,7 @@ public class RetrievePeertubeNotificationsAsyncTask extends AsyncTask contextReference; - public RetrievePeertubeNotificationsAsyncTask(Context context, Account account, String max_id, OnRetrievePeertubeNotificationsInterface onRetrievePeertubeNotificationsInterface){ + public RetrievePeertubeNotificationsAsyncTask(Context context, Account account, String max_id, OnRetrievePeertubeNotificationsInterface onRetrievePeertubeNotificationsInterface) { this.contextReference = new WeakReference<>(context); this.max_id = max_id; this.listener = onRetrievePeertubeNotificationsInterface; @@ -51,11 +51,11 @@ public class RetrievePeertubeNotificationsAsyncTask extends AsyncTask private OnRetrieveFeedsInterface listener; private WeakReference contextReference; - public RetrievePeertubeSearchAsyncTask(Context context, String instance, String query, OnRetrieveFeedsInterface onRetrieveFeedsInterface){ + public RetrievePeertubeSearchAsyncTask(Context context, String instance, String query, OnRetrieveFeedsInterface onRetrieveFeedsInterface) { this.contextReference = new WeakReference<>(context); this.query = query; this.listener = onRetrieveFeedsInterface; diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrievePeertubeSingleAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrievePeertubeSingleAsyncTask.java index 1d0b4a3a4..640c8f4ac 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrievePeertubeSingleAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrievePeertubeSingleAsyncTask.java @@ -36,7 +36,6 @@ import app.fedilab.android.interfaces.OnRetrievePeertubeInterface; public class RetrievePeertubeSingleAsyncTask extends AsyncTask { - private APIResponse apiResponse; private String videoId; private OnRetrievePeertubeInterface listener; @@ -44,8 +43,7 @@ public class RetrievePeertubeSingleAsyncTask extends AsyncTask private String instanceName; - - public RetrievePeertubeSingleAsyncTask(Context context, String instanceName, String videoId, OnRetrievePeertubeInterface onRetrievePeertubeInterface){ + public RetrievePeertubeSingleAsyncTask(Context context, String instanceName, String videoId, OnRetrievePeertubeInterface onRetrievePeertubeInterface) { this.contextReference = new WeakReference<>(context); this.videoId = videoId; this.listener = onRetrievePeertubeInterface; @@ -53,20 +51,19 @@ public class RetrievePeertubeSingleAsyncTask extends AsyncTask } - @Override protected Void doInBackground(Void... params) { - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { API api = new API(this.contextReference.get()); apiResponse = api.getSinglePeertube(this.instanceName, videoId); - }else if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE){ + } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { PeertubeAPI peertubeAPI = new PeertubeAPI(this.contextReference.get()); SharedPreferences sharedpreferences = contextReference.get().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); apiResponse = peertubeAPI.getSinglePeertube(this.instanceName, videoId, token); - if (apiResponse.getPeertubes() != null && apiResponse.getPeertubes().size() > 0 && apiResponse.getPeertubes().get(0) != null) { + if (apiResponse.getPeertubes() != null && apiResponse.getPeertubes().size() > 0 && apiResponse.getPeertubes().get(0) != null) { String rate = new PeertubeAPI(this.contextReference.get()).getRating(videoId); - if( rate != null) + if (rate != null) apiResponse.getPeertubes().get(0).setMyRating(rate); } } diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrievePeertubeSingleCommentsAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrievePeertubeSingleCommentsAsyncTask.java index 7909e06d4..609c5182b 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrievePeertubeSingleCommentsAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrievePeertubeSingleCommentsAsyncTask.java @@ -32,7 +32,6 @@ import app.fedilab.android.interfaces.OnRetrievePeertubeInterface; public class RetrievePeertubeSingleCommentsAsyncTask extends AsyncTask { - private APIResponse apiResponse; private String videoId; private OnRetrievePeertubeInterface listener; @@ -40,8 +39,7 @@ public class RetrievePeertubeSingleCommentsAsyncTask extends AsyncTask(context); this.videoId = videoId; this.listener = onRetrievePeertubeInterface; @@ -49,7 +47,6 @@ public class RetrievePeertubeSingleCommentsAsyncTask extends AsyncTask { private Error error; private WeakReference contextReference; - public RetrieveRelationshipAsyncTask(Context context, String accountId, OnRetrieveRelationshipInterface onRetrieveRelationshipInterface){ + public RetrieveRelationshipAsyncTask(Context context, String accountId, OnRetrieveRelationshipInterface onRetrieveRelationshipInterface) { this.contextReference = new WeakReference<>(context); this.listener = onRetrieveRelationshipInterface; this.accountId = accountId; @@ -54,11 +54,11 @@ public class RetrieveRelationshipAsyncTask extends AsyncTask { API api = new API(this.contextReference.get()); relationship = api.getRelationship(accountId); error = api.getError(); - } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA){ + } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { GNUAPI gnuapi = new GNUAPI(this.contextReference.get()); relationship = gnuapi.getRelationship(accountId); error = gnuapi.getError(); - }else { + } else { PeertubeAPI api = new PeertubeAPI(this.contextReference.get()); relationship = new Relationship(); relationship.setFollowing(api.isFollowing(accountId)); diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveRelationshipQuickReplyAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveRelationshipQuickReplyAsyncTask.java index 0a14c9af4..e08978e9d 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveRelationshipQuickReplyAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveRelationshipQuickReplyAsyncTask.java @@ -39,7 +39,7 @@ public class RetrieveRelationshipQuickReplyAsyncTask extends AsyncTask contextReference; - public RetrieveRelationshipQuickReplyAsyncTask(Context context, app.fedilab.android.client.Entities.Status status, OnRetrieveRelationshipQuickReplyInterface onRetrieveRelationshipQuickReplyInterface){ + public RetrieveRelationshipQuickReplyAsyncTask(Context context, app.fedilab.android.client.Entities.Status status, OnRetrieveRelationshipQuickReplyInterface onRetrieveRelationshipQuickReplyInterface) { this.contextReference = new WeakReference<>(context); this.listener = onRetrieveRelationshipQuickReplyInterface; this.status = status; @@ -50,7 +50,7 @@ public class RetrieveRelationshipQuickReplyAsyncTask extends AsyncTask { private WeakReference contextReference; - public RetrieveRemoteDataAsyncTask(Context context, String username, String instance, OnRetrieveRemoteAccountInterface onRetrieveRemoteAccountInterface){ + public RetrieveRemoteDataAsyncTask(Context context, String username, String instance, OnRetrieveRemoteAccountInterface onRetrieveRemoteAccountInterface) { this.url = Helper.instanceWithProtocol(context, instance) + "/@" + username; this.listener = onRetrieveRemoteAccountInterface; this.contextReference = new WeakReference<>(context); } - public RetrieveRemoteDataAsyncTask(Context context, String url, OnRetrieveRemoteAccountInterface onRetrieveRemoteAccountInterface){ + public RetrieveRemoteDataAsyncTask(Context context, String url, OnRetrieveRemoteAccountInterface onRetrieveRemoteAccountInterface) { this.url = url; this.listener = onRetrieveRemoteAccountInterface; this.contextReference = new WeakReference<>(context); @@ -57,7 +57,7 @@ public class RetrieveRemoteDataAsyncTask extends AsyncTask { protected Void doInBackground(Void... params) { API api = new API(this.contextReference.get()); APIResponse apiResponse = api.search(this.url); - if( apiResponse.getResults() != null) + if (apiResponse.getResults() != null) results = apiResponse.getResults(); return null; } diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveScheduledTootsAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveScheduledTootsAsyncTask.java index 4ce34b93b..62da496e2 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveScheduledTootsAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveScheduledTootsAsyncTask.java @@ -50,7 +50,7 @@ public class RetrieveScheduledTootsAsyncTask extends AsyncTask private WeakReference contextReference; private DisplayScheduledTootsFragment.typeOfSchedule type; - public RetrieveScheduledTootsAsyncTask(Context context, DisplayScheduledTootsFragment.typeOfSchedule type, OnRetrieveScheduledTootsInterface onRetrieveScheduledTootsInterface){ + public RetrieveScheduledTootsAsyncTask(Context context, DisplayScheduledTootsFragment.typeOfSchedule type, OnRetrieveScheduledTootsInterface onRetrieveScheduledTootsInterface) { this.contextReference = new WeakReference<>(context); this.listener = onRetrieveScheduledTootsInterface; this.type = type; @@ -60,36 +60,36 @@ public class RetrieveScheduledTootsAsyncTask extends AsyncTask protected Void doInBackground(Void... params) { SQLiteDatabase db = Sqlite.getInstance(this.contextReference.get(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); //Retrieves job asked by the user - if( type == DisplayScheduledTootsFragment.typeOfSchedule.TOOT) + if (type == DisplayScheduledTootsFragment.typeOfSchedule.TOOT) storedStatuses = new StatusStoredDAO(this.contextReference.get(), db).getAllScheduled(); - else if(type == DisplayScheduledTootsFragment.typeOfSchedule.BOOST ) + else if (type == DisplayScheduledTootsFragment.typeOfSchedule.BOOST) storedStatuses = new BoostScheduleDAO(this.contextReference.get(), db).getAllScheduled(); //Retrieves real jobs still waiting Set jobRequests = null; - if( type == DisplayScheduledTootsFragment.typeOfSchedule.TOOT) + if (type == DisplayScheduledTootsFragment.typeOfSchedule.TOOT) jobRequests = JobManager.instance().getAllJobRequestsForTag(ScheduledTootsSyncJob.SCHEDULED_TOOT); - else if(type == DisplayScheduledTootsFragment.typeOfSchedule.BOOST ) + else if (type == DisplayScheduledTootsFragment.typeOfSchedule.BOOST) jobRequests = JobManager.instance().getAllJobRequestsForTag(ScheduledBoostsSyncJob.SCHEDULED_BOOST); int[] jobIds; - if( jobRequests != null && jobRequests.size() > 0 ){ + if (jobRequests != null && jobRequests.size() > 0) { int i = 0; jobIds = new int[jobRequests.size()]; - for(JobRequest jobRequest : jobRequests){ + for (JobRequest jobRequest : jobRequests) { jobIds[i] = jobRequest.getJobId(); i++; } - }else{ + } else { jobIds = new int[]{}; } - if( storedStatuses != null && storedStatuses.size() > 0 ){ - for(StoredStatus ss: storedStatuses){ - if (!Helper.isJobPresent(jobIds, ss.getJobId())){ + if (storedStatuses != null && storedStatuses.size() > 0) { + for (StoredStatus ss : storedStatuses) { + if (!Helper.isJobPresent(jobIds, ss.getJobId())) { //JobId is fixed to -1 which means an error occured (it was never sent) - if( type == DisplayScheduledTootsFragment.typeOfSchedule.TOOT) - new StatusStoredDAO(this.contextReference.get(), db).updateJobId(ss.getId(),-1); - else if(type == DisplayScheduledTootsFragment.typeOfSchedule.BOOST ) - new BoostScheduleDAO(this.contextReference.get(), db).updateJobId(ss.getId(),-1); + if (type == DisplayScheduledTootsFragment.typeOfSchedule.TOOT) + new StatusStoredDAO(this.contextReference.get(), db).updateJobId(ss.getId(), -1); + else if (type == DisplayScheduledTootsFragment.typeOfSchedule.BOOST) + new BoostScheduleDAO(this.contextReference.get(), db).updateJobId(ss.getId(), -1); } } //Lets time to update db before dispaying diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveSearchAccountsAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveSearchAccountsAsyncTask.java index 6641fac11..d07fdb512 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveSearchAccountsAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveSearchAccountsAsyncTask.java @@ -37,14 +37,14 @@ public class RetrieveSearchAccountsAsyncTask extends AsyncTask private WeakReference contextReference; private boolean following; - public RetrieveSearchAccountsAsyncTask(Context context, String query, OnRetrieveSearcAccountshInterface onRetrieveSearcAccountshInterface){ + public RetrieveSearchAccountsAsyncTask(Context context, String query, OnRetrieveSearcAccountshInterface onRetrieveSearcAccountshInterface) { this.contextReference = new WeakReference<>(context); this.query = query; this.listener = onRetrieveSearcAccountshInterface; this.following = false; } - public RetrieveSearchAccountsAsyncTask(Context context, String query, boolean following, OnRetrieveSearcAccountshInterface onRetrieveSearcAccountshInterface){ + public RetrieveSearchAccountsAsyncTask(Context context, String query, boolean following, OnRetrieveSearcAccountshInterface onRetrieveSearcAccountshInterface) { this.contextReference = new WeakReference<>(context); this.query = query; this.listener = onRetrieveSearcAccountshInterface; @@ -54,7 +54,7 @@ public class RetrieveSearchAccountsAsyncTask extends AsyncTask @Override protected Void doInBackground(Void... params) { API api = new API(this.contextReference.get()); - if( !following) + if (!following) apiResponse = api.searchAccounts(query, 20); else apiResponse = new API(contextReference.get()).searchAccounts(query, 20, true); @@ -63,7 +63,7 @@ public class RetrieveSearchAccountsAsyncTask extends AsyncTask @Override protected void onPostExecute(Void result) { - if( !following) + if (!following) listener.onRetrieveSearchAccounts(apiResponse); else listener.onRetrieveContact(apiResponse); diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveSearchAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveSearchAsyncTask.java index 43c4c5a3e..424d9adc9 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveSearchAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveSearchAsyncTask.java @@ -48,20 +48,20 @@ public class RetrieveSearchAsyncTask extends AsyncTask { private API.searchType type; private String max_id; - public RetrieveSearchAsyncTask(Context context, String query, OnRetrieveSearchInterface onRetrieveSearchInterface){ + public RetrieveSearchAsyncTask(Context context, String query, OnRetrieveSearchInterface onRetrieveSearchInterface) { this.contextReference = new WeakReference<>(context); this.query = query; this.listener = onRetrieveSearchInterface; } - public RetrieveSearchAsyncTask(Context context, String query, boolean tagsOnly, OnRetrieveSearchInterface onRetrieveSearchInterface){ + public RetrieveSearchAsyncTask(Context context, String query, boolean tagsOnly, OnRetrieveSearchInterface onRetrieveSearchInterface) { this.contextReference = new WeakReference<>(context); this.query = query; this.listener = onRetrieveSearchInterface; this.tagsOnly = tagsOnly; } - public RetrieveSearchAsyncTask(Context context, String query, API.searchType searchType, String max_id, OnRetrieveSearchInterface onRetrieveSearchInterface){ + public RetrieveSearchAsyncTask(Context context, String query, API.searchType searchType, String max_id, OnRetrieveSearchInterface onRetrieveSearchInterface) { this.contextReference = new WeakReference<>(context); this.query = query; this.listener = onRetrieveSearchInterface; @@ -76,39 +76,39 @@ public class RetrieveSearchAsyncTask extends AsyncTask { if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { API api = new API(this.contextReference.get()); String[] split = query.trim().split("@"); - if( split.length > 1 ){ + if (split.length > 1) { - String domain; - String username; - if( split.length == 2){ - username = split[0]; - domain = split[1]; - }else{ - username = split[1]; - domain = split[2]; - } - if( domain != null && username != null){ - InstanceNodeInfo node = api.getNodeInfo(domain); - String url = null; - if( node != null && node.getName() != null){ - switch (node.getName().trim()){ - case "MASTODON": - url = "https://" + domain + "/@" + username; - break; - case "PEERTUBE": - url = "https://" + domain + "/accounts/" + username; - break; - case "PIXELFED": - url = "https://" + domain + "/" + username; - break; - case "GNU": - url = "https://" + domain + "/profile/" + username; - break; - } - } - if( url != null) - query = url; - } + String domain; + String username; + if (split.length == 2) { + username = split[0]; + domain = split[1]; + } else { + username = split[1]; + domain = split[2]; + } + if (domain != null && username != null) { + InstanceNodeInfo node = api.getNodeInfo(domain); + String url = null; + if (node != null && node.getName() != null) { + switch (node.getName().trim()) { + case "MASTODON": + url = "https://" + domain + "/@" + username; + break; + case "PEERTUBE": + url = "https://" + domain + "/accounts/" + username; + break; + case "PIXELFED": + url = "https://" + domain + "/" + username; + break; + case "GNU": + url = "https://" + domain + "/profile/" + username; + break; + } + } + if (url != null) + query = url; + } } @@ -141,7 +141,7 @@ public class RetrieveSearchAsyncTask extends AsyncTask { GNUAPI gnuapi = new GNUAPI(this.contextReference.get()); apiResponse = gnuapi.search(query); } - }else{ + } else { API api = new API(this.contextReference.get()); apiResponse = api.search2(query, type, max_id); } diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveStatsAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveStatsAsyncTask.java index 8d9cf4ec3..89e41b74b 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveStatsAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveStatsAsyncTask.java @@ -17,7 +17,9 @@ package app.fedilab.android.asynctasks; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; + import java.lang.ref.WeakReference; + import app.fedilab.android.client.Entities.Statistics; import app.fedilab.android.interfaces.OnRetrieveStatsInterface; import app.fedilab.android.sqlite.Sqlite; @@ -36,7 +38,7 @@ public class RetrieveStatsAsyncTask extends AsyncTask { private WeakReference contextReference; private Statistics statistics; - public RetrieveStatsAsyncTask(Context context, OnRetrieveStatsInterface onRetrieveStatsInterface){ + public RetrieveStatsAsyncTask(Context context, OnRetrieveStatsInterface onRetrieveStatsInterface) { this.contextReference = new WeakReference<>(context); this.listener = onRetrieveStatsInterface; } diff --git a/app/src/main/java/app/fedilab/android/asynctasks/SyncTimelinesAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/SyncTimelinesAsyncTask.java index 814713cb6..3924f0f21 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/SyncTimelinesAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/SyncTimelinesAsyncTask.java @@ -51,7 +51,7 @@ public class SyncTimelinesAsyncTask extends AsyncTask { private WeakReference contextReference; private List manageTimelines; - public SyncTimelinesAsyncTask(Context context, int position, OnSyncTimelineInterface onSyncTimelineInterface){ + public SyncTimelinesAsyncTask(Context context, int position, OnSyncTimelineInterface onSyncTimelineInterface) { this.contextReference = new WeakReference<>(context); this.listener = onSyncTimelineInterface; this.position = position; @@ -65,7 +65,7 @@ public class SyncTimelinesAsyncTask extends AsyncTask { manageTimelines = new TimelinesDAO(contextReference.get(), db).getAllTimelines(); //First time that the timeline is created int i = 0; - if( manageTimelines == null || manageTimelines.size() == 0){ + if (manageTimelines == null || manageTimelines.size() == 0) { manageTimelines = new ArrayList<>(); //Add home TL ManageTimelines manageHome = new ManageTimelines(); @@ -99,7 +99,7 @@ public class SyncTimelinesAsyncTask extends AsyncTask { i++; manageTimelines.add(manageLocal); new TimelinesDAO(contextReference.get(), db).insert(manageLocal); - if(MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA){ + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { //Add Public TL ManageTimelines managePublic = new ManageTimelines(); managePublic.setDisplayed(true); @@ -109,7 +109,7 @@ public class SyncTimelinesAsyncTask extends AsyncTask { manageTimelines.add(managePublic); new TimelinesDAO(contextReference.get(), db).insert(managePublic); } - if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { //Add Public ART ManageTimelines manageArt = new ManageTimelines(); manageArt.setDisplayed(true); @@ -129,8 +129,8 @@ public class SyncTimelinesAsyncTask extends AsyncTask { } List tagTimelines = new SearchDAO(contextReference.get(), db).getAll(); - if( tagTimelines != null && tagTimelines.size() > 0 ){ - for(TagTimeline ttl: tagTimelines){ + if (tagTimelines != null && tagTimelines.size() > 0) { + for (TagTimeline ttl : tagTimelines) { //Add tag timelines ManageTimelines manageTagTimeline = new ManageTimelines(); manageTagTimeline.setDisplayed(true); @@ -143,8 +143,8 @@ public class SyncTimelinesAsyncTask extends AsyncTask { } } List instances = new InstancesDAO(contextReference.get(), db).getAllInstances(); - if( instances != null && instances.size() > 0 ){ - for(RemoteInstance ritl: instances){ + if (instances != null && instances.size() > 0) { + for (RemoteInstance ritl : instances) { //Add remote instances ManageTimelines manageRemoteTimline = new ManageTimelines(); manageRemoteTimline.setDisplayed(true); @@ -161,7 +161,7 @@ public class SyncTimelinesAsyncTask extends AsyncTask { List tagsInDb = new SearchDAO(contextReference.get(), db).getAll(); List instancesInDb = new InstancesDAO(contextReference.get(), db).getAllInstances(); - if( tagsInDb != null) { + if (tagsInDb != null) { for (TagTimeline tag : tagsInDb) { boolean isInDb = false; ManageTimelines timelines_tmp = null; @@ -188,36 +188,36 @@ public class SyncTimelinesAsyncTask extends AsyncTask { } } - for(ManageTimelines manageTimelines: manageTimelines){ - if( manageTimelines.getTagTimeline() == null ) + for (ManageTimelines manageTimelines : manageTimelines) { + if (manageTimelines.getTagTimeline() == null) continue; boolean shouldBeRemoved = true; - for(TagTimeline tag: tagsInDb){ - if( tag.getId() == manageTimelines.getTagTimeline().getId()){ + for (TagTimeline tag : tagsInDb) { + if (tag.getId() == manageTimelines.getTagTimeline().getId()) { shouldBeRemoved = false; } } - if( shouldBeRemoved){ + if (shouldBeRemoved) { new TimelinesDAO(contextReference.get(), db).remove(manageTimelines); } } } - if( instancesInDb != null){ - for(RemoteInstance instance: instancesInDb){ + if (instancesInDb != null) { + for (RemoteInstance instance : instancesInDb) { boolean isInDb = false; ManageTimelines timelines_tmp = null; - for(ManageTimelines manageTimeline: manageTimelines){ - if( manageTimeline.getRemoteInstance() == null ) + for (ManageTimelines manageTimeline : manageTimelines) { + if (manageTimeline.getRemoteInstance() == null) continue; - if(manageTimeline.getRemoteInstance().getHost().trim().equals(instance.getHost().trim())){ + if (manageTimeline.getRemoteInstance().getHost().trim().equals(instance.getHost().trim())) { isInDb = true; timelines_tmp = manageTimeline; break; } } - if( !isInDb){ + if (!isInDb) { ManageTimelines manageTL = new ManageTimelines(); manageTL.setRemoteInstance(instance); manageTL.setDisplayed(true); @@ -225,41 +225,41 @@ public class SyncTimelinesAsyncTask extends AsyncTask { manageTL.setPosition(manageTimelines.size()); new TimelinesDAO(contextReference.get(), db).insert(manageTL); manageTimelines.add(manageTL); - }else{ + } else { //Update list timelines_tmp.setRemoteInstance(instance); new TimelinesDAO(contextReference.get(), db).update(timelines_tmp); } } - for(ManageTimelines manageTimelines: manageTimelines){ - if( manageTimelines.getRemoteInstance() == null ) + for (ManageTimelines manageTimelines : manageTimelines) { + if (manageTimelines.getRemoteInstance() == null) continue; boolean shouldBeRemoved = true; - for(RemoteInstance instance: instancesInDb){ - if( instance.getHost().trim().equals(manageTimelines.getRemoteInstance().getHost().trim())){ + for (RemoteInstance instance : instancesInDb) { + if (instance.getHost().trim().equals(manageTimelines.getRemoteInstance().getHost().trim())) { shouldBeRemoved = false; } } - if( shouldBeRemoved){ + if (shouldBeRemoved) { new TimelinesDAO(contextReference.get(), db).remove(manageTimelines); } } } APIResponse apiResponse; - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { List listsAPI = null; try { apiResponse = new API(contextReference.get()).getLists(); listsAPI = apiResponse.getLists(); //Check potential duplicated lists in db - List duplicated_id = new ArrayList<>(); + List duplicated_id = new ArrayList<>(); List present_id = new ArrayList<>(); for (ManageTimelines manageTimeline : manageTimelines) { if (manageTimeline.getListTimeline() == null) continue; - if( !present_id.contains(manageTimeline.getListTimeline().getId())) { + if (!present_id.contains(manageTimeline.getListTimeline().getId())) { present_id.add(manageTimeline.getListTimeline().getId()); - }else{ + } else { duplicated_id.add(manageTimeline); new TimelinesDAO(contextReference.get(), db).remove(manageTimeline); } @@ -309,19 +309,19 @@ public class SyncTimelinesAsyncTask extends AsyncTask { manageTimelinesToRemove.add(dbtTimelines); } } - if( manageTimelinesToRemove.size() > 0 ){ + if (manageTimelinesToRemove.size() > 0) { manageTimelines.removeAll(manageTimelinesToRemove); } } else { //No lists, all are removed if exist in db ArrayList manageTimelinesToRemove = new ArrayList<>(); - if( apiResponse.getError() == null) { //Only done if there is no errors when fetching lists + if (apiResponse.getError() == null) { //Only done if there is no errors when fetching lists for (ManageTimelines manageTimelines : manageTimelines) { if (manageTimelines.getListTimeline() == null) continue; new TimelinesDAO(contextReference.get(), db).remove(manageTimelines); manageTimelinesToRemove.add(manageTimelines); } - if( manageTimelinesToRemove.size() > 0 ){ + if (manageTimelinesToRemove.size() > 0) { manageTimelines.removeAll(manageTimelinesToRemove); } } @@ -329,7 +329,7 @@ public class SyncTimelinesAsyncTask extends AsyncTask { } catch (Exception ignored) { } } - for (Iterator it = manageTimelines.iterator(); it.hasNext();) { + for (Iterator it = manageTimelines.iterator(); it.hasNext(); ) { if (!it.next().isDisplayed()) { it.remove(); } diff --git a/app/src/main/java/app/fedilab/android/asynctasks/UpdateAccountInfoAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/UpdateAccountInfoAsyncTask.java index 28505c204..190ab6417 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/UpdateAccountInfoAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/UpdateAccountInfoAsyncTask.java @@ -46,7 +46,7 @@ public class UpdateAccountInfoAsyncTask extends AsyncTask { private WeakReference contextReference; private SOCIAL social; - public enum SOCIAL{ + public enum SOCIAL { MASTODON, PEERTUBE, PIXELFED, @@ -54,7 +54,8 @@ public class UpdateAccountInfoAsyncTask extends AsyncTask { GNU, FRIENDICA } - public UpdateAccountInfoAsyncTask(Context context, String token, String client_id, String client_secret, String refresh_token, String instance, SOCIAL social){ + + public UpdateAccountInfoAsyncTask(Context context, String token, String client_id, String client_secret, String refresh_token, String instance, SOCIAL social) { this.contextReference = new WeakReference<>(context); this.token = token; this.instance = instance; @@ -67,17 +68,17 @@ public class UpdateAccountInfoAsyncTask extends AsyncTask { @Override protected Void doInBackground(Void... params) { Account account; - if( social == SOCIAL.MASTODON || social == SOCIAL.PIXELFED) { + if (social == SOCIAL.MASTODON || social == SOCIAL.PIXELFED) { account = new API(this.contextReference.get(), instance, null).verifyCredentials(); - if( account != null) + if (account != null) account.setSocial(account.getSocial()); - }else if( social == SOCIAL.PEERTUBE) { + } else if (social == SOCIAL.PEERTUBE) { account = new PeertubeAPI(this.contextReference.get(), instance, null).verifyCredentials(); - if( account != null) + if (account != null) account.setSocial("PEERTUBE"); - }else{ + } else { account = new GNUAPI(this.contextReference.get(), instance, null).verifyCredentials(); - if( account != null) + if (account != null) account.setSocial(account.getSocial()); } if (account == null) @@ -85,7 +86,8 @@ public class UpdateAccountInfoAsyncTask extends AsyncTask { try { //At the state the instance can be encoded instance = URLDecoder.decode(instance, "utf-8"); - } catch (UnsupportedEncodingException ignored) {} + } catch (UnsupportedEncodingException ignored) { + } SharedPreferences sharedpreferences = this.contextReference.get().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); account.setToken(token); @@ -101,10 +103,10 @@ public class UpdateAccountInfoAsyncTask extends AsyncTask { editor.putBoolean(Helper.PREF_IS_ADMINISTRATOR, account.isAdmin()); editor.putString(Helper.PREF_INSTANCE, instance); editor.apply(); - if( userExists) + if (userExists) new AccountDAO(this.contextReference.get(), db).updateAccountCredential(account); else { - if( account.getUsername() != null && account.getCreated_at() != null) + if (account.getUsername() != null && account.getCreated_at() != null) new AccountDAO(this.contextReference.get(), db).insertAccount(account); } @@ -114,7 +116,7 @@ public class UpdateAccountInfoAsyncTask extends AsyncTask { @Override protected void onPostExecute(Void result) { - if( this.contextReference.get() != null) { + if (this.contextReference.get() != null) { Intent mainActivity = new Intent(this.contextReference.get(), MainActivity.class); mainActivity.putExtra(Helper.INTENT_ACTION, Helper.ADD_USER_INTENT); this.contextReference.get().startActivity(mainActivity); diff --git a/app/src/main/java/app/fedilab/android/asynctasks/UpdateAccountInfoByIDAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/UpdateAccountInfoByIDAsyncTask.java index 22847e817..48e2c2dd8 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/UpdateAccountInfoByIDAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/UpdateAccountInfoByIDAsyncTask.java @@ -45,7 +45,7 @@ public class UpdateAccountInfoByIDAsyncTask extends AsyncTask private WeakReference contextReference; private UpdateAccountInfoAsyncTask.SOCIAL social; - public UpdateAccountInfoByIDAsyncTask(Context context, UpdateAccountInfoAsyncTask.SOCIAL social, OnUpdateAccountInfoInterface onUpdateAccountInfoInterface){ + public UpdateAccountInfoByIDAsyncTask(Context context, UpdateAccountInfoAsyncTask.SOCIAL social, OnUpdateAccountInfoInterface onUpdateAccountInfoInterface) { this.contextReference = new WeakReference<>(context); this.listener = onUpdateAccountInfoInterface; this.social = social; @@ -58,29 +58,29 @@ public class UpdateAccountInfoByIDAsyncTask extends AsyncTask String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, null); Account account = null; - if( social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) + if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) account = new API(this.contextReference.get()).verifyCredentials(); - else if( social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { + else if (social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { account = new PeertubeAPI(this.contextReference.get()).verifyCredentials(); account.setSocial("PEERTUBE"); - }else if ( social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA){ + } else if (social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { account = new GNUAPI(this.contextReference.get()).verifyCredentials(); } - if( account == null) + if (account == null) return null; account.setInstance(Helper.getLiveInstance(contextReference.get())); SQLiteDatabase db = Sqlite.getInstance(this.contextReference.get(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); boolean userExists = new AccountDAO(this.contextReference.get(), db).userExist(account); - if( userExists) { + if (userExists) { Account accountDb = new AccountDAO(this.contextReference.get(), db).getUniqAccount(userId, instance); - if( accountDb != null){ + if (accountDb != null) { account.setInstance(accountDb.getInstance()); account.setToken(accountDb.getToken()); new AccountDAO(this.contextReference.get(), db).updateAccountCredential(account); } } - if( social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { + if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { try { APIResponse response = new API(contextReference.get()).getCustomEmoji(); if (response != null && response.getEmojis() != null && response.getEmojis().size() > 0) { diff --git a/app/src/main/java/app/fedilab/android/asynctasks/UpdateCredentialAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/UpdateCredentialAsyncTask.java index b962ff769..8d4e0d3cb 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/UpdateCredentialAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/UpdateCredentialAsyncTask.java @@ -42,7 +42,7 @@ public class UpdateCredentialAsyncTask extends AsyncTask { private WeakReference contextReference; private HashMap customFields; - public UpdateCredentialAsyncTask(Context context, HashMap customFields, String display_name, String note, ByteArrayInputStream avatar, String avatarName, ByteArrayInputStream header, String headerName, API.accountPrivacy privacy, boolean senstive, OnUpdateCredentialInterface onUpdateCredentialInterface){ + public UpdateCredentialAsyncTask(Context context, HashMap customFields, String display_name, String note, ByteArrayInputStream avatar, String avatarName, ByteArrayInputStream header, String headerName, API.accountPrivacy privacy, boolean senstive, OnUpdateCredentialInterface onUpdateCredentialInterface) { this.contextReference = new WeakReference<>(context); this.display_name = display_name; this.note = note; diff --git a/app/src/main/java/app/fedilab/android/asynctasks/UpdateDescriptionAttachmentAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/UpdateDescriptionAttachmentAsyncTask.java index 7d163bf54..4fb519c18 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/UpdateDescriptionAttachmentAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/UpdateDescriptionAttachmentAsyncTask.java @@ -39,7 +39,7 @@ public class UpdateDescriptionAttachmentAsyncTask extends AsyncTask contextReference; - public UpdateDescriptionAttachmentAsyncTask(Context context, String mediaId, String description, Account account, OnRetrieveAttachmentInterface onRetrieveAttachmentInterface){ + public UpdateDescriptionAttachmentAsyncTask(Context context, String mediaId, String description, Account account, OnRetrieveAttachmentInterface onRetrieveAttachmentInterface) { this.contextReference = new WeakReference<>(context); this.listener = onRetrieveAttachmentInterface; this.description = description; @@ -49,7 +49,7 @@ public class UpdateDescriptionAttachmentAsyncTask extends AsyncTask. */ package app.fedilab.android.asynctasks; + import android.content.Context; import android.os.AsyncTask; + import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; @@ -36,7 +38,7 @@ public class WhoToFollowAsyncTask extends AsyncTask { private OnRetrieveWhoToFollowInterface listener; private WeakReference contextReference; - public WhoToFollowAsyncTask(Context context, String name, OnRetrieveWhoToFollowInterface onRetrieveWhoToFollowInterface){ + public WhoToFollowAsyncTask(Context context, String name, OnRetrieveWhoToFollowInterface onRetrieveWhoToFollowInterface) { this.contextReference = new WeakReference<>(context); this.name = name; this.listener = onRetrieveWhoToFollowInterface; @@ -46,7 +48,7 @@ public class WhoToFollowAsyncTask extends AsyncTask { @Override protected Void doInBackground(Void... params) { API api = new API(this.contextReference.get()); - if( name != null) + if (name != null) response = api.getCommunitywikiList(name); else response = api.getCommunitywikiList(); @@ -55,11 +57,11 @@ public class WhoToFollowAsyncTask extends AsyncTask { @Override protected void onPostExecute(Void result) { - if( name == null) + if (name == null) listener.onRetrieveWhoToFollowList(response); else { List trunkAccounts = null; - if(response != null) { + if (response != null) { trunkAccounts = new ArrayList<>(); for (String res : response) { TrunkAccount trunkAccount = new TrunkAccount(); diff --git a/app/src/main/java/app/fedilab/android/client/API.java b/app/src/main/java/app/fedilab/android/client/API.java index 73be43b27..6d02f05d6 100644 --- a/app/src/main/java/app/fedilab/android/client/API.java +++ b/app/src/main/java/app/fedilab/android/client/API.java @@ -95,7 +95,6 @@ import app.fedilab.android.sqlite.TimelineCacheDAO; public class API { - private Account account; private Context context; private Results results; @@ -111,14 +110,14 @@ public class API { private Error APIError; private List domains; - public enum searchType{ + public enum searchType { TAGS, STATUSES, ACCOUNTS } - public enum adminAction{ + public enum adminAction { ENABLE, APPROVE, REJECT, @@ -139,7 +138,7 @@ public class API { } - public enum StatusAction{ + public enum StatusAction { FAVOURITE, UNFAVOURITE, REBLOG, @@ -185,7 +184,7 @@ public class API { public API(Context context) { this.context = context; - if( context == null) { + if (context == null) { APIError = new Error(); return; } @@ -194,14 +193,14 @@ public class API { accountPerPage = Helper.ACCOUNTS_PER_PAGE; notificationPerPage = Helper.NOTIFICATIONS_PER_PAGE; this.prefKeyOauthTokenT = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); - if( Helper.getLiveInstance(context) != null) + if (Helper.getLiveInstance(context) != null) this.instance = Helper.getLiveInstance(context); else { SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(context)); Account account = new AccountDAO(context, db).getUniqAccount(userId, instance); - if( account == null) { + if (account == null) { APIError = new Error(); APIError.setError(context.getString(R.string.toast_error)); return; @@ -215,19 +214,20 @@ public class API { /** * Execute admin get actions + * * @param action type of the action - * @param id String can for an account or a status + * @param id String can for an account or a status * @return APIResponse */ - public APIResponse adminGet(adminAction action, String id, AdminAction adminAction){ + public APIResponse adminGet(adminAction action, String id, AdminAction adminAction) { apiResponse = new APIResponse(); HashMap params = null; String endpoint = null; String url_action = null; - switch (action){ + switch (action) { case GET_ACCOUNTS: params = new HashMap<>(); - if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { if (adminAction.isLocal()) params.put("local", String.valueOf(adminAction.isLocal())); if (adminAction.isRemote()) @@ -243,25 +243,26 @@ public class API { if (adminAction.isSuspended()) params.put("suspended", String.valueOf(adminAction.isSuspended())); endpoint = "/admin/accounts"; - }else if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA){ + } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { if (adminAction.isLocal()) - params.put("filters","local"); + params.put("filters", "local"); if (adminAction.isRemote()) - params.put("filters","external"); + params.put("filters", "external"); if (adminAction.isActive()) - params.put("filters","active"); + params.put("filters", "active"); if (adminAction.isDisabled()) - params.put("filters","deactivated"); + params.put("filters", "deactivated"); endpoint = "/admin/users"; } break; case GET_ONE_ACCOUNT: - if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { endpoint = String.format("/admin/accounts/%s", id); - }else { + } else { try { id = URLEncoder.encode(id, "UTF-8"); - } catch (UnsupportedEncodingException e) { } + } catch (UnsupportedEncodingException e) { + } params = new HashMap<>(); params.put("query", id); endpoint = "/admin/users"; @@ -270,16 +271,16 @@ public class API { break; case GET_REPORTS: endpoint = "/admin/reports"; - if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { - if( !adminAction.isUnresolved()) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { + if (!adminAction.isUnresolved()) { params = new HashMap<>(); params.put("resolved", "present"); } - }else if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { - if( adminAction.isUnresolved()) { + } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { + if (adminAction.isUnresolved()) { params = new HashMap<>(); params.put("state", "open"); - }else{ + } else { params = new HashMap<>(); params.put("state", "resolved"); } @@ -289,13 +290,13 @@ public class API { endpoint = String.format("/admin/reports/%s", id); break; } - if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { url_action = getAbsoluteUrl(endpoint); - }else if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { + } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { url_action = Helper.instanceWithProtocol(this.context, this.instance) + "/api/pleroma" + endpoint; } - if( url_action == null){ + if (url_action == null) { apiResponse = new APIResponse(); APIError = new Error(); APIError.setError(context.getString(R.string.toast_error)); @@ -304,29 +305,29 @@ public class API { } try { String response = new HttpsConnection(context, this.instance).get(url_action, 10, params, prefKeyOauthTokenT); - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA){ - if( new JSONObject(response).has("users") ) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { + if (new JSONObject(response).has("users")) { response = new JSONArray(new JSONObject(response).getJSONArray("users").toString()).toString(); - }else if( new JSONObject(response).has("reports") ) { + } else if (new JSONObject(response).has("reports")) { response = new JSONArray(new JSONObject(response).getJSONArray("reports").toString()).toString(); } } - switch (action){ + switch (action) { case GET_ACCOUNTS: List accountAdmins = parseAccountAdminResponse(new JSONArray(response)); apiResponse.setAccountAdmins(accountAdmins); break; case GET_ONE_ACCOUNT: - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { accountAdmins = parseAccountAdminResponse(new JSONArray(response)); - if( accountAdmins != null && accountAdmins.size() > 0) { + if (accountAdmins != null && accountAdmins.size() > 0) { Account accountpleroma = getAccount(accountAdmins.get(0).getId()); if (accountpleroma != null) { accountAdmins.get(0).setAccount(accountpleroma); } } - }else{ + } else { AccountAdmin accountAdmin = parseAccountAdminResponse(context, new JSONObject(response)); accountAdmins = new ArrayList<>(); accountAdmins.add(accountAdmin); @@ -362,23 +363,24 @@ public class API { /** * Execute admin post actions + * * @param action type of the action - * @param id String can for an account or a status + * @param id String can for an account or a status * @return APIResponse */ - public APIResponse adminDo(adminAction action, String id, AdminAction adminAction){ + public APIResponse adminDo(adminAction action, String id, AdminAction adminAction) { apiResponse = new APIResponse(); String http_action = "POST"; String endpoint = null; String url_action = null; HashMap params = null; - switch (action){ + switch (action) { case ENABLE: - if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { endpoint = String.format("/admin/accounts/%s/enable", id); - }else if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { + } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { http_action = "PATCH"; - endpoint = String.format( "/admin/users/%s/toggle_activation", id); + endpoint = String.format("/admin/users/%s/toggle_activation", id); } break; case APPROVE: @@ -400,62 +402,62 @@ public class API { endpoint = String.format("/admin/reports/%s/unassign", id); break; case REOPEN: - if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { endpoint = String.format("/admin/reports/%s/reopen", id); - }else if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { + } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { endpoint = String.format("/admin/reports/%s", id); params = new HashMap<>(); - params.put("state","open"); + params.put("state", "open"); http_action = "PUT"; } break; case RESOLVE: - if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { endpoint = String.format("/admin/reports/%s/resolve", id); - }else if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { + } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { endpoint = String.format("/admin/reports/%s", id); params = new HashMap<>(); - params.put("state","resolved"); + params.put("state", "resolved"); http_action = "PUT"; } break; case NONE: params = new HashMap<>(); - params.put("type","none"); + params.put("type", "none"); endpoint = String.format("/admin/accounts/%s/action", id); params.put("send_email_notification", String.valueOf(adminAction.isSend_email_notification())); - if( adminAction.getText() != null) { + if (adminAction.getText() != null) { params.put("text", adminAction.getText()); } break; case DISABLE: - if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { params = new HashMap<>(); - params.put("type","disable"); + params.put("type", "disable"); endpoint = String.format("/admin/accounts/%s/action", id); params.put("send_email_notification", String.valueOf(adminAction.isSend_email_notification())); - if( adminAction.getText() != null) { + if (adminAction.getText() != null) { params.put("text", adminAction.getText()); } - }else if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { + } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { http_action = "PATCH"; - endpoint = String.format( "/admin/users/%s/toggle_activation", id); + endpoint = String.format("/admin/users/%s/toggle_activation", id); } break; case SILENCE: params = new HashMap<>(); - params.put("type","silence"); + params.put("type", "silence"); endpoint = String.format("/admin/accounts/%s/action", id); params.put("send_email_notification", String.valueOf(adminAction.isSend_email_notification())); - if( adminAction.getText() != null) { + if (adminAction.getText() != null) { params.put("text", adminAction.getText()); } break; case SUSPEND: - if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { params = new HashMap<>(); params.put("type", "suspend"); endpoint = String.format("/admin/accounts/%s/action", id); @@ -463,7 +465,7 @@ public class API { if (adminAction.getText() != null) { params.put("text", adminAction.getText()); } - }else if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { + } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { http_action = "DELETE"; endpoint = "/admin/users"; params = new HashMap<>(); @@ -471,10 +473,10 @@ public class API { } break; } - if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { url_action = getAbsoluteUrl(endpoint); - }else if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { + } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { url_action = Helper.instanceWithProtocol(this.context, this.instance) + "/api/pleroma" + endpoint; } try { @@ -493,12 +495,12 @@ public class API { new HttpsConnection(context, this.instance).delete(url_action, 10, params, prefKeyOauthTokenT); break; } - switch (action){ + switch (action) { case ENABLE: case APPROVE: case REJECT: case UNSILENCE: - // case UNDISABLE: + // case UNDISABLE: case UNSUSPEND: List accountAdmins = null; try { @@ -572,11 +574,11 @@ public class API { return apiResponse; } - public InstanceNodeInfo getNodeInfo(String domain){ + public InstanceNodeInfo getNodeInfo(String domain) { //Try to guess URL scheme for the onion instance String scheme = "https"; - if( domain.endsWith(".onion")){ + if (domain.endsWith(".onion")) { try { new HttpsConnection(context, domain).get("http://" + domain, 30, null, null); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); @@ -600,12 +602,12 @@ public class API { String response; InstanceNodeInfo instanceNodeInfo = new InstanceNodeInfo(); try { - response = new HttpsConnection(context, domain).get(scheme+"://" + domain + "/.well-known/nodeinfo", 30, null, null); + response = new HttpsConnection(context, domain).get(scheme + "://" + domain + "/.well-known/nodeinfo", 30, null, null); JSONArray jsonArray = new JSONObject(response).getJSONArray("links"); ArrayList nodeInfos = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ){ + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); NodeInfo nodeInfo = new NodeInfo(); @@ -614,24 +616,24 @@ public class API { i++; nodeInfos.add(nodeInfo); } - if( nodeInfos.size() > 0){ - NodeInfo nodeInfo = nodeInfos.get(nodeInfos.size()-1); + if (nodeInfos.size() > 0) { + NodeInfo nodeInfo = nodeInfos.get(nodeInfos.size() - 1); response = new HttpsConnection(context, this.instance).get(nodeInfo.getHref(), 30, null, null); JSONObject resobj = new JSONObject(response); JSONObject jsonObject = resobj.getJSONObject("software"); - String name= null; - if( resobj.has("metadata") && resobj.getJSONObject("metadata").has("features") ) { + String name = null; + if (resobj.has("metadata") && resobj.getJSONObject("metadata").has("features")) { JSONArray features = resobj.getJSONObject("metadata").getJSONArray("features"); - if( features != null && features.length() > 0){ - for( int counter = 0; counter < features.length(); counter++ ) { - if( features.getString(counter).toUpperCase().equals("MASTODON_API") ) { + if (features != null && features.length() > 0) { + for (int counter = 0; counter < features.length(); counter++) { + if (features.getString(counter).toUpperCase().equals("MASTODON_API")) { name = "MASTODON"; break; } } } } - if( name == null) { + if (name == null) { name = jsonObject.getString("name").toUpperCase(); if (jsonObject.getString("name") != null) { switch (jsonObject.getString("name").toUpperCase()) { @@ -663,7 +665,7 @@ public class API { e.printStackTrace(); } catch (HttpsConnection.HttpsConnectionException e) { try { - response = new HttpsConnection(context, this.instance).get(scheme+"://" + domain + "/api/v1/instance", 30, null, null); + response = new HttpsConnection(context, this.instance).get(scheme + "://" + domain + "/api/v1/instance", 30, null, null); JSONObject jsonObject = new JSONObject(response); instanceNodeInfo.setName("MASTODON"); instanceNodeInfo.setVersion(jsonObject.getString("version")); @@ -692,8 +694,7 @@ public class API { } - - public InstanceNodeInfo displayNodeInfo(String domain){ + public InstanceNodeInfo displayNodeInfo(String domain) { String response; InstanceNodeInfo instanceNodeInfo = new InstanceNodeInfo(); @@ -703,7 +704,7 @@ public class API { ArrayList nodeInfos = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ){ + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); NodeInfo nodeInfo = new NodeInfo(); @@ -712,12 +713,12 @@ public class API { i++; nodeInfos.add(nodeInfo); } - if( nodeInfos.size() > 0){ - NodeInfo nodeInfo = nodeInfos.get(nodeInfos.size()-1); + if (nodeInfos.size() > 0) { + NodeInfo nodeInfo = nodeInfos.get(nodeInfos.size() - 1); response = new HttpsConnection(context, this.instance).get(nodeInfo.getHref(), 30, null, null); JSONObject resobj = new JSONObject(response); JSONObject jsonObject = resobj.getJSONObject("software"); - String name= null; + String name = null; name = jsonObject.getString("name").toUpperCase(); instanceNodeInfo.setName(name); instanceNodeInfo.setVersion(jsonObject.getString("version")); @@ -762,7 +763,7 @@ public class API { public API(Context context, String instance, String token) { this.context = context; - if( context == null) { + if (context == null) { apiResponse = new APIResponse(); APIError = new Error(); return; @@ -771,12 +772,12 @@ public class API { tootPerPage = sharedpreferences.getInt(Helper.SET_TOOT_PER_PAGE, Helper.TOOTS_PER_PAGE); accountPerPage = Helper.ACCOUNTS_PER_PAGE; notificationPerPage = Helper.NOTIFICATIONS_PER_PAGE; - if( instance != null) + if (instance != null) this.instance = instance; else this.instance = Helper.getLiveInstance(context); - if( token != null) + if (token != null) this.prefKeyOauthTokenT = token; else this.prefKeyOauthTokenT = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); @@ -785,9 +786,6 @@ public class API { } - - - /*** * Get info on the current Instance *synchronously* * @return APIResponse @@ -837,7 +835,6 @@ public class API { } - /*** * Update credential of the authenticated user *synchronously* * @return APIResponse @@ -845,27 +842,27 @@ public class API { public APIResponse updateCredential(String display_name, String note, ByteArrayInputStream avatar, String avatarName, ByteArrayInputStream header, String headerName, accountPrivacy privacy, HashMap customFields, boolean sensitive) { HashMap requestParams = new HashMap<>(); - if( display_name != null) + if (display_name != null) try { - requestParams.put("display_name",URLEncoder.encode(display_name, "UTF-8")); + requestParams.put("display_name", URLEncoder.encode(display_name, "UTF-8")); } catch (UnsupportedEncodingException e) { - requestParams.put("display_name",display_name); + requestParams.put("display_name", display_name); } - if( note != null) + if (note != null) try { - requestParams.put("note",URLEncoder.encode(note, "UTF-8")); + requestParams.put("note", URLEncoder.encode(note, "UTF-8")); } catch (UnsupportedEncodingException e) { - requestParams.put("note",note); + requestParams.put("note", note); } - if( privacy != null) - requestParams.put("locked",privacy==accountPrivacy.LOCKED?"true":"false"); + if (privacy != null) + requestParams.put("locked", privacy == accountPrivacy.LOCKED ? "true" : "false"); int i = 0; - if( customFields != null && customFields.size() > 0){ + if (customFields != null && customFields.size() > 0) { Iterator it = customFields.entrySet().iterator(); while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - requestParams.put("fields_attributes["+i+"][name]",(String)pair.getKey()); - requestParams.put("fields_attributes["+i+"][value]",(String)pair.getValue()); + Map.Entry pair = (Map.Entry) it.next(); + requestParams.put("fields_attributes[" + i + "][name]", (String) pair.getKey()); + requestParams.put("fields_attributes[" + i + "][value]", (String) pair.getValue()); it.remove(); i++; } @@ -893,41 +890,42 @@ public class API { public Account verifyCredentials() { account = new Account(); try { - if( context == null) { + if (context == null) { setError(500, new Throwable("An error occured!")); return null; } String response = new HttpsConnection(context, this.instance).get(getAbsoluteUrl("/accounts/verify_credentials"), 10, null, prefKeyOauthTokenT); account = parseAccountResponse(context, new JSONObject(response)); - if( account != null && account.getSocial() != null && account.getSocial().equals("PLEROMA")){ + if (account != null && account.getSocial() != null && account.getSocial().equals("PLEROMA")) { isPleromaAdmin(account.getAcct()); } } catch (HttpsConnection.HttpsConnectionException e) { e.printStackTrace(); - if( e.getStatusCode() == 401 || e.getStatusCode() == 403){ + if (e.getStatusCode() == 401 || e.getStatusCode() == 403) { SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); Account targetedAccount = new AccountDAO(context, db).getAccountByToken(prefKeyOauthTokenT); - if( targetedAccount == null) + if (targetedAccount == null) return null; HashMap values = refreshToken(targetedAccount.getClient_id(), targetedAccount.getClient_secret(), targetedAccount.getRefresh_token()); - if( values.containsKey("access_token") && values.get("access_token") != null) { + if (values.containsKey("access_token") && values.get("access_token") != null) { targetedAccount.setToken(values.get("access_token")); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); //This account is currently logged in, the token is updated - if( prefKeyOauthTokenT.equals(token)){ + if (prefKeyOauthTokenT.equals(token)) { SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, targetedAccount.getToken()); editor.apply(); } - }if( values.containsKey("refresh_token") && values.get("refresh_token") != null) + } + if (values.containsKey("refresh_token") && values.get("refresh_token") != null) targetedAccount.setRefresh_token(values.get("refresh_token")); new AccountDAO(context, db).updateAccountCredential(targetedAccount); String response; try { response = new HttpsConnection(context, this.instance).get(getAbsoluteUrl("/accounts/verify_credentials"), 10, null, targetedAccount.getToken()); account = parseAccountResponse(context, new JSONObject(response)); - if( account.getSocial().equals("PLEROMA")){ + if (account.getSocial().equals("PLEROMA")) { isPleromaAdmin(account.getAcct()); } } catch (IOException e1) { @@ -960,7 +958,7 @@ public class API { * Verifiy credential of the authenticated user *synchronously* * @return Account */ - private HashMap refreshToken(String client_id, String client_secret, String refresh_token) { + private HashMap refreshToken(String client_id, String client_secret, String refresh_token) { account = new Account(); HashMap params = new HashMap<>(); HashMap newValues = new HashMap<>(); @@ -972,10 +970,10 @@ public class API { String response = new HttpsConnection(context, this.instance).post(getAbsoluteUrl("/oauth/token"), 10, params, null); JSONObject resobj = new JSONObject(response); String token = resobj.get("access_token").toString(); - if( resobj.has("refresh_token")) + if (resobj.has("refresh_token")) refresh_token = resobj.get("refresh_token").toString(); - newValues.put("access_token",token); - newValues.put("refresh_token",refresh_token); + newValues.put("access_token", token); + newValues.put("refresh_token", refresh_token); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); @@ -991,7 +989,7 @@ public class API { return newValues; } - public APIResponse createAccount(AccountCreation accountCreation){ + public APIResponse createAccount(AccountCreation accountCreation) { apiResponse = new APIResponse(); try { @@ -1067,6 +1065,7 @@ public class API { /** * Returns an account + * * @param accountId String account fetched * @return Account entity */ @@ -1074,11 +1073,11 @@ public class API { account = new Account(); try { - String response = new HttpsConnection(context, this.instance).get(getAbsoluteUrl(String.format("/accounts/%s",accountId)), 10, null, prefKeyOauthTokenT); + String response = new HttpsConnection(context, this.instance).get(getAbsoluteUrl(String.format("/accounts/%s", accountId)), 10, null, prefKeyOauthTokenT); account = parseAccountResponse(context, new JSONObject(response)); final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - if( account.getSocial().equals("PLEROMA") && accountId.equals(userId)){ + if (account.getSocial().equals("PLEROMA") && accountId.equals(userId)) { isPleromaAdmin(account.getAcct()); } } catch (HttpsConnection.HttpsConnectionException e) { @@ -1098,6 +1097,7 @@ public class API { /** * Returns a relationship between the authenticated account and an account + * * @param accountId String account fetched * @return Relationship entity */ @@ -1106,11 +1106,11 @@ public class API { List relationships; Relationship relationship = null; HashMap params = new HashMap<>(); - params.put("id",accountId); + params.put("id", accountId); try { String response = new HttpsConnection(context, this.instance).get(getAbsoluteUrl("/accounts/relationships"), 10, params, prefKeyOauthTokenT); relationships = parseRelationshipResponse(new JSONArray(response)); - if( relationships != null && relationships.size() > 0) + if (relationships != null && relationships.size() > 0) relationship = relationships.get(0); } catch (HttpsConnection.HttpsConnectionException e) { setError(e.getStatusCode(), e); @@ -1127,19 +1127,17 @@ public class API { } - - - /** * Returns a relationship between the authenticated account and an account + * * @param accounts ArrayList accounts fetched * @return Relationship entity */ public APIResponse getRelationship(List accounts) { HashMap params = new HashMap<>(); - if( accounts != null && accounts.size() > 0 ) { + if (accounts != null && accounts.size() > 0) { StringBuilder parameters = new StringBuilder(); - for(Account account: accounts) + for (Account account : accounts) parameters.append("id[]=").append(account.getId()).append("&"); parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1).substring(5)); params.put("id[]", parameters.toString()); @@ -1243,15 +1241,15 @@ public class API { params.put("since_id", since_id); if (0 < limit || limit > 40) limit = 40; - if( onlyMedia) + if (onlyMedia) params.put("only_media", Boolean.toString(true)); - if( pinned) + if (pinned) params.put("pinned", Boolean.toString(true)); params.put("exclude_replies", Boolean.toString(exclude_replies)); params.put("limit", String.valueOf(limit)); final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String tag = sharedpreferences.getString(Helper.SET_FEATURED_TAG_ACTION, null); - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON && tag != null){ + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON && tag != null) { params.put("tagged", tag.toLowerCase()); } statuses = new ArrayList<>(); @@ -1278,12 +1276,11 @@ public class API { } - /** * Retrieves accounts that reblogged the status *synchronously* * - * @param statusId String Id of the status - * @param max_id String id max + * @param statusId String Id of the status + * @param max_id String id max * @return APIResponse */ @SuppressWarnings("SameParameterValue") @@ -1320,8 +1317,8 @@ public class API { /** * Retrieves accounts that favourited the status *synchronously* * - * @param statusId String Id of the status - * @param max_id String id max + * @param statusId String Id of the status + * @param max_id String id max * @return APIResponse */ @SuppressWarnings("SameParameterValue") @@ -1358,7 +1355,7 @@ public class API { /** * Retrieves one status *synchronously* * - * @param statusId String Id of the status + * @param statusId String Id of the status * @return APIResponse */ public APIResponse getStatusbyId(String statusId) { @@ -1387,7 +1384,7 @@ public class API { /** * Retrieves one status *synchronously* * - * @param statusId String Id of the status + * @param statusId String Id of the status * @return APIResponse */ public APIResponse getStatusbyIdAndCache(String statusId) { @@ -1418,7 +1415,7 @@ public class API { /** * Retrieves the context of status with replies *synchronously* * - * @param statusId Id of the status + * @param statusId Id of the status * @return List */ public app.fedilab.android.client.Entities.Context getStatusContext(String statusId) { @@ -1444,24 +1441,27 @@ public class API { /** * Retrieves direct timeline for the account *synchronously* - * @param max_id String id max + * + * @param max_id String id max * @return APIResponse */ - public APIResponse getDirectTimeline( String max_id) { + public APIResponse getDirectTimeline(String max_id) { return getDirectTimeline(max_id, null, tootPerPage); } /** * Retrieves conversation timeline for the account *synchronously* - * @param max_id String id max + * + * @param max_id String id max * @return APIResponse */ - public APIResponse getConversationTimeline( String max_id) { + public APIResponse getConversationTimeline(String max_id) { return getConversationTimeline(max_id, null, tootPerPage); } /** * Retrieves direct timeline for the account since an Id value *synchronously* + * * @return APIResponse */ public APIResponse getConversationTimelineSinceId(String since_id) { @@ -1470,6 +1470,7 @@ public class API { /** * Retrieves conversation timeline for the account *synchronously* + * * @param max_id String id max * @param since_id String since the id * @param limit int limit - max value 40 @@ -1484,7 +1485,7 @@ public class API { params.put("since_id", since_id); if (0 > limit || limit > 80) limit = 80; - params.put("limit",String.valueOf(limit)); + params.put("limit", String.valueOf(limit)); conversations = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); @@ -1509,6 +1510,7 @@ public class API { /** * Retrieves direct timeline for the account since an Id value *synchronously* + * * @return APIResponse */ public APIResponse getDirectTimelineSinceId(String since_id) { @@ -1517,6 +1519,7 @@ public class API { /** * Retrieves direct timeline for the account *synchronously* + * * @param max_id String id max * @param since_id String since the id * @param limit int limit - max value 40 @@ -1531,7 +1534,7 @@ public class API { params.put("since_id", since_id); if (0 > limit || limit > 80) limit = 80; - params.put("limit",String.valueOf(limit)); + params.put("limit", String.valueOf(limit)); statuses = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); @@ -1557,16 +1560,18 @@ public class API { /** * Retrieves home timeline for the account *synchronously* - * @param max_id String id max + * + * @param max_id String id max * @return APIResponse */ - public APIResponse getHomeTimeline( String max_id) { + public APIResponse getHomeTimeline(String max_id) { return getHomeTimeline(max_id, null, null, tootPerPage); } /** * Retrieves home timeline for the account since an Id value *synchronously* + * * @return APIResponse */ public APIResponse getHomeTimelineSinceId(String since_id) { @@ -1575,6 +1580,7 @@ public class API { /** * Retrieves home timeline for the account from a min Id value *synchronously* + * * @return APIResponse */ public APIResponse getHomeTimelineMinId(String min_id) { @@ -1582,42 +1588,41 @@ public class API { } - - /** * Retrieves home timeline from cache the account *synchronously* - * @param max_id String id max + * + * @param max_id String id max * @return APIResponse */ public APIResponse getHomeTimelineCache(String max_id) { SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - statuses = new TimelineCacheDAO(context, db).get(max_id); + statuses = new TimelineCacheDAO(context, db).get(max_id); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); boolean remember_position_home = sharedpreferences.getBoolean(Helper.SET_REMEMBER_POSITION_HOME, true); - if( remember_position_home ){ - if( statuses != null){ + if (remember_position_home) { + if (statuses != null) { Iterator i = statuses.iterator(); List ids = new ArrayList<>(); while (i.hasNext()) { Status s = i.next(); - if( ids.contains(s.getId())) { + if (ids.contains(s.getId())) { i.remove(); new TimelineCacheDAO(context, db).remove(s.getId()); - }else{ + } else { ids.add(s.getId()); } } } - if( statuses == null){ + if (statuses == null) { return getHomeTimeline(max_id); - }else{ - if( statuses.size() > 0) { - if( statuses.get(0).getId().matches("\\d+")){ + } else { + if (statuses.size() > 0) { + if (statuses.get(0).getId().matches("\\d+")) { apiResponse.setSince_id(String.valueOf(statuses.get(0).getId())); apiResponse.setMax_id(statuses.get(statuses.size() - 1).getId()); - }else{ + } else { apiResponse.setSince_id(statuses.get(0).getId()); apiResponse.setMax_id(statuses.get(statuses.size() - 1).getId()); } @@ -1625,7 +1630,7 @@ public class API { apiResponse.setStatuses(statuses); return apiResponse; } - }else{ + } else { return getHomeTimeline(max_id); } @@ -1634,6 +1639,7 @@ public class API { /** * Retrieves home timeline for the account *synchronously* + * * @param max_id String id max * @param since_id String since the id * @param limit int limit - max value 40 @@ -1650,16 +1656,16 @@ public class API { params.put("min_id", min_id); if (0 > limit || limit > 80) limit = 80; - params.put("limit",String.valueOf(limit)); + params.put("limit", String.valueOf(limit)); statuses = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); String response = httpsConnection.get(getAbsoluteUrl("/timelines/home"), 10, params, prefKeyOauthTokenT); apiResponse.setSince_id(httpsConnection.getSince_id()); apiResponse.setMax_id(httpsConnection.getMax_id()); - if( since_id == null) { + if (since_id == null) { statuses = parseStatusesForCache(context, new JSONArray(response)); - }else{ + } else { statuses = parseStatuses(context, new JSONArray(response)); } } catch (HttpsConnection.HttpsConnectionException e) { @@ -1673,7 +1679,7 @@ public class API { } catch (JSONException e) { e.printStackTrace(); } - if( apiResponse == null) + if (apiResponse == null) apiResponse = new APIResponse(); apiResponse.setStatuses(statuses); return apiResponse; @@ -1682,7 +1688,8 @@ public class API { /** * Retrieves public GNU timeline for the account *synchronously* - * @param max_id String id max + * + * @param max_id String id max * @return APIResponse */ public APIResponse getGNUTimeline(String remoteInstance, String max_id) { @@ -1693,13 +1700,13 @@ public class API { statuses = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - String response = httpsConnection.get("https://"+remoteInstance+"/api/statuses/public_timeline.json", 10, params, prefKeyOauthTokenT); + String response = httpsConnection.get("https://" + remoteInstance + "/api/statuses/public_timeline.json", 10, params, prefKeyOauthTokenT); statuses = GNUAPI.parseStatuses(context, new JSONArray(response)); - if( statuses.size() > 0) { - if(statuses.get(0).getId() != null && statuses.get(0).getId().matches("-?\\d+(\\.\\d+)?")) { + if (statuses.size() > 0) { + if (statuses.get(0).getId() != null && statuses.get(0).getId().matches("-?\\d+(\\.\\d+)?")) { apiResponse.setSince_id(String.valueOf(statuses.get(0).getId())); apiResponse.setMax_id(String.valueOf(statuses.get(statuses.size() - 1).getId())); - }else{ + } else { apiResponse.setSince_id(statuses.get(0).getId()); apiResponse.setMax_id(statuses.get(statuses.size() - 1).getId()); } @@ -1722,7 +1729,8 @@ public class API { /** * Retrieves public pixelfed timeline for the account *synchronously* - * @param max_id String id max + * + * @param max_id String id max * @return APIResponse */ public APIResponse getPixelfedTimeline(String remoteInstance, String max_id) { @@ -1751,8 +1759,10 @@ public class API { apiResponse.setStatuses(statuses); return apiResponse; } + /** * Retrieves Peertube videos from an instance *synchronously* + * * @return APIResponse */ public APIResponse getPeertubeChannel(String instance, String name) { @@ -1760,7 +1770,7 @@ public class API { List accounts = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - String response = httpsConnection.get(String.format("https://"+instance+"/api/v1/accounts/%s/video-channels", name), 10, null, null); + String response = httpsConnection.get(String.format("https://" + instance + "/api/v1/accounts/%s/video-channels", name), 10, null, null); JSONArray jsonArray = new JSONObject(response).getJSONArray("data"); accounts = parseAccountResponsePeertube(context, instance, jsonArray); } catch (HttpsConnection.HttpsConnectionException e) { @@ -1782,6 +1792,7 @@ public class API { /** * Retrieves Peertube videos from an instance *synchronously* + * * @return APIResponse */ public APIResponse getPeertubeChannelVideos(String instance, String name) { @@ -1789,7 +1800,7 @@ public class API { List peertubes = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - String response = httpsConnection.get(String.format("https://"+instance+"/api/v1/video-channels/%s/videos", name), 10, null, null); + String response = httpsConnection.get(String.format("https://" + instance + "/api/v1/video-channels/%s/videos", name), 10, null, null); JSONArray jsonArray = new JSONObject(response).getJSONArray("data"); peertubes = parsePeertube(instance, jsonArray); } catch (HttpsConnection.HttpsConnectionException e) { @@ -1809,22 +1820,23 @@ public class API { /** * Retrieves Peertube videos from an instance *synchronously* + * * @return APIResponse */ public APIResponse getPeertube(String instance, String max_id) { List peertubes = new ArrayList<>(); HashMap params = new HashMap<>(); - if( max_id == null) + if (max_id == null) max_id = "0"; params.put("start", max_id); - params.put("filter","local"); - params.put("sort","-publishedAt"); + params.put("filter", "local"); + params.put("sort", "-publishedAt"); params.put("count", "20"); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - String response = httpsConnection.get("https://"+instance+"/api/v1/videos", 10, params, null); + String response = httpsConnection.get("https://" + instance + "/api/v1/videos", 10, params, null); JSONArray jsonArray = new JSONObject(response).getJSONArray("data"); peertubes = parsePeertube(instance, jsonArray); } catch (HttpsConnection.HttpsConnectionException e) { @@ -1844,6 +1856,7 @@ public class API { /** * Retrieves Peertube videos from an instance *synchronously* + * * @return APIResponse */ public APIResponse getSinglePeertube(String instance, String videoId) { @@ -1852,7 +1865,7 @@ public class API { Peertube peertube = null; try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - String response = httpsConnection.get(String.format("https://"+instance+"/api/v1/videos/%s", videoId), 10, null, null); + String response = httpsConnection.get(String.format("https://" + instance + "/api/v1/videos/%s", videoId), 10, null, null); JSONObject jsonObject = new JSONObject(response); peertube = parseSinglePeertube(context, instance, jsonObject); } catch (HttpsConnection.HttpsConnectionException e) { @@ -1875,13 +1888,13 @@ public class API { /** * Retrieves peertube search *synchronously* * - * @param query String search + * @param query String search * @return APIResponse */ public APIResponse searchPeertube(String instance, String query) { HashMap params = new HashMap<>(); params.put("count", "50"); - if( query == null) + if (query == null) return null; try { params.put("search", URLEncoder.encode(query, "UTF-8")); @@ -1892,7 +1905,7 @@ public class API { List peertubes = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - String response = httpsConnection.get("https://"+instance+"/api/v1/search/videos", 10, params, null); + String response = httpsConnection.get("https://" + instance + "/api/v1/search/videos", 10, params, null); JSONArray jsonArray = new JSONObject(response).getJSONArray("data"); peertubes = parsePeertube(instance, jsonArray); } catch (HttpsConnection.HttpsConnectionException e) { @@ -1910,15 +1923,17 @@ public class API { apiResponse.setPeertubes(peertubes); return apiResponse; } + /** * Retrieves Peertube videos from an instance *synchronously* + * * @return APIResponse */ public APIResponse getSinglePeertubeComments(String instance, String videoId) { statuses = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - String response = httpsConnection.get(String.format("https://"+instance+"/api/v1/videos/%s/comment-threads", videoId), 10, null, null); + String response = httpsConnection.get(String.format("https://" + instance + "/api/v1/videos/%s/comment-threads", videoId), 10, null, null); JSONObject jsonObject = new JSONObject(response); statuses = parseSinglePeertubeComments(context, instance, jsonObject); } catch (HttpsConnection.HttpsConnectionException e) { @@ -1938,6 +1953,7 @@ public class API { /** * Retrieves home timeline for the account *synchronously* + * * @return APIResponse */ public APIResponse getHowTo() { @@ -1966,6 +1982,7 @@ public class API { /** * Retrieves Peertube videos from an instance *synchronously* + * * @return APIResponse */ public APIResponse getMisskey(String instance, String max_id) { @@ -1973,12 +1990,12 @@ public class API { JSONObject params = new JSONObject(); try { params.put("file", false); - if( max_id != null) - params.put("untilId",max_id); - params.put("local",true); - params.put("poll",false); - params.put("renote",false); - params.put("reply",false); + if (max_id != null) + params.put("untilId", max_id); + params.put("local", true); + params.put("poll", false); + params.put("renote", false); + params.put("reply", false); } catch (JSONException e) { e.printStackTrace(); } @@ -1986,11 +2003,11 @@ public class API { try { statuses = new ArrayList<>(); HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - String response = httpsConnection.postMisskey("https://"+instance+"/api/notes", 10, params, null); + String response = httpsConnection.postMisskey("https://" + instance + "/api/notes", 10, params, null); statuses = parseNotes(context, instance, new JSONArray(response)); - if( statuses != null && statuses.size() > 0){ + if (statuses != null && statuses.size() > 0) { apiResponse.setSince_id(statuses.get(0).getId()); - apiResponse.setMax_id(statuses.get(statuses.size() -1).getId()); + apiResponse.setMax_id(statuses.get(statuses.size() - 1).getId()); } } catch (HttpsConnection.HttpsConnectionException e) { setError(e.getStatusCode(), e); @@ -2006,29 +2023,33 @@ public class API { apiResponse.setStatuses(statuses); return apiResponse; } + /** * Retrieves public timeline for the account *synchronously* - * @param local boolean only local timeline + * + * @param local boolean only local timeline * @param max_id String id max * @return APIResponse */ - public APIResponse getPublicTimeline(String instanceName, boolean local, String max_id){ + public APIResponse getPublicTimeline(String instanceName, boolean local, String max_id) { return getPublicTimeline(local, instanceName, max_id, null, tootPerPage); } /** * Retrieves public timeline for the account *synchronously* - * @param local boolean only local timeline + * + * @param local boolean only local timeline * @param max_id String id max * @return APIResponse */ - public APIResponse getPublicTimeline(boolean local, String max_id){ + public APIResponse getPublicTimeline(boolean local, String max_id) { return getPublicTimeline(local, null, max_id, null, tootPerPage); } /** * Retrieves public timeline for the account since an Id value *synchronously* - * @param local boolean only local timeline + * + * @param local boolean only local timeline * @param since_id String id since * @return APIResponse */ @@ -2038,8 +2059,9 @@ public class API { /** * Retrieves instance timeline since an Id value *synchronously* + * * @param instanceName String instance name - * @param since_id String id since + * @param since_id String id since * @return APIResponse */ public APIResponse getInstanceTimelineSinceId(String instanceName, String since_id) { @@ -2048,29 +2070,30 @@ public class API { /** * Retrieves public timeline for the account *synchronously* - * @param local boolean only local timeline - * @param max_id String id max + * + * @param local boolean only local timeline + * @param max_id String id max * @param since_id String since the id - * @param limit int limit - max value 40 + * @param limit int limit - max value 40 * @return APIResponse */ - private APIResponse getPublicTimeline(boolean local, String instanceName, String max_id, String since_id, int limit){ + private APIResponse getPublicTimeline(boolean local, String instanceName, String max_id, String since_id, int limit) { HashMap params = new HashMap<>(); - if( local) + if (local) params.put("local", Boolean.toString(true)); - if( max_id != null ) + if (max_id != null) params.put("max_id", max_id); - if( since_id != null ) + if (since_id != null) params.put("since_id", since_id); - if( 0 > limit || limit > 40) + if (0 > limit || limit > 40) limit = 40; - params.put("limit",String.valueOf(limit)); + params.put("limit", String.valueOf(limit)); statuses = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); String url; - if( instanceName == null) + if (instanceName == null) url = getAbsoluteUrl("/timelines/public"); else url = getAbsoluteUrlRemoteInstance(instanceName); @@ -2095,13 +2118,13 @@ public class API { } - /** * Retrieves news coming from Fedilab's account *synchronously* + * * @param max_id String id max * @return APIResponse */ - public APIResponse getNews(String max_id){ + public APIResponse getNews(String max_id) { HashMap params = null; if (max_id != null) { @@ -2117,9 +2140,9 @@ public class API { apiResponse.setSince_id(httpsConnection.getSince_id()); apiResponse.setMax_id(httpsConnection.getMax_id()); List tmp_status = parseStatuses(context, new JSONArray(response)); - if( tmp_status != null && tmp_status.size() > 0){ - for(Status status: tmp_status){ - if( status.getAccount().getAcct().equals("fedilab")){ + if (tmp_status != null && tmp_status.size() > 0) { + for (Status status : tmp_status) { + if (status.getAccount().getAcct().equals("fedilab")) { statuses.add(status); } } @@ -2141,35 +2164,37 @@ public class API { /** * Retrieves discover timeline for the account *synchronously* - * @param local boolean only local timeline + * + * @param local boolean only local timeline * @param max_id String id max * @return APIResponse */ - public APIResponse getDiscoverTimeline(boolean local, String max_id){ + public APIResponse getDiscoverTimeline(boolean local, String max_id) { return getDiscoverTimeline(local, max_id, null, tootPerPage); } /** * Retrieves discover timeline for the account *synchronously* - * @param local boolean only local timeline - * @param max_id String id max + * + * @param local boolean only local timeline + * @param max_id String id max * @param since_id String since the id - * @param limit int limit - max value 40 + * @param limit int limit - max value 40 * @return APIResponse */ - private APIResponse getDiscoverTimeline(boolean local, String max_id, String since_id, int limit){ + private APIResponse getDiscoverTimeline(boolean local, String max_id, String since_id, int limit) { HashMap params = new HashMap<>(); - if( local) + if (local) params.put("local", Boolean.toString(true)); - if( max_id != null ) + if (max_id != null) params.put("max_id", max_id); - if( since_id != null ) + if (since_id != null) params.put("since_id", since_id); - if( 0 > limit || limit > 40) + if (0 > limit || limit > 40) limit = 40; - params.put("limit",String.valueOf(limit)); + params.put("limit", String.valueOf(limit)); statuses = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); @@ -2195,40 +2220,41 @@ public class API { } - - public APIResponse getCustomArtTimeline(boolean local, String tag, String max_id, List any, List all, List none){ + public APIResponse getCustomArtTimeline(boolean local, String tag, String max_id, List any, List all, List none) { return getArtTimeline(local, tag, max_id, null, any, all, none); } - public APIResponse getArtTimeline(boolean local, String max_id, List any, List all, List none){ + public APIResponse getArtTimeline(boolean local, String max_id, List any, List all, List none) { return getArtTimeline(local, null, max_id, null, any, all, none); } - public APIResponse getCustomArtTimelineSinceId(boolean local, String tag, String since_id, List any, List all, List none){ + public APIResponse getCustomArtTimelineSinceId(boolean local, String tag, String since_id, List any, List all, List none) { return getArtTimeline(local, tag, null, since_id, any, all, none); } - public APIResponse getArtTimelineSinceId(boolean local, String since_id, List any, List all, List none){ + public APIResponse getArtTimelineSinceId(boolean local, String since_id, List any, List all, List none) { return getArtTimeline(local, null, null, since_id, any, all, none); } + /** * Retrieves art timeline - * @param local boolean only local timeline + * + * @param local boolean only local timeline * @param max_id String id max * @return APIResponse */ - private APIResponse getArtTimeline(boolean local, String tag, String max_id, String since_id, List any, List all, List none){ - if( tag == null) + private APIResponse getArtTimeline(boolean local, String tag, String max_id, String since_id, List any, List all, List none) { + if (tag == null) tag = "mastoart"; APIResponse apiResponse = getPublicTimelineTag(tag, local, true, max_id, since_id, tootPerPage, any, all, none, null); APIResponse apiResponseReply = new APIResponse(); - if( apiResponse != null){ + if (apiResponse != null) { apiResponseReply.setMax_id(apiResponse.getMax_id()); apiResponseReply.setSince_id(apiResponse.getSince_id()); apiResponseReply.setStatuses(new ArrayList<>()); - if( apiResponse.getStatuses() != null && apiResponse.getStatuses().size() > 0){ - for( Status status: apiResponse.getStatuses()){ - if( status.getMedia_attachments() != null ) { + if (apiResponse.getStatuses() != null && apiResponse.getStatuses().size() > 0) { + for (Status status : apiResponse.getStatuses()) { + if (status.getMedia_attachments() != null) { String statusSerialized = Helper.statusToStringStorage(status); for (Attachment attachment : status.getMedia_attachments()) { Status newStatus = Helper.restoreStatusFromString(statusSerialized); @@ -2246,113 +2272,122 @@ public class API { /** * Retrieves public tag timeline *synchronously* - * @param tag String - * @param local boolean only local timeline + * + * @param tag String + * @param local boolean only local timeline * @param max_id String id max * @return APIResponse */ @SuppressWarnings("SameParameterValue") - public APIResponse getPublicTimelineTag(String tag, boolean local, String max_id, List any, List all, List none){ + public APIResponse getPublicTimelineTag(String tag, boolean local, String max_id, List any, List all, List none) { return getPublicTimelineTag(tag, local, false, max_id, null, tootPerPage, any, all, none, null); } /** * Retrieves public tag timeline *synchronously* - * @param tag String - * @param local boolean only local timeline + * + * @param tag String + * @param local boolean only local timeline * @param max_id String id max * @return APIResponse */ @SuppressWarnings("SameParameterValue") - public APIResponse getPublicTimelineTag(String tag, boolean local, String max_id, String instance){ + public APIResponse getPublicTimelineTag(String tag, boolean local, String max_id, String instance) { return getPublicTimelineTag(tag, local, false, max_id, null, tootPerPage, null, null, null, instance); } /** * Retrieves public tag timeline *synchronously* - * @param tag String - * @param local boolean only local timeline + * + * @param tag String + * @param local boolean only local timeline * @param since_id String since id * @return APIResponse */ @SuppressWarnings("SameParameterValue") - public APIResponse getPublicTimelineTagSinceId(String tag, boolean local, String since_id, List any, List all, List none){ + public APIResponse getPublicTimelineTagSinceId(String tag, boolean local, String since_id, List any, List all, List none) { return getPublicTimelineTag(tag, local, false, null, since_id, tootPerPage, any, all, none, null); } + /** * Retrieves public tag timeline *synchronously* - * @param tag String - * @param local boolean only local timeline - * @param max_id String id max + * + * @param tag String + * @param local boolean only local timeline + * @param max_id String id max * @param since_id String since the id - * @param limit int limit - max value 40 + * @param limit int limit - max value 40 * @return APIResponse */ @SuppressWarnings("SameParameterValue") - private APIResponse getPublicTimelineTag(String tag, boolean local, boolean onlymedia, String max_id, String since_id, int limit, List any, List all, List none, String instance){ + private APIResponse getPublicTimelineTag(String tag, boolean local, boolean onlymedia, String max_id, String since_id, int limit, List any, List all, List none, String instance) { HashMap params = new HashMap<>(); - if( local) + if (local) params.put("local", Boolean.toString(true)); - if( max_id != null ) + if (max_id != null) params.put("max_id", max_id); - if( since_id != null ) + if (since_id != null) params.put("since_id", since_id); - if( 0 > limit || limit > 40) + if (0 > limit || limit > 40) limit = 40; - if( onlymedia) + if (onlymedia) params.put("only_media", Boolean.toString(true)); - if( any != null && any.size() > 0) { + if (any != null && any.size() > 0) { StringBuilder parameters = new StringBuilder(); for (String a : any) { try { a = URLEncoder.encode(a, "UTF-8"); - } catch (UnsupportedEncodingException ignored) {} + } catch (UnsupportedEncodingException ignored) { + } parameters.append("any[]=").append(a).append("&"); } parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1).substring(6)); params.put("any[]", parameters.toString()); } - if( all != null && all.size() > 0) { + if (all != null && all.size() > 0) { StringBuilder parameters = new StringBuilder(); for (String a : all) { try { a = URLEncoder.encode(a, "UTF-8"); - } catch (UnsupportedEncodingException ignored) {} + } catch (UnsupportedEncodingException ignored) { + } parameters.append("all[]=").append(a).append("&"); } parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1).substring(6)); params.put("all[]", parameters.toString()); } - if( none != null && none.size() > 0) { + if (none != null && none.size() > 0) { StringBuilder parameters = new StringBuilder(); for (String a : none) { try { a = URLEncoder.encode(a, "UTF-8"); - } catch (UnsupportedEncodingException ignored) {} + } catch (UnsupportedEncodingException ignored) { + } parameters.append("none[]=").append(a).append("&"); } parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1).substring(7)); params.put("none[]", parameters.toString()); } - params.put("limit",String.valueOf(limit)); + params.put("limit", String.valueOf(limit)); statuses = new ArrayList<>(); - if( tag == null) + if (tag == null) return null; try { String query = tag.trim(); HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) try { query = URLEncoder.encode(query, "UTF-8"); - } catch (UnsupportedEncodingException ignored) {} + } catch (UnsupportedEncodingException ignored) { + } String response; - if( instance == null) - response = httpsConnection.get(getAbsoluteUrl(String.format("/timelines/tag/%s",query)), 10, params, prefKeyOauthTokenT); + if (instance == null) + response = httpsConnection.get(getAbsoluteUrl(String.format("/timelines/tag/%s", query)), 10, params, prefKeyOauthTokenT); else - response = httpsConnection.get(getAbsoluteUrlRemote(instance, String.format("/timelines/tag/%s",query)), 10, params, null); + response = httpsConnection.get(getAbsoluteUrlRemote(instance, String.format("/timelines/tag/%s", query)), 10, params, null); apiResponse.setSince_id(httpsConnection.getSince_id()); apiResponse.setMax_id(httpsConnection.getMax_id()); statuses = parseStatuses(context, new JSONArray(response)); @@ -2375,61 +2410,66 @@ public class API { /** * Retrieves muted users by the authenticated account *synchronously* + * * @param max_id String id max * @return APIResponse */ - public APIResponse getMuted(String max_id){ + public APIResponse getMuted(String max_id) { return getAccounts("/mutes", max_id, null, accountPerPage); } /** * Retrieves blocked users by the authenticated account *synchronously* + * * @param max_id String id max * @return APIResponse */ - public APIResponse getBlocks(String max_id){ + public APIResponse getBlocks(String max_id) { return getAccounts("/blocks", max_id, null, accountPerPage); } /** * Retrieves following for the account specified by targetedId *synchronously* + * * @param targetedId String targetedId - * @param max_id String id max + * @param max_id String id max * @return APIResponse */ - public APIResponse getFollowing(String targetedId, String max_id){ - return getAccounts(String.format("/accounts/%s/following",targetedId),max_id, null, accountPerPage); + public APIResponse getFollowing(String targetedId, String max_id) { + return getAccounts(String.format("/accounts/%s/following", targetedId), max_id, null, accountPerPage); } /** * Retrieves followers for the account specified by targetedId *synchronously* + * * @param targetedId String targetedId - * @param max_id String id max + * @param max_id String id max * @return APIResponse */ - public APIResponse getFollowers(String targetedId, String max_id){ - return getAccounts(String.format("/accounts/%s/followers",targetedId),max_id, null, accountPerPage); + public APIResponse getFollowers(String targetedId, String max_id) { + return getAccounts(String.format("/accounts/%s/followers", targetedId), max_id, null, accountPerPage); } /** * Retrieves blocked users by the authenticated account *synchronously* - * @param max_id String id max + * + * @param max_id String id max * @param since_id String since the id - * @param limit int limit - max value 40 + * @param limit int limit - max value 40 * @return APIResponse */ @SuppressWarnings("SameParameterValue") - private APIResponse getAccounts(String action, String max_id, String since_id, int limit){ + private APIResponse getAccounts(String action, String max_id, String since_id, int limit) { HashMap params = new HashMap<>(); - if( max_id != null ) + if (max_id != null) params.put("max_id", max_id); - if( since_id != null ) + if (since_id != null) params.put("since_id", since_id); - if( 0 > limit || limit > 40) + if (0 > limit || limit > 40) limit = 40; - params.put("limit",String.valueOf(limit)); + params.put("limit", String.valueOf(limit)); accounts = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); @@ -2437,8 +2477,8 @@ public class API { apiResponse.setSince_id(httpsConnection.getSince_id()); apiResponse.setMax_id(httpsConnection.getMax_id()); accounts = parseAccountResponse(new JSONArray(response)); - if( accounts != null && accounts.size() == 1 ){ - if(accounts.get(0).getAcct() == null){ + if (accounts != null && accounts.size() == 1) { + if (accounts.get(0).getAcct() == null) { Throwable error = new Throwable(context.getString(R.string.toast_error)); setError(500, error); } @@ -2461,9 +2501,10 @@ public class API { /** * Retrieves opencollective accounts *synchronously* + * * @return APIResponse */ - public Results getOpencollectiveAccounts(RetrieveOpenCollectiveAsyncTask.Type type){ + public Results getOpencollectiveAccounts(RetrieveOpenCollectiveAsyncTask.Type type) { results = new Results(); accounts = new ArrayList<>(); @@ -2487,19 +2528,19 @@ public class API { } - /** * Retrieves blocked domains for the authenticated account *synchronously* + * * @param max_id String id max * @return APIResponse */ @SuppressWarnings("SameParameterValue") - public APIResponse getBlockedDomain(String max_id){ + public APIResponse getBlockedDomain(String max_id) { HashMap params = new HashMap<>(); - if( max_id != null ) + if (max_id != null) params.put("max_id", max_id); - params.put("limit","80"); + params.put("limit", "80"); domains = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); @@ -2525,13 +2566,14 @@ public class API { /** * Delete a blocked domains for the authenticated account *synchronously* + * * @param domain String domain name */ @SuppressWarnings("SameParameterValue") - public int deleteBlockedDomain(String domain){ + public int deleteBlockedDomain(String domain) { HashMap params = new HashMap<>(); - params.put("domain",domain); + params.put("domain", domain); domains = new ArrayList<>(); HttpsConnection httpsConnection; try { @@ -2552,30 +2594,33 @@ public class API { /** * Retrieves follow requests for the authenticated account *synchronously* + * * @param max_id String id max * @return APIResponse */ - public APIResponse getFollowRequest(String max_id){ + public APIResponse getFollowRequest(String max_id) { return getFollowRequest(max_id, null, accountPerPage); } + /** * Retrieves follow requests for the authenticated account *synchronously* - * @param max_id String id max + * + * @param max_id String id max * @param since_id String since the id - * @param limit int limit - max value 40 + * @param limit int limit - max value 40 * @return APIResponse */ @SuppressWarnings("SameParameterValue") - private APIResponse getFollowRequest(String max_id, String since_id, int limit){ + private APIResponse getFollowRequest(String max_id, String since_id, int limit) { HashMap params = new HashMap<>(); - if( max_id != null ) + if (max_id != null) params.put("max_id", max_id); - if( since_id != null ) + if (since_id != null) params.put("since_id", since_id); - if( 0 > limit || limit > 40) + if (0 > limit || limit > 40) limit = 40; - params.put("limit",String.valueOf(limit)); + params.put("limit", String.valueOf(limit)); accounts = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); @@ -2601,30 +2646,33 @@ public class API { /** * Retrieves favourited status for the authenticated account *synchronously* + * * @param max_id String id max * @return APIResponse */ - public APIResponse getFavourites(String max_id){ + public APIResponse getFavourites(String max_id) { return getFavourites(max_id, null, tootPerPage); } + /** * Retrieves favourited status for the authenticated account *synchronously* - * @param max_id String id max + * + * @param max_id String id max * @param since_id String since the id - * @param limit int limit - max value 40 + * @param limit int limit - max value 40 * @return APIResponse */ @SuppressWarnings("SameParameterValue") - private APIResponse getFavourites(String max_id, String since_id, int limit){ + private APIResponse getFavourites(String max_id, String since_id, int limit) { HashMap params = new HashMap<>(); - if( max_id != null ) + if (max_id != null) params.put("max_id", max_id); - if( since_id != null ) + if (since_id != null) params.put("since_id", since_id); - if( 0 > limit || limit > 40) + if (0 > limit || limit > 40) limit = 40; - params.put("limit",String.valueOf(limit)); + params.put("limit", String.valueOf(limit)); statuses = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); @@ -2650,21 +2698,23 @@ public class API { /** * Makes the post action for a status + * * @param statusAction Enum - * @param targetedId String id of the targeted Id *can be this of a status or an account* + * @param targetedId String id of the targeted Id *can be this of a status or an account* * @return in status code - Should be equal to 200 when action is done */ - public int postAction(StatusAction statusAction, String targetedId){ + public int postAction(StatusAction statusAction, String targetedId) { return postAction(statusAction, targetedId, null, null); } /** * Makes the post action for a status - * @param targetedId String id of the targeted Id *can be this of a status or an account* + * + * @param targetedId String id of the targeted Id *can be this of a status or an account* * @param muteNotifications - boolean - notifications should be also muted * @return in status code - Should be equal to 200 when action is done */ - public int muteNotifications(String targetedId, boolean muteNotifications){ + public int muteNotifications(String targetedId, boolean muteNotifications) { HashMap params = new HashMap<>(); params.put("notifications", Boolean.toString(muteNotifications)); @@ -2687,41 +2737,44 @@ public class API { /** * Makes the post action - * @param status Status object related to the status + * + * @param status Status object related to the status * @param comment String comment for the report * @return in status code - Should be equal to 200 when action is done */ - public int reportAction(Status status, String comment){ + public int reportAction(Status status, String comment) { return postAction(API.StatusAction.REPORT, null, status, comment); } /** * Makes the post action + * * @param targetedId targeted account - * @param comment String comment for the report + * @param comment String comment for the report * @return in status code - Should be equal to 200 when action is done */ - public int reportAction(String targetedId, String comment){ + public int reportAction(String targetedId, String comment) { return postAction(API.StatusAction.REPORT, targetedId, null, comment); } - public int statusAction(Status status){ + public int statusAction(Status status) { return postAction(StatusAction.CREATESTATUS, null, status, null); } /** * Makes the post action + * * @param statusAction Enum - * @param targetedId String id of the targeted Id *can be this of a status or an account* - * @param status Status object related to the status - * @param comment String comment for the report + * @param targetedId String id of the targeted Id *can be this of a status or an account* + * @param status Status object related to the status + * @param comment String comment for the report * @return in status code - Should be equal to 200 when action is done */ - private int postAction(StatusAction statusAction, String targetedId, Status status, String comment ){ + private int postAction(StatusAction statusAction, String targetedId, Status status, String comment) { String action; HashMap params = null; - switch (statusAction){ + switch (statusAction) { case FAVOURITE: action = String.format("/statuses/%s/favourite", targetedId); break; @@ -2782,12 +2835,12 @@ public class API { break; case SHOW_BOOST: params = new HashMap<>(); - params.put("reblogs","true"); + params.put("reblogs", "true"); action = String.format("/accounts/%s/follow", targetedId); break; case HIDE_BOOST: params = new HashMap<>(); - params.put("reblogs","false"); + params.put("reblogs", "false"); action = String.format("/accounts/%s/follow", targetedId); break; case UNSTATUS: @@ -2802,12 +2855,12 @@ public class API { case REPORT: action = "/reports"; params = new HashMap<>(); - if( status != null ) + if (status != null) params.put("account_id", status.getAccount().getId()); else params.put("account_id", targetedId); params.put("comment", comment); - if( status != null) { + if (status != null) { params.put("status_ids[]", status.getId()); } break; @@ -2819,48 +2872,49 @@ public class API { } catch (UnsupportedEncodingException e) { params.put("status", status.getContent()); } - if( status.getScheduled_at() != null) + if (status.getScheduled_at() != null) params.put("scheduled_at", status.getScheduled_at()); - if( status.getIn_reply_to_id() != null) + if (status.getIn_reply_to_id() != null) params.put("in_reply_to_id", status.getIn_reply_to_id()); - if( status.getMedia_attachments() != null && status.getMedia_attachments().size() > 0 ) { + if (status.getMedia_attachments() != null && status.getMedia_attachments().size() > 0) { StringBuilder parameters = new StringBuilder(); - for(Attachment attachment: status.getMedia_attachments()) + for (Attachment attachment : status.getMedia_attachments()) parameters.append("media_ids[]=").append(attachment.getId()).append("&"); parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1).substring(12)); params.put("media_ids[]", parameters.toString()); } - if( status.isSensitive()) + if (status.isSensitive()) params.put("sensitive", Boolean.toString(status.isSensitive())); - if( status.getSpoiler_text() != null) + if (status.getSpoiler_text() != null) try { params.put("spoiler_text", URLEncoder.encode(status.getSpoiler_text(), "UTF-8")); } catch (UnsupportedEncodingException e) { params.put("spoiler_text", status.getSpoiler_text()); } params.put("visibility", status.getVisibility()); - break; + break; default: return -1; } - if(statusAction != StatusAction.UNSTATUS ) { + if (statusAction != StatusAction.UNSTATUS) { try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); String resp = httpsConnection.post(getAbsoluteUrl(action), 10, params, prefKeyOauthTokenT); actionCode = httpsConnection.getActionCode(); - if( statusAction == StatusAction.REBLOG || statusAction == StatusAction.UNREBLOG || statusAction == StatusAction.FAVOURITE || statusAction == StatusAction.UNFAVOURITE) { + if (statusAction == StatusAction.REBLOG || statusAction == StatusAction.UNREBLOG || statusAction == StatusAction.FAVOURITE || statusAction == StatusAction.UNFAVOURITE) { Bundle b = new Bundle(); try { Status status1 = parseStatuses(context, new JSONObject(resp)); b.putParcelable("status", status1); - } catch (JSONException ignored) {} + } catch (JSONException ignored) { + } Intent intentBC = new Intent(Helper.RECEIVE_ACTION); intentBC.putExtras(b); LocalBroadcastManager.getInstance(context).sendBroadcast(intentBC); SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); Account account = new AccountDAO(context, db).getAccountByToken(prefKeyOauthTokenT); Status indb = new TimelineCacheDAO(context, db).getSingle(targetedId); - if( indb != null) { + if (indb != null) { String response = httpsConnection.get(getAbsoluteUrl(String.format("/statuses/%s", targetedId)), 10, null, prefKeyOauthTokenT); new TimelineCacheDAO(context, db).update(targetedId, response, account.getId(), account.getInstance()); } @@ -2874,7 +2928,7 @@ public class API { } catch (KeyManagementException e) { e.printStackTrace(); } - }else{ + } else { try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); httpsConnection.delete(getAbsoluteUrl(action), 10, null, prefKeyOauthTokenT); @@ -2894,7 +2948,7 @@ public class API { return actionCode; } - public int reportStatus(List statuses, String comment, boolean forward){ + public int reportStatus(List statuses, String comment, boolean forward) { String action; HashMap params = null; action = "/reports"; @@ -2902,9 +2956,9 @@ public class API { params.put("account_id", statuses.get(0).getAccount().getId()); params.put("comment", comment); StringBuilder parameters = new StringBuilder(); - for(Status val: statuses) + for (Status val : statuses) parameters.append("status_ids[]=").append(val).append("&"); - if( parameters.length() > 0) { + if (parameters.length() > 0) { parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1).substring(13)); params.put("status_ids[]", parameters.toString()); } @@ -2926,20 +2980,20 @@ public class API { } - /** * scheduled action for a status + * * @param status Status object related to the status * @return APIResponse */ - public APIResponse scheduledAction(String call, Status status, String max_id, String targetedId){ + public APIResponse scheduledAction(String call, Status status, String max_id, String targetedId) { HashMap params = new HashMap<>(); - if( call.equals("PUT")){ - if( status.getScheduled_at() != null) + if (call.equals("PUT")) { + if (status.getScheduled_at() != null) params.put("scheduled_at", status.getScheduled_at()); - }else if(call.equals("GET")){ - if( max_id != null ) + } else if (call.equals("GET")) { + if (max_id != null) params.put("max_id", max_id); } List storedStatus = new ArrayList<>(); @@ -2947,13 +3001,13 @@ public class API { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); String response = null; int responseCode = -1; - if( call.equals("GET")) + if (call.equals("GET")) response = httpsConnection.get(getAbsoluteUrl("/scheduled_statuses/"), 10, null, prefKeyOauthTokenT); - else if( call.equals("PUT")) + else if (call.equals("PUT")) response = httpsConnection.put(getAbsoluteUrl(String.format("/scheduled_statuses/%s", targetedId)), 10, params, prefKeyOauthTokenT); - else if( call.equals("DELETE")) - responseCode = httpsConnection.delete(getAbsoluteUrl(String.format("/scheduled_statuses/%s",targetedId)), 10, null, prefKeyOauthTokenT); - if(call.equals("GET")) { + else if (call.equals("DELETE")) + responseCode = httpsConnection.delete(getAbsoluteUrl(String.format("/scheduled_statuses/%s", targetedId)), 10, null, prefKeyOauthTokenT); + if (call.equals("GET")) { apiResponse.setSince_id(httpsConnection.getSince_id()); apiResponse.setMax_id(httpsConnection.getMax_id()); } @@ -2971,11 +3025,11 @@ public class API { st.setUserId(userId); st.setStatus(schedule.getStatus()); storedStatus.add(st); - }else if (response != null && call.equals("GET")) { + } else if (response != null && call.equals("GET")) { List scheduleList = parseSchedule(context, new JSONArray(response)); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - for(Schedule schedule: scheduleList){ + for (Schedule schedule : scheduleList) { StoredStatus st = new StoredStatus(); st.setCreation_date(null); st.setScheduledServerdId(schedule.getId()); @@ -3008,17 +3062,18 @@ public class API { /** * Public api call to submit a vote + * * @param pollId * @param choices * @return */ - public Poll submiteVote(String pollId, int[] choices){ + public Poll submiteVote(String pollId, int[] choices) { JsonObject jsonObject = new JsonObject(); JsonArray jchoices = new JsonArray(); - for(int choice : choices){ + for (int choice : choices) { jchoices.add(choice); } - jsonObject.add("choices",jchoices); + jsonObject.add("choices", jchoices); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); String response = httpsConnection.postJson(getAbsoluteUrl(String.format("/polls/%s/votes", pollId)), 10, jsonObject, prefKeyOauthTokenT); @@ -3040,12 +3095,13 @@ public class API { /** * Public api call to refresh a poll + * * @param status Status * @return Poll */ - public Poll getPoll(Status status){ + public Poll getPoll(Status status) { try { - Poll _p = (status.getReblog() != null)?status.getReblog().getPoll():status.getPoll(); + Poll _p = (status.getReblog() != null) ? status.getReblog().getPoll() : status.getPoll(); HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); String response = httpsConnection.get(getAbsoluteUrl(String.format("/polls/%s", _p.getId())), 10, null, prefKeyOauthTokenT); Poll poll = parsePoll(context, new JSONObject(response)); @@ -3080,39 +3136,40 @@ public class API { /** * Posts a status + * * @param status Status object related to the status * @return APIResponse */ - public APIResponse postStatusAction(Status status){ + public APIResponse postStatusAction(Status status) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("status", status.getContent()); - if( status.getContentType() != null) + if (status.getContentType() != null) jsonObject.addProperty("content_type", status.getContentType()); - if( status.getIn_reply_to_id() != null) + if (status.getIn_reply_to_id() != null) jsonObject.addProperty("in_reply_to_id", status.getIn_reply_to_id()); - if( status.getMedia_attachments() != null && status.getMedia_attachments().size() > 0 ) { + if (status.getMedia_attachments() != null && status.getMedia_attachments().size() > 0) { JsonArray mediaArray = new JsonArray(); - for(Attachment attachment: status.getMedia_attachments()) + for (Attachment attachment : status.getMedia_attachments()) mediaArray.add(attachment.getId()); jsonObject.add("media_ids", mediaArray); } - if( status.getScheduled_at() != null) + if (status.getScheduled_at() != null) jsonObject.addProperty("scheduled_at", status.getScheduled_at()); - if( status.isSensitive()) + if (status.isSensitive()) jsonObject.addProperty("sensitive", Boolean.toString(status.isSensitive())); - if( status.getSpoiler_text() != null) + if (status.getSpoiler_text() != null) jsonObject.addProperty("spoiler_text", status.getSpoiler_text()); - if( status.getPoll() != null){ + if (status.getPoll() != null) { JsonObject poll = new JsonObject(); JsonArray options = new JsonArray(); - for(PollOptions option: status.getPoll().getOptionsList()){ - if( !option.getTitle().isEmpty()) + for (PollOptions option : status.getPoll().getOptionsList()) { + if (!option.getTitle().isEmpty()) options.add(option.getTitle()); } - poll.add("options",options); - poll.addProperty("expires_in",status.getPoll().getExpires_in()); - poll.addProperty("multiple",status.getPoll().isMultiple()); + poll.add("options", options); + poll.addProperty("expires_in", status.getPoll().getExpires_in()); + poll.addProperty("multiple", status.getPoll().isMultiple()); jsonObject.add("poll", poll); } jsonObject.addProperty("visibility", status.getVisibility()); @@ -3143,14 +3200,15 @@ public class API { /** * Posts a status + * * @param notificationId String, the current notification id, if null all notifications are deleted * @return APIResponse */ - public APIResponse postNoticationAction(String notificationId){ + public APIResponse postNoticationAction(String notificationId) { String action; HashMap params = new HashMap<>(); - if( notificationId == null) + if (notificationId == null) action = "/notifications/clear"; else { action = "/notifications/" + notificationId + "/dismiss"; @@ -3172,45 +3230,49 @@ public class API { /** * Retrieves notifications for the authenticated account since an id*synchronously* + * * @param since_id String since max * @return APIResponse */ - public APIResponse getNotificationsSince(DisplayNotificationsFragment.Type type, String since_id, boolean display){ + public APIResponse getNotificationsSince(DisplayNotificationsFragment.Type type, String since_id, boolean display) { return getNotifications(type, null, since_id, notificationPerPage, display); } /** * Retrieves notifications for the authenticated account since an id*synchronously* + * * @param since_id String since max * @return APIResponse */ @SuppressWarnings("SameParameterValue") - public APIResponse getNotificationsSince(DisplayNotificationsFragment.Type type, String since_id, int notificationPerPage, boolean display){ + public APIResponse getNotificationsSince(DisplayNotificationsFragment.Type type, String since_id, int notificationPerPage, boolean display) { return getNotifications(type, null, since_id, notificationPerPage, display); } /** * Retrieves notifications for the authenticated account *synchronously* + * * @param max_id String id max * @return APIResponse */ - public APIResponse getNotifications(DisplayNotificationsFragment.Type type, String max_id, boolean display){ + public APIResponse getNotifications(DisplayNotificationsFragment.Type type, String max_id, boolean display) { return getNotifications(type, max_id, null, notificationPerPage, display); } /** * Retrieves notifications for the authenticated account *synchronously* + * * @param max_id String id max * @return APIResponse */ - public APIResponse getNotifications( String max_id){ + public APIResponse getNotifications(String max_id) { HashMap params = new HashMap<>(); - if( max_id != null ) + if (max_id != null) params.put("max_id", max_id); - params.put("limit","30"); - if( context == null){ + params.put("limit", "30"); + if (context == null) { apiResponse = new APIResponse(); Error error = new Error(); apiResponse.setError(error); @@ -3241,23 +3303,24 @@ public class API { /** * Retrieves notifications for the authenticated account *synchronously* - * @param max_id String id max + * + * @param max_id String id max * @param since_id String since the id - * @param limit int limit - max value 40 + * @param limit int limit - max value 40 * @return APIResponse */ - private APIResponse getNotifications(DisplayNotificationsFragment.Type type, String max_id, String since_id, int limit, boolean display){ + private APIResponse getNotifications(DisplayNotificationsFragment.Type type, String max_id, String since_id, int limit, boolean display) { HashMap params = new HashMap<>(); - if( max_id != null ) + if (max_id != null) params.put("max_id", max_id); - if( since_id != null ) + if (since_id != null) params.put("since_id", since_id); - if( 0 > limit || limit > 30) + if (0 > limit || limit > 30) limit = 30; - params.put("limit",String.valueOf(limit)); + params.put("limit", String.valueOf(limit)); - if( context == null){ + if (context == null) { apiResponse = new APIResponse(); Error error = new Error(); apiResponse.setError(error); @@ -3266,14 +3329,14 @@ public class API { final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); boolean notif_follow, notif_add, notif_mention, notif_share, notif_poll; StringBuilder parameters = new StringBuilder(); - if( type == DisplayNotificationsFragment.Type.ALL){ - if( display) { + if (type == DisplayNotificationsFragment.Type.ALL) { + if (display) { notif_follow = sharedpreferences.getBoolean(Helper.SET_NOTIF_FOLLOW_FILTER, true); notif_add = sharedpreferences.getBoolean(Helper.SET_NOTIF_ADD_FILTER, true); notif_mention = sharedpreferences.getBoolean(Helper.SET_NOTIF_MENTION_FILTER, true); notif_share = sharedpreferences.getBoolean(Helper.SET_NOTIF_SHARE_FILTER, true); notif_poll = sharedpreferences.getBoolean(Helper.SET_NOTIF_POLL_FILTER, true); - }else{ + } else { notif_follow = sharedpreferences.getBoolean(Helper.SET_NOTIF_FOLLOW, true); notif_add = sharedpreferences.getBoolean(Helper.SET_NOTIF_ADD, true); notif_mention = sharedpreferences.getBoolean(Helper.SET_NOTIF_MENTION, true); @@ -3282,49 +3345,49 @@ public class API { } - if( !notif_follow ) + if (!notif_follow) parameters.append("exclude_types[]=").append("follow").append("&"); - if( !notif_add ) + if (!notif_add) parameters.append("exclude_types[]=").append("favourite").append("&"); - if( !notif_share ) + if (!notif_share) parameters.append("exclude_types[]=").append("reblog").append("&"); - if( !notif_mention ) + if (!notif_mention) parameters.append("exclude_types[]=").append("mention").append("&"); - if( !notif_poll ) + if (!notif_poll) parameters.append("exclude_types[]=").append("poll").append("&"); - if( parameters.length() > 0) { + if (parameters.length() > 0) { parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1).substring(16)); params.put("exclude_types[]", parameters.toString()); } - }else if(type == DisplayNotificationsFragment.Type.MENTION){ - parameters.append("exclude_types[]=").append("follow").append("&"); - parameters.append("exclude_types[]=").append("favourite").append("&"); - parameters.append("exclude_types[]=").append("reblog").append("&"); - parameters.append("exclude_types[]=").append("poll").append("&"); - parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1).substring(16)); - params.put("exclude_types[]", parameters.toString()); - }else if(type == DisplayNotificationsFragment.Type.FAVORITE){ + } else if (type == DisplayNotificationsFragment.Type.MENTION) { + parameters.append("exclude_types[]=").append("follow").append("&"); + parameters.append("exclude_types[]=").append("favourite").append("&"); + parameters.append("exclude_types[]=").append("reblog").append("&"); + parameters.append("exclude_types[]=").append("poll").append("&"); + parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1).substring(16)); + params.put("exclude_types[]", parameters.toString()); + } else if (type == DisplayNotificationsFragment.Type.FAVORITE) { parameters.append("exclude_types[]=").append("follow").append("&"); parameters.append("exclude_types[]=").append("mention").append("&"); parameters.append("exclude_types[]=").append("reblog").append("&"); parameters.append("exclude_types[]=").append("poll").append("&"); parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1).substring(16)); params.put("exclude_types[]", parameters.toString()); - }else if(type == DisplayNotificationsFragment.Type.BOOST){ + } else if (type == DisplayNotificationsFragment.Type.BOOST) { parameters.append("exclude_types[]=").append("follow").append("&"); parameters.append("exclude_types[]=").append("mention").append("&"); parameters.append("exclude_types[]=").append("favourite").append("&"); parameters.append("exclude_types[]=").append("poll").append("&"); parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1).substring(16)); params.put("exclude_types[]", parameters.toString()); - }else if(type == DisplayNotificationsFragment.Type.POLL){ + } else if (type == DisplayNotificationsFragment.Type.POLL) { parameters.append("exclude_types[]=").append("reblog").append("&"); parameters.append("exclude_types[]=").append("follow").append("&"); parameters.append("exclude_types[]=").append("mention").append("&"); parameters.append("exclude_types[]=").append("favourite").append("&"); parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1).substring(16)); params.put("exclude_types[]", parameters.toString()); - }else if(type == DisplayNotificationsFragment.Type.FOLLOW){ + } else if (type == DisplayNotificationsFragment.Type.FOLLOW) { parameters.append("exclude_types[]=").append("reblog").append("&"); parameters.append("exclude_types[]=").append("mention").append("&"); parameters.append("exclude_types[]=").append("favourite").append("&"); @@ -3357,16 +3420,14 @@ public class API { } - - - /** * Changes media description - * @param mediaId String - * @param description String + * + * @param mediaId String + * @param description String * @return Attachment */ - public Attachment updateDescription(String mediaId, String description){ + public Attachment updateDescription(String mediaId, String description) { HashMap params = new HashMap<>(); try { @@ -3395,14 +3456,14 @@ public class API { /** * Retrieves Accounts and feeds when searching *synchronously* * - * @param query String search + * @param query String search * @return Results */ public APIResponse search(String query) { HashMap params = new HashMap<>(); apiResponse = new APIResponse(); - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) params.put("q", query); else try { @@ -3435,13 +3496,13 @@ public class API { /** * Retrieves Accounts and feeds when searching *synchronously* * - * @param query String search + * @param query String search * @return Results */ public APIResponse search2(String query, searchType type, String offset) { apiResponse = new APIResponse(); HashMap params = new HashMap<>(); - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) params.put("q", query); else try { @@ -3449,9 +3510,9 @@ public class API { } catch (UnsupportedEncodingException e) { params.put("q", query); } - if( offset != null) + if (offset != null) params.put("offset", offset); - if( type != null) { + if (type != null) { switch (type) { case TAGS: params.put("type", "hashtags"); @@ -3492,7 +3553,8 @@ public class API { /** * Retrieves Accounts when searching (ie: via @...) *synchronously* * Not limited to following - * @param query String search + * + * @param query String search * @return APIResponse */ @SuppressWarnings("SameParameterValue") @@ -3502,20 +3564,21 @@ public class API { /** * Retrieves Accounts when searching (ie: via @...) *synchronously* - * @param query String search - * @param count int limit - * @param following boolean following only + * + * @param query String search + * @param count int limit + * @param following boolean following only * @return APIResponse */ public APIResponse searchAccounts(String query, int count, boolean following) { HashMap params = new HashMap<>(); params.put("q", query); - if( count < 5) + if (count < 5) count = 5; - if( count > 40 ) + if (count > 40) count = 40; - if( following) + if (following) params.put("following", Boolean.toString(true)); params.put("limit", String.valueOf(count)); @@ -3542,7 +3605,6 @@ public class API { } - /** * Retrieves Accounts when searching (ie: via @...) *synchronously* * @@ -3569,9 +3631,9 @@ public class API { e.printStackTrace(); } //Add custom emoji for Pleroma - if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA){ + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { APIResponse apiResponsePleroma = getCustomPleromaEmoji(); - if( apiResponsePleroma != null && apiResponsePleroma.getEmojis() != null && apiResponsePleroma.getEmojis().size() > 0) + if (apiResponsePleroma != null && apiResponsePleroma.getEmojis() != null && apiResponsePleroma.getEmojis().size() > 0) emojis.addAll(apiResponsePleroma.getEmojis()); } apiResponse.setEmojis(emojis); @@ -3579,6 +3641,7 @@ public class API { } //Pleroma admin calls + /** * Check if it's a Pleroma admin account and change in settings *synchronously* */ @@ -3587,7 +3650,7 @@ public class API { boolean isAdmin; try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - String response = httpsConnection.get(String.format(Helper.getLiveInstanceWithProtocol(context)+"/api/pleroma/admin/permission_group/%s/admin",nickname), 10, null, prefKeyOauthTokenT); + String response = httpsConnection.get(String.format(Helper.getLiveInstanceWithProtocol(context) + "/api/pleroma/admin/permission_group/%s/admin", nickname), 10, null, prefKeyOauthTokenT); //Call didn't return a 404, so the account is admin isAdmin = true; } catch (Exception e) { @@ -3607,7 +3670,7 @@ public class API { List emojis = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - String response = httpsConnection.get(Helper.getLiveInstanceWithProtocol(context)+"/api/pleroma/emoji", 10, null, prefKeyOauthTokenT); + String response = httpsConnection.get(Helper.getLiveInstanceWithProtocol(context) + "/api/pleroma/emoji", 10, null, prefKeyOauthTokenT); emojis = parsePleromaEmojis(new JSONObject(response)); } catch (HttpsConnection.HttpsConnectionException e) { @@ -3627,9 +3690,10 @@ public class API { /** * Get filters for the user + * * @return APIResponse */ - public APIResponse getFilters(){ + public APIResponse getFilters() { List filters = null; try { @@ -3652,10 +3716,11 @@ public class API { /** * Get a Filter by its id + * * @return APIResponse */ @SuppressWarnings("unused") - public APIResponse getFilters(String filterId){ + public APIResponse getFilters(String filterId) { List filters = new ArrayList<>(); Filters filter; @@ -3681,16 +3746,17 @@ public class API { /** * Create a filter + * * @param filter Filter * @return APIResponse */ - public APIResponse addFilters(Filters filter){ + public APIResponse addFilters(Filters filter) { HashMap params = new HashMap<>(); params.put("phrase", filter.getPhrase()); StringBuilder parameters = new StringBuilder(); - for(String context: filter.getContext()) + for (String context : filter.getContext()) parameters.append("context[]=").append(context).append("&"); - if( parameters.length() > 0) { + if (parameters.length() > 0) { parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1).substring(10)); params.put("context[]", parameters.toString()); } @@ -3719,10 +3785,11 @@ public class API { /** * Delete a filter + * * @param filter Filter * @return APIResponse */ - public int deleteFilters(Filters filter){ + public int deleteFilters(Filters filter) { try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); @@ -3742,16 +3809,17 @@ public class API { /** * Delete a filter + * * @param filter Filter * @return APIResponse */ - public APIResponse updateFilters(Filters filter){ + public APIResponse updateFilters(Filters filter) { HashMap params = new HashMap<>(); params.put("phrase", filter.getPhrase()); StringBuilder parameters = new StringBuilder(); - for(String context: filter.getContext()) + for (String context : filter.getContext()) parameters.append("context[]=").append(context).append("&"); - if( parameters.length() > 0) { + if (parameters.length() > 0) { parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1).substring(10)); params.put("context[]", parameters.toString()); } @@ -3780,9 +3848,10 @@ public class API { /** * Get lists for the user + * * @return APIResponse */ - public APIResponse getLists(){ + public APIResponse getLists() { apiResponse = new APIResponse(); List lists = new ArrayList<>(); try { @@ -3805,10 +3874,11 @@ public class API { /** * Get lists for a user by its id + * * @return APIResponse */ @SuppressWarnings("unused") - public APIResponse getLists(String userId){ + public APIResponse getLists(String userId) { List lists = new ArrayList<>(); app.fedilab.android.client.Entities.List list; @@ -3833,7 +3903,8 @@ public class API { /** * Retrieves list timeline *synchronously* - * @param list_id String id of the list + * + * @param list_id String id of the list * @param max_id String id max * @param since_id String since the id * @param limit int limit - max value 40 @@ -3848,11 +3919,11 @@ public class API { params.put("since_id", since_id); if (0 > limit || limit > 80) limit = 80; - params.put("limit",String.valueOf(limit)); + params.put("limit", String.valueOf(limit)); statuses = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - String response = httpsConnection.get(getAbsoluteUrl(String.format("/timelines/list/%s",list_id)), 10, params, prefKeyOauthTokenT); + String response = httpsConnection.get(getAbsoluteUrl(String.format("/timelines/list/%s", list_id)), 10, params, prefKeyOauthTokenT); apiResponse.setSince_id(httpsConnection.getSince_id()); apiResponse.setMax_id(httpsConnection.getMax_id()); statuses = parseStatuses(context, new JSONArray(response)); @@ -3875,19 +3946,20 @@ public class API { /** * Get accounts in a list for a user + * * @param listId String, id of the list - * @param limit int, limit of results + * @param limit int, limit of results * @return APIResponse */ @SuppressWarnings("SameParameterValue") - public APIResponse getAccountsInList(String listId, int limit){ + public APIResponse getAccountsInList(String listId, int limit) { HashMap params = new HashMap<>(); - if( limit < 0) + if (limit < 0) limit = 0; - if( limit > 50 ) + if (limit > 50) limit = 50; - params.put("limit",String.valueOf(limit)); + params.put("limit", String.valueOf(limit)); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); String response = httpsConnection.get(getAbsoluteUrl(String.format("/lists/%s/accounts", listId)), 10, params, prefKeyOauthTokenT); @@ -3910,19 +3982,19 @@ public class API { } - /** * Get a list + * * @param id String, id of the list * @return APIResponse */ @SuppressWarnings("unused") - public APIResponse getList(String id){ + public APIResponse getList(String id) { List lists = new ArrayList<>(); app.fedilab.android.client.Entities.List list; try { - String response = new HttpsConnection(context, this.instance).get(getAbsoluteUrl(String.format("/lists/%s",id)), 10, null, prefKeyOauthTokenT); + String response = new HttpsConnection(context, this.instance).get(getAbsoluteUrl(String.format("/lists/%s", id)), 10, null, prefKeyOauthTokenT); list = parseList(new JSONObject(response)); lists.add(list); } catch (HttpsConnection.HttpsConnectionException e) { @@ -3943,19 +4015,20 @@ public class API { /** * Add an account in a list - * @param id String, id of the list + * + * @param id String, id of the list * @param account_ids String, account to add * @return APIResponse */ //TODO: it is unclear what is returned here //TODO: improves doc https://github.com/tootsuite/documentation/blob/4bb149c73f40fa58fd7265a336703dd2d83efb1c/Using-the-API/API.md#addingremoving-accounts-tofrom-a-list - public APIResponse addAccountToList(String id, String[] account_ids){ + public APIResponse addAccountToList(String id, String[] account_ids) { HashMap params = new HashMap<>(); StringBuilder parameters = new StringBuilder(); - for(String val: account_ids) + for (String val : account_ids) parameters.append("account_ids[]=").append(val).append("&"); - if( parameters.length() > 0) { + if (parameters.length() > 0) { parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1).substring(14)); params.put("account_ids[]", parameters.toString()); } @@ -3976,17 +4049,18 @@ public class API { /** * Delete an account from a list + * * @param id String, the id of the list * @return APIResponse */ - public int deleteAccountFromList(String id, String[] account_ids){ + public int deleteAccountFromList(String id, String[] account_ids) { try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); StringBuilder parameters = new StringBuilder(); HashMap params = new HashMap<>(); - for(String val: account_ids) + for (String val : account_ids) parameters.append("account_ids[]=").append(val).append("&"); - if( parameters.length() > 0) { + if (parameters.length() > 0) { parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1).substring(14)); params.put("account_ids[]", parameters.toString()); } @@ -4007,13 +4081,14 @@ public class API { /** * Posts a list + * * @param title String, the title of the list * @return APIResponse */ - public APIResponse createList(String title){ + public APIResponse createList(String title) { HashMap params = new HashMap<>(); - params.put("title",title); + params.put("title", title); List lists = new ArrayList<>(); app.fedilab.android.client.Entities.List list; try { @@ -4036,17 +4111,17 @@ public class API { } - /** * Update a list by its id - * @param id String, the id of the list + * + * @param id String, the id of the list * @param title String, the title of the list * @return APIResponse */ - public APIResponse updateList(String id, String title){ + public APIResponse updateList(String id, String title) { HashMap params = new HashMap<>(); - params.put("title",title); + params.put("title", title); List lists = new ArrayList<>(); app.fedilab.android.client.Entities.List list; try { @@ -4071,26 +4146,27 @@ public class API { /** * Delete a list by its id + * * @param id String, the id of the list * @return APIResponse */ - public int deleteList(String id){ + public int deleteList(String id) { try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); httpsConnection.delete(getAbsoluteUrl(String.format("/lists/%s", id)), 10, null, prefKeyOauthTokenT); actionCode = httpsConnection.getActionCode(); } catch (HttpsConnection.HttpsConnectionException e) { setError(e.getStatusCode(), e); - }catch (Exception e) { + } catch (Exception e) { setDefaultError(e); } return actionCode; } - /** * Retrieves list from Communitywiki *synchronously* + * * @return APIResponse */ public ArrayList getCommunitywikiList() { @@ -4101,7 +4177,7 @@ public class API { JSONArray jsonArray = new JSONArray(response); int len = jsonArray.length(); - for (int i=0;i getCommunitywikiList(String name) { @@ -4130,10 +4207,11 @@ public class API { String response = httpsConnection.get(getAbsoluteUrlCommunitywiki(String.format("/list/%s", name)), 10, null, prefKeyOauthTokenT); JSONArray jsonArray = new JSONArray(response); - for(int i = 0; i < jsonArray.length(); i++){ + for (int i = 0; i < jsonArray.length(); i++) { try { list.add(jsonArray.getJSONObject(i).getString("acct")); - } catch (JSONException ignored) {} + } catch (JSONException ignored) { + } } } catch (HttpsConnection.HttpsConnectionException e) { setError(e.getStatusCode(), e); @@ -4153,10 +4231,11 @@ public class API { /** * Parse json response an unique account + * * @param resobj JSONObject * @return Account */ - private Results parseResultsResponse(JSONObject resobj){ + private Results parseResultsResponse(JSONObject resobj) { Results results = new Results(); try { @@ -4171,10 +4250,11 @@ public class API { /** * Parse json response an unique Car + * * @param resobj JSONObject * @return Card */ - private static Card parseCardResponse(JSONObject resobj){ + private static Card parseCardResponse(JSONObject resobj) { Card card = new Card(); try { @@ -4186,42 +4266,42 @@ public class API { card.setType(resobj.get("type").toString()); try { card.setAuthor_name(resobj.get("author_name").toString()); - }catch (Exception e){ + } catch (Exception e) { card.setAuthor_name(null); } try { card.setAuthor_url(resobj.get("author_url").toString()); - }catch (Exception e){ + } catch (Exception e) { card.setAuthor_url(null); } try { card.setHtml(resobj.get("html").toString()); - }catch (Exception e){ + } catch (Exception e) { card.setHtml(null); } try { card.setEmbed_url(resobj.get("embed_url").toString()); - }catch (Exception e){ + } catch (Exception e) { card.setEmbed_url(null); } try { card.setProvider_name(resobj.get("provider_name").toString()); - }catch (Exception e){ + } catch (Exception e) { card.setProvider_name(null); } try { card.setProvider_url(resobj.get("provider_url").toString()); - }catch (Exception e){ + } catch (Exception e) { card.setProvider_url(null); } try { card.setHeight(Integer.parseInt(resobj.get("height").toString())); - }catch (Exception e){ + } catch (Exception e) { card.setHeight(0); } try { card.setWidth(Integer.parseInt(resobj.get("width").toString())); - }catch (Exception e){ + } catch (Exception e) { card.setWidth(0); } } catch (JSONException e) { @@ -4232,10 +4312,11 @@ public class API { /** * Parse json response an unique instance social result + * * @param resobj JSONObject * @return InstanceSocial */ - public static InstanceSocial parseInstanceSocialResponse(Context context, JSONObject resobj){ + public static InstanceSocial parseInstanceSocialResponse(Context context, JSONObject resobj) { InstanceSocial instanceSocial = new InstanceSocial(); try { @@ -4278,51 +4359,56 @@ public class API { /** * Parse Domains + * * @param jsonArray JSONArray * @return List of domains */ - private List parseDomains(JSONArray jsonArray){ + private List parseDomains(JSONArray jsonArray) { List list_tmp = new ArrayList<>(); - for(int i = 0; i < jsonArray.length(); i++){ + for (int i = 0; i < jsonArray.length(); i++) { try { list_tmp.add(jsonArray.getString(i)); - } catch (JSONException ignored) {} + } catch (JSONException ignored) { + } } - return list_tmp; + return list_tmp; } /** * Parse Tags + * * @param jsonArray JSONArray * @return List of tags */ - private List parseTags(JSONArray jsonArray){ + private List parseTags(JSONArray jsonArray) { List list_tmp = new ArrayList<>(); - for(int i = 0; i < jsonArray.length(); i++){ + for (int i = 0; i < jsonArray.length(); i++) { try { - if( jsonArray.get(i) instanceof JSONObject) { + if (jsonArray.get(i) instanceof JSONObject) { list_tmp.add(jsonArray.getJSONObject(i).getString("name")); - }else{ + } else { list_tmp.add(jsonArray.getString(i)); } } catch (JSONException ignored) { } } - return list_tmp; + return list_tmp; } + /** * Parse json response for several howto + * * @param jsonArray JSONArray * @return List */ - private List parseHowTos(JSONArray jsonArray){ + private List parseHowTos(JSONArray jsonArray) { List howToVideos = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ){ + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); HowToVideo howToVideo = parseHowTo(context, resobj); @@ -4338,15 +4424,16 @@ public class API { /** * Parse json response for several howto + * * @param jsonArray JSONArray * @return List */ - private List parsePeertube(String instance, JSONArray jsonArray){ + private List parsePeertube(String instance, JSONArray jsonArray) { List peertubes = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ){ + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Peertube peertube = parsePeertube(context, instance, resobj); i++; @@ -4361,10 +4448,11 @@ public class API { /** * Parse json response for unique how to + * * @param resobj JSONObject * @return Peertube */ - public static Peertube parsePeertube(Context context, String instance, JSONObject resobj){ + public static Peertube parsePeertube(Context context, String instance, JSONObject resobj) { Peertube peertube = new Peertube(); try { peertube.setId(resobj.get("id").toString()); @@ -4395,10 +4483,11 @@ public class API { /** * Parse json response for unique how to + * * @param resobj JSONObject * @return Peertube */ - private static Peertube parseSinglePeertube(Context context, String instance, JSONObject resobj){ + private static Peertube parseSinglePeertube(Context context, String instance, JSONObject resobj) { Peertube peertube = new Peertube(); try { peertube.setId(resobj.get("id").toString()); @@ -4424,7 +4513,7 @@ public class API { } JSONArray files = resobj.getJSONArray("files"); ArrayList resolutions = new ArrayList<>(); - for(int j = 0 ; j < files.length() ; j++){ + for (int j = 0; j < files.length(); j++) { JSONObject attObj = files.getJSONObject(j); resolutions.add(attObj.getJSONObject("resolution").get("id").toString()); } @@ -4438,33 +4527,34 @@ public class API { /** * Parse json response for peertube comments + * * @param resobj JSONObject * @return Peertube */ - private static List parseSinglePeertubeComments(Context context, String instance, JSONObject resobj){ + private static List parseSinglePeertubeComments(Context context, String instance, JSONObject resobj) { List statuses = new ArrayList<>(); try { JSONArray jsonArray = resobj.getJSONArray("data"); - int i = 0; - while (i < jsonArray.length() ){ - Status status = new Status(); - JSONObject comment = jsonArray.getJSONObject(i); - status.setId(comment.get("id").toString()); - status.setUri(comment.get("url").toString()); - status.setUrl(comment.get("url").toString()); - status.setSensitive(false); - status.setSpoiler_text(""); - status.setContent(comment.get("text").toString()); - status.setIn_reply_to_id(comment.get("inReplyToCommentId").toString()); - status.setAccount(parseAccountResponsePeertube(context, instance, comment.getJSONObject("account"))); - status.setCreated_at(Helper.mstStringToDate(context, comment.get("createdAt").toString())); - status.setMentions(new ArrayList<>()); - status.setEmojis(new ArrayList<>()); - status.setMedia_attachments(new ArrayList<>()); - status.setVisibility("public"); - i++; - statuses.add(status); - } + int i = 0; + while (i < jsonArray.length()) { + Status status = new Status(); + JSONObject comment = jsonArray.getJSONObject(i); + status.setId(comment.get("id").toString()); + status.setUri(comment.get("url").toString()); + status.setUrl(comment.get("url").toString()); + status.setSensitive(false); + status.setSpoiler_text(""); + status.setContent(comment.get("text").toString()); + status.setIn_reply_to_id(comment.get("inReplyToCommentId").toString()); + status.setAccount(parseAccountResponsePeertube(context, instance, comment.getJSONObject("account"))); + status.setCreated_at(Helper.mstStringToDate(context, comment.get("createdAt").toString())); + status.setMentions(new ArrayList<>()); + status.setEmojis(new ArrayList<>()); + status.setMedia_attachments(new ArrayList<>()); + status.setVisibility("public"); + i++; + statuses.add(status); + } } catch (JSONException e) { e.printStackTrace(); } catch (ParseException e) { @@ -4475,10 +4565,11 @@ public class API { /** * Parse json response for unique how to + * * @param resobj JSONObject * @return HowToVideo */ - private static HowToVideo parseHowTo(Context context, JSONObject resobj){ + private static HowToVideo parseHowTo(Context context, JSONObject resobj) { HowToVideo howToVideo = new HowToVideo(); try { howToVideo.setId(resobj.get("id").toString()); @@ -4497,15 +4588,16 @@ public class API { /** * Parse json response for several conversations + * * @param jsonArray JSONArray * @return List */ - private List parseConversations(JSONArray jsonArray){ + private List parseConversations(JSONArray jsonArray) { List conversations = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ){ + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Conversation conversation = parseConversation(context, resobj); @@ -4521,6 +4613,7 @@ public class API { /** * Parse json response for unique conversation + * * @param resobj JSONObject * @return Conversation */ @@ -4532,16 +4625,18 @@ public class API { conversation.setUnread(Boolean.parseBoolean(resobj.get("unread").toString())); conversation.setAccounts(parseAccountResponse(resobj.getJSONArray("accounts"))); conversation.setLast_status(parseStatuses(context, resobj.getJSONObject("last_status"))); - }catch (JSONException ignored) {} + } catch (JSONException ignored) { + } return conversation; } /** * Parse json response for several scheduled toots + * * @param jsonObject JSONObject * @return List */ - private static Schedule parseSimpleSchedule(Context context, JSONObject jsonObject){ + private static Schedule parseSimpleSchedule(Context context, JSONObject jsonObject) { Schedule schedule = new Schedule(); try { JSONObject resobj = jsonObject.getJSONObject("params"); @@ -4562,15 +4657,16 @@ public class API { /** * Parse json response for several scheduled toots + * * @param jsonArray JSONArray * @return List */ - private static List parseSchedule(Context context, JSONArray jsonArray){ + private static List parseSchedule(Context context, JSONArray jsonArray) { List schedules = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ){ + while (i < jsonArray.length()) { Schedule schedule = new Schedule(); JSONObject resobj = jsonArray.getJSONObject(i).getJSONObject("params"); Status status = parseSchedule(context, resobj); @@ -4594,16 +4690,17 @@ public class API { /** * Parse json response for several status + * * @param jsonArray JSONArray * @return List */ - private List parseStatusesForCache(Context context, JSONArray jsonArray){ + private List parseStatusesForCache(Context context, JSONArray jsonArray) { SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); Account account = new AccountDAO(context, db).getAccountByToken(prefKeyOauthTokenT); List statuses = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ){ + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Status status = parseStatuses(context, resobj); @@ -4623,20 +4720,21 @@ public class API { /** * Parse json response for several status + * * @param jsonArray JSONArray * @return List */ - private static List parseStatuses(Context context, JSONArray jsonArray){ + private static List parseStatuses(Context context, JSONArray jsonArray) { List statuses = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ){ + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Status status = parseStatuses(context, resobj); i++; - if( status != null) { + if (status != null) { statuses.add(status); } } @@ -4650,11 +4748,12 @@ public class API { /** * Parse a poll + * * @param context * @param resobj * @return */ - public static Poll parsePoll(Context context, JSONObject resobj){ + public static Poll parsePoll(Context context, JSONObject resobj) { Poll poll = new Poll(); try { poll.setId(resobj.getString("id")); @@ -4665,7 +4764,7 @@ public class API { poll.setVoted(resobj.getBoolean("voted")); JSONArray options = resobj.getJSONArray("options"); List pollOptions = new ArrayList<>(); - for(int i = 0; i < options.length() ; i++){ + for (int i = 0; i < options.length(); i++) { JSONObject option = options.getJSONObject(i); PollOptions pollOption = new PollOptions(); pollOption.setTitle(option.getString("title")); @@ -4683,11 +4782,12 @@ public class API { /** * Parse json response for unique status + * * @param resobj JSONObject * @return Status */ @SuppressWarnings("InfiniteRecursion") - public static Status parseStatuses(Context context, JSONObject resobj){ + public static Status parseStatuses(Context context, JSONObject resobj) { Status status = new Status(); try { status.setId(resobj.get("id").toString()); @@ -4699,16 +4799,20 @@ public class API { status.setSpoiler_text(resobj.get("spoiler_text").toString()); try { status.setVisibility(resobj.get("visibility").toString()); - }catch (Exception e){status.setVisibility("public");} + } catch (Exception e) { + status.setVisibility("public"); + } try { status.setLanguage(resobj.get("language").toString()); - }catch (Exception e){status.setLanguage("ja");} + } catch (Exception e) { + status.setLanguage("ja"); + } status.setUrl(resobj.get("url").toString()); //Retrieves attachments JSONArray arrayAttachement = resobj.getJSONArray("media_attachments"); ArrayList attachments = new ArrayList<>(); - if( arrayAttachement != null){ - for(int j = 0 ; j < arrayAttachement.length() ; j++){ + if (arrayAttachement != null) { + for (int j = 0; j < arrayAttachement.length(); j++) { JSONObject attObj = arrayAttachement.getJSONObject(j); Attachment attachment = new Attachment(); attachment.setId(attObj.get("id").toString()); @@ -4719,21 +4823,24 @@ public class API { attachment.setUrl(attObj.get("url").toString()); try { attachment.setDescription(attObj.get("description").toString()); - }catch (JSONException ignore){} + } catch (JSONException ignore) { + } attachments.add(attachment); } } try { status.setCard(parseCardResponse(resobj.getJSONObject("card"))); - }catch (Exception e){status.setCard(null);} + } catch (Exception e) { + status.setCard(null); + } status.setMedia_attachments(attachments); //Retrieves mentions List mentions = new ArrayList<>(); JSONArray arrayMention = resobj.getJSONArray("mentions"); - if( arrayMention != null){ - for(int j = 0 ; j < arrayMention.length() ; j++){ + if (arrayMention != null) { + for (int j = 0; j < arrayMention.length(); j++) { JSONObject menObj = arrayMention.getJSONObject(j); Mention mention = new Mention(); mention.setId(menObj.get("id").toString()); @@ -4747,8 +4854,8 @@ public class API { //Retrieves tags List tags = new ArrayList<>(); JSONArray arrayTag = resobj.getJSONArray("tags"); - if( arrayTag != null){ - for(int j = 0 ; j < arrayTag.length() ; j++){ + if (arrayTag != null) { + for (int j = 0; j < arrayTag.length(); j++) { JSONObject tagObj = arrayTag.getJSONObject(j); Tag tag = new Tag(); tag.setName(tagObj.get("name").toString()); @@ -4761,25 +4868,25 @@ public class API { List emojiList = new ArrayList<>(); try { JSONArray emojisTag = resobj.getJSONArray("emojis"); - if( emojisTag != null){ - for(int j = 0 ; j < emojisTag.length() ; j++){ + if (emojisTag != null) { + for (int j = 0; j < emojisTag.length(); j++) { JSONObject emojisObj = emojisTag.getJSONObject(j); Emojis emojis = parseEmojis(emojisObj); emojiList.add(emojis); } } status.setEmojis(emojiList); - }catch (Exception e){ + } catch (Exception e) { status.setEmojis(new ArrayList<>()); } //Retrieve Application Application application = new Application(); try { - if(resobj.getJSONObject("application") != null){ + if (resobj.getJSONObject("application") != null) { application.setName(resobj.getJSONObject("application").getString("name")); application.setWebsite(resobj.getJSONObject("application").getString("website")); } - }catch (Exception e){ + } catch (Exception e) { application = new Application(); } status.setApplication(application); @@ -4788,41 +4895,42 @@ public class API { status.setContent(resobj.get("content").toString()); status.setFavourites_count(Integer.valueOf(resobj.get("favourites_count").toString())); status.setReblogs_count(Integer.valueOf(resobj.get("reblogs_count").toString())); - try{ + try { status.setReplies_count(Integer.valueOf(resobj.get("replies_count").toString())); - }catch (Exception e){ + } catch (Exception e) { status.setReplies_count(-1); } try { status.setReblogged(Boolean.valueOf(resobj.get("reblogged").toString())); - }catch (Exception e){ + } catch (Exception e) { status.setReblogged(false); } try { status.setFavourited(Boolean.valueOf(resobj.get("favourited").toString())); - }catch (Exception e){ + } catch (Exception e) { status.setFavourited(false); } try { status.setMuted(Boolean.valueOf(resobj.get("muted").toString())); - }catch (Exception e){ + } catch (Exception e) { status.setMuted(false); } try { status.setPinned(Boolean.valueOf(resobj.get("pinned").toString())); - }catch (JSONException e){ + } catch (JSONException e) { status.setPinned(false); } - try{ + try { status.setReblog(parseStatuses(context, resobj.getJSONObject("reblog"))); - }catch (Exception ignored){} + } catch (Exception ignored) { + } - if( resobj.has("poll") && !resobj.isNull("poll")){ + if (resobj.has("poll") && !resobj.isNull("poll")) { Poll poll = new Poll(); poll.setId(resobj.getJSONObject("poll").getString("id")); try { poll.setExpires_at(Helper.mstStringToDate(context, resobj.getJSONObject("poll").getString("expires_at"))); - }catch (Exception e){ + } catch (Exception e) { poll.setExpires_at(new Date()); } poll.setExpired(resobj.getJSONObject("poll").getBoolean("expired")); @@ -4831,7 +4939,7 @@ public class API { poll.setVoted(resobj.getJSONObject("poll").getBoolean("voted")); JSONArray options = resobj.getJSONObject("poll").getJSONArray("options"); List pollOptions = new ArrayList<>(); - for(int i = 0; i < options.length() ; i++){ + for (int i = 0; i < options.length(); i++) { JSONObject option = options.getJSONObject(i); PollOptions pollOption = new PollOptions(); pollOption.setTitle(option.getString("title")); @@ -4842,7 +4950,8 @@ public class API { status.setPoll(poll); } - } catch (JSONException ignored) {} catch (ParseException e) { + } catch (JSONException ignored) { + } catch (ParseException e) { e.printStackTrace(); } status.setViewType(context); @@ -4852,11 +4961,12 @@ public class API { /** * Parse json response for unique schedule + * * @param resobj JSONObject * @return Status */ @SuppressWarnings("InfiniteRecursion") - private static Status parseSchedule(Context context, JSONObject resobj){ + private static Status parseSchedule(Context context, JSONObject resobj) { Status status = new Status(); try { status.setIn_reply_to_id(resobj.get("in_reply_to_id").toString()); @@ -4864,23 +4974,27 @@ public class API { status.setSpoiler_text(resobj.get("spoiler_text").toString()); try { status.setVisibility(resobj.get("visibility").toString()); - }catch (Exception e){status.setVisibility("public");} + } catch (Exception e) { + status.setVisibility("public"); + } status.setContent(resobj.get("text").toString()); - } catch (JSONException ignored) {} + } catch (JSONException ignored) { + } return status; } /** * Parse json response for several notes (Misskey) + * * @param jsonArray JSONArray * @return List */ - public static List parseNotes(Context context, String instance, JSONArray jsonArray){ + public static List parseNotes(Context context, String instance, JSONArray jsonArray) { List statuses = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ){ + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Status status = parseNotes(context, instance, resobj); @@ -4896,11 +5010,12 @@ public class API { /** * Parse json response for unique note (misskey) + * * @param resobj JSONObject * @return Status */ @SuppressWarnings("InfiniteRecursion") - public static Status parseNotes(Context context, String instance, JSONObject resobj){ + public static Status parseNotes(Context context, String instance, JSONObject resobj) { Status status = new Status(); try { @@ -4909,14 +5024,17 @@ public class API { status.setCreated_at(Helper.mstStringToDate(context, resobj.get("createdAt").toString())); status.setIn_reply_to_id(resobj.get("replyId").toString()); status.setSensitive(false); - if(resobj.get("cw") != null && !resobj.get("cw").toString().equals("null")) + if (resobj.get("cw") != null && !resobj.get("cw").toString().equals("null")) status.setSpoiler_text(resobj.get("cw").toString()); try { status.setVisibility(resobj.get("visibility").toString()); - }catch (Exception e){status.setVisibility("public"); e.printStackTrace();} + } catch (Exception e) { + status.setVisibility("public"); + e.printStackTrace(); + } status.setUrl("https://" + instance + "/notes/" + resobj.get("id").toString()); //Retrieves attachments - if( resobj.has("media")) { + if (resobj.has("media")) { JSONArray arrayAttachement = resobj.getJSONArray("media"); ArrayList attachments = new ArrayList<>(); if (arrayAttachement != null) { @@ -4944,12 +5062,14 @@ public class API { } } status.setMedia_attachments(attachments); - }else{ + } else { status.setMedia_attachments(new ArrayList<>()); } try { status.setCard(parseCardResponse(resobj.getJSONObject("card"))); - }catch (Exception e){status.setCard(null);} + } catch (Exception e) { + status.setCard(null); + } //Retrieves mentions @@ -4958,25 +5078,26 @@ public class API { status.setAccount(parseMisskeyAccountResponse(context, instance, resobj.getJSONObject("user"))); status.setContent(resobj.get("text").toString()); - try{ + try { status.setReplies_count(Integer.valueOf(resobj.get("repliesCount").toString())); - }catch (Exception e){ + } catch (Exception e) { status.setReplies_count(-1); } try { status.setFavourited(Boolean.valueOf(resobj.get("isFavorited").toString())); - }catch (Exception e){ + } catch (Exception e) { status.setFavourited(false); } - try{ - if(resobj.getJSONObject("renoteId") != null && !resobj.getJSONObject("renoteId").toString().equals("null")) + try { + if (resobj.getJSONObject("renoteId") != null && !resobj.getJSONObject("renoteId").toString().equals("null")) status.setReblog(parseStatuses(context, resobj.getJSONObject("renote"))); - }catch (Exception ignored){} + } catch (Exception ignored) { + } status.setMentions(mentions); //Retrieves tags List tags = new ArrayList<>(); - if( resobj.has("tags")) { + if (resobj.has("tags")) { JSONArray arrayTag = resobj.getJSONArray("tags"); if (arrayTag != null) { for (int j = 0; j < arrayTag.length(); j++) { @@ -4992,7 +5113,7 @@ public class API { //Retrieves emjis List emojiList = new ArrayList<>(); - if( resobj.has("emojis")) { + if (resobj.has("emojis")) { JSONArray emojisTag = resobj.getJSONArray("emojis"); if (emojisTag != null) { for (int j = 0; j < emojisTag.length(); j++) { @@ -5007,27 +5128,30 @@ public class API { //Retrieve Application Application application = new Application(); try { - if(resobj.getJSONObject("application") != null){ + if (resobj.getJSONObject("application") != null) { application.setName(resobj.getJSONObject("application").getString("name")); application.setWebsite(resobj.getJSONObject("application").getString("website")); } - }catch (Exception e){ + } catch (Exception e) { application = new Application(); } status.setApplication(application); - } catch (JSONException ignored) {} catch (ParseException e) { + } catch (JSONException ignored) { + } catch (ParseException e) { e.printStackTrace(); } return status; } + /** * Parse json response an unique instance + * * @param resobj JSONObject * @return Instance */ - private Instance parseInstance(JSONObject resobj){ + private Instance parseInstance(JSONObject resobj) { Instance instance = new Instance(); try { @@ -5036,23 +5160,23 @@ public class API { instance.setDescription(resobj.get("description").toString()); instance.setEmail(resobj.get("email").toString()); instance.setVersion(resobj.get("version").toString()); - if( resobj.has("registrations")){ + if (resobj.has("registrations")) { instance.setRegistration(resobj.getBoolean("registrations")); - }else{ + } else { instance.setRegistration(false); } - if( resobj.has("approval_required")){ + if (resobj.has("approval_required")) { instance.setApproval_required(resobj.getBoolean("approval_required")); - }else{ + } else { instance.setApproval_required(false); } - if(resobj.has("poll_limits")){ + if (resobj.has("poll_limits")) { HashMap poll_limits = new HashMap<>(); JSONObject polllimits = resobj.getJSONObject("poll_limits"); - poll_limits.put("min_expiration",polllimits.getInt("min_expiration")); - poll_limits.put("max_options",polllimits.getInt("max_options")); - poll_limits.put("max_option_chars",polllimits.getInt("max_option_chars")); - poll_limits.put("max_expiration",polllimits.getInt("max_expiration")); + poll_limits.put("min_expiration", polllimits.getInt("min_expiration")); + poll_limits.put("max_options", polllimits.getInt("max_options")); + poll_limits.put("max_option_chars", polllimits.getInt("max_option_chars")); + poll_limits.put("max_expiration", polllimits.getInt("max_expiration")); instance.setPoll_limits(poll_limits); } } catch (JSONException e) { @@ -5062,18 +5186,18 @@ public class API { } - /** * Parse json response for several instance reg + * * @param jsonArray JSONArray * @return List */ - public List parseInstanceReg(JSONArray jsonArray){ + public List parseInstanceReg(JSONArray jsonArray) { List instanceRegs = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ){ + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); InstanceReg instanceReg = parseInstanceReg(resobj); i++; @@ -5087,10 +5211,11 @@ public class API { /** * Parse json response an unique instance for registering + * * @param resobj JSONObject * @return InstanceReg */ - private InstanceReg parseInstanceReg(JSONObject resobj){ + private InstanceReg parseInstanceReg(JSONObject resobj) { InstanceReg instanceReg = new InstanceReg(); try { instanceReg.setDomain(resobj.getString("domain")); @@ -5108,13 +5233,13 @@ public class API { } - /** * Parse Pleroma emojis + * * @param jsonObject JSONObject * @return List of emojis */ - private List parsePleromaEmojis(JSONObject jsonObject){ + private List parsePleromaEmojis(JSONObject jsonObject) { List emojis = new ArrayList<>(); Iterator iter = jsonObject.keys(); while (iter.hasNext()) { @@ -5127,7 +5252,8 @@ public class API { emojisObj.setStatic_url(Helper.getLiveInstanceWithProtocol(context) + url); emojisObj.setUrl(Helper.getLiveInstanceWithProtocol(context) + url); emojis.add(emojisObj); - } catch (JSONException ignored) { } + } catch (JSONException ignored) { + } } return emojis; } @@ -5135,17 +5261,18 @@ public class API { /** * Parse emojis + * * @param jsonArray JSONArray * @return List of emojis */ - private List parseEmojis(JSONArray jsonArray){ + private List parseEmojis(JSONArray jsonArray) { List emojis = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ) { + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Emojis emojis1 = parseEmojis(resobj); - if( emojis1.isVisible_in_picker()) + if (emojis1.isVisible_in_picker()) emojis.add(emojis1); i++; } @@ -5158,10 +5285,11 @@ public class API { /** * Parse json response for emoji + * * @param resobj JSONObject * @return Emojis */ - private static Emojis parseEmojis(JSONObject resobj){ + private static Emojis parseEmojis(JSONObject resobj) { Emojis emojis = new Emojis(); try { emojis.setShortcode(resobj.get("shortcode").toString()); @@ -5169,24 +5297,26 @@ public class API { emojis.setUrl(resobj.get("url").toString()); try { emojis.setVisible_in_picker((resobj.getBoolean("visible_in_picker"))); - }catch (Exception e){ + } catch (Exception e) { emojis.setVisible_in_picker(true); } - }catch (Exception ignored){} + } catch (Exception ignored) { + } return emojis; } /** * Parse emojis + * * @param jsonArray JSONArray * @return List of emojis */ - private List parseMisskeyEmojis(JSONArray jsonArray){ + private List parseMisskeyEmojis(JSONArray jsonArray) { List emojis = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ) { + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Emojis emojis1 = parseMisskeyEmojis(resobj); emojis.add(emojis1); @@ -5201,33 +5331,36 @@ public class API { /** * Parse json response for emoji + * * @param resobj JSONObject * @return Emojis */ - private static Emojis parseMisskeyEmojis(JSONObject resobj){ + private static Emojis parseMisskeyEmojis(JSONObject resobj) { Emojis emojis = new Emojis(); try { emojis.setShortcode(resobj.get("name").toString()); emojis.setStatic_url(resobj.get("url").toString()); emojis.setUrl(resobj.get("url").toString()); - }catch (Exception ignored){} + } catch (Exception ignored) { + } return emojis; } /** * Parse Filters + * * @param jsonArray JSONArray * @return List of filters */ - private List parseFilters(JSONArray jsonArray){ + private List parseFilters(JSONArray jsonArray) { List filters = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ) { + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Filters filter = parseFilter(resobj); - if( filter != null) + if (filter != null) filters.add(filter); i++; } @@ -5239,50 +5372,54 @@ public class API { /** * Parse json response for filter + * * @param resobj JSONObject * @return Filter */ - private Filters parseFilter(JSONObject resobj){ + private Filters parseFilter(JSONObject resobj) { Filters filter = new Filters(); try { filter.setId(resobj.get("id").toString()); - if( resobj.get("phrase").toString() == null) + if (resobj.get("phrase").toString() == null) return null; filter.setPhrase(resobj.get("phrase").toString()); - if( resobj.get("expires_at") != null && !resobj.get("expires_at").toString().equals("null")) + if (resobj.get("expires_at") != null && !resobj.get("expires_at").toString().equals("null")) filter.setSetExpires_at(Helper.mstStringToDate(context, resobj.get("expires_at").toString())); filter.setWhole_word(Boolean.parseBoolean(resobj.get("whole_word").toString())); filter.setIrreversible(Boolean.parseBoolean(resobj.get("irreversible").toString())); String contextString = resobj.get("context").toString(); - contextString = contextString.replaceAll("\\[",""); - contextString = contextString.replaceAll("]",""); - contextString = contextString.replaceAll("\"",""); - if( contextString != null) { + contextString = contextString.replaceAll("\\[", ""); + contextString = contextString.replaceAll("]", ""); + contextString = contextString.replaceAll("\"", ""); + if (contextString != null) { String[] context = contextString.split(","); - if( contextString.length() > 0 ){ + if (contextString.length() > 0) { ArrayList finalContext = new ArrayList<>(); - for(String c: context) + for (String c : context) finalContext.add(c.trim()); filter.setContext(finalContext); } } return filter; - }catch (Exception ignored){ return null;} + } catch (Exception ignored) { + return null; + } } /** * Parse Lists + * * @param jsonArray JSONArray * @return List of lists */ - private List parseLists(JSONArray jsonArray){ + private List parseLists(JSONArray jsonArray) { List lists = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ) { + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); app.fedilab.android.client.Entities.List list = parseList(resobj); lists.add(list); @@ -5297,23 +5434,25 @@ public class API { /** * Parse json response for emoji + * * @param resobj JSONObject * @return Emojis */ - private static app.fedilab.android.client.Entities.List parseList(JSONObject resobj){ + private static app.fedilab.android.client.Entities.List parseList(JSONObject resobj) { app.fedilab.android.client.Entities.List list = new app.fedilab.android.client.Entities.List(); try { list.setId(resobj.get("id").toString()); list.setTitle(resobj.get("title").toString()); - }catch (Exception ignored){} + } catch (Exception ignored) { + } return list; } - private List parseAccountResponsePeertube(Context context, String instance, JSONArray jsonArray){ + private List parseAccountResponsePeertube(Context context, String instance, JSONArray jsonArray) { List accounts = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ) { + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Account account = parseAccountResponsePeertube(context, instance, resobj); accounts.add(account); @@ -5327,43 +5466,45 @@ public class API { /** * Parse json response an unique peertube account + * * @param resobj JSONObject * @return Account */ - private static Account parseAccountResponsePeertube(Context context, String instance, JSONObject resobj){ + private static Account parseAccountResponsePeertube(Context context, String instance, JSONObject resobj) { Account account = new Account(); try { account.setId(resobj.get("id").toString()); account.setUsername(resobj.get("name").toString()); - account.setAcct(resobj.get("name").toString() + "@"+ resobj.get("host").toString()); + account.setAcct(resobj.get("name").toString() + "@" + resobj.get("host").toString()); account.setDisplay_name(resobj.get("displayName").toString()); account.setHost(resobj.get("host").toString()); - if( resobj.has("createdAt") ) + if (resobj.has("createdAt")) account.setCreated_at(Helper.mstStringToDate(context, resobj.get("createdAt").toString())); else account.setCreated_at(new Date()); - if( resobj.has("followersCount") ) + if (resobj.has("followersCount")) account.setFollowers_count(Integer.valueOf(resobj.get("followersCount").toString())); else account.setFollowers_count(0); - if( resobj.has("followingCount")) + if (resobj.has("followingCount")) account.setFollowing_count(Integer.valueOf(resobj.get("followingCount").toString())); else account.setFollowing_count(0); account.setStatuses_count(0); - if( resobj.has("description") ) + if (resobj.has("description")) account.setNote(resobj.get("description").toString()); else account.setNote(""); account.setUrl(resobj.get("url").toString()); account.setSocial("PEERTUBE"); - if( resobj.has("avatar") && !resobj.get("avatar").toString().equals("null")){ + if (resobj.has("avatar") && !resobj.get("avatar").toString().equals("null")) { account.setAvatar("https://" + instance + resobj.getJSONObject("avatar").get("path")); - }else + } else account.setAvatar(null); account.setAvatar_static(resobj.get("avatar").toString()); - } catch (JSONException ignored) {} catch (ParseException e) { + } catch (JSONException ignored) { + } catch (ParseException e) { e.printStackTrace(); } return account; @@ -5372,15 +5513,16 @@ public class API { /** * Parse json response for list of reports for admins + * * @param jsonArray JSONArray * @return List */ - private List parseReportAdminResponse(JSONArray jsonArray){ + private List parseReportAdminResponse(JSONArray jsonArray) { List reports = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ) { + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Report report = parseReportAdminResponse(context, resobj); reports.add(report); @@ -5394,43 +5536,44 @@ public class API { /** * Parse json response an unique report for admins + * * @param resobj JSONObject * @return AccountAdmin */ - private static Report parseReportAdminResponse(Context context, JSONObject resobj){ + private static Report parseReportAdminResponse(Context context, JSONObject resobj) { Report report = new Report(); try { report.setId(resobj.getString("id")); - if( !resobj.isNull("action_taken")) { + if (!resobj.isNull("action_taken")) { report.setAction_taken(resobj.getBoolean("action_taken")); - }else if( !resobj.isNull("state")) { + } else if (!resobj.isNull("state")) { report.setAction_taken(!resobj.getString("state").equals("open")); } - if( !resobj.isNull("comment")) { + if (!resobj.isNull("comment")) { report.setComment(resobj.getString("comment")); - }else if( !resobj.isNull("content")) { + } else if (!resobj.isNull("content")) { report.setComment(resobj.getString("content")); } report.setCreated_at(Helper.mstStringToDate(context, resobj.getString("created_at"))); - if( !resobj.isNull("updated_at")) { + if (!resobj.isNull("updated_at")) { report.setUpdated_at(Helper.mstStringToDate(context, resobj.getString("updated_at"))); } - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON){ - if( !resobj.isNull("account")) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { + if (!resobj.isNull("account")) { report.setAccount(parseAccountAdminResponse(context, resobj.getJSONObject("account"))); } - if( !resobj.isNull("target_account")) { + if (!resobj.isNull("target_account")) { report.setTarget_account(parseAccountAdminResponse(context, resobj.getJSONObject("target_account"))); } - if( !resobj.isNull("assigned_account")) { + if (!resobj.isNull("assigned_account")) { report.setAssigned_account(parseAccountAdminResponse(context, resobj.getJSONObject("assigned_account"))); } - }else if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA){ + } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { - if( !resobj.isNull("account")) { + if (!resobj.isNull("account")) { Account account = parseAccountResponse(context, resobj.getJSONObject("account")); AccountAdmin accountAdmin = new AccountAdmin(); accountAdmin.setId(account.getId()); @@ -5439,7 +5582,7 @@ public class API { report.setTarget_account(accountAdmin); } - if( !resobj.isNull("actor")) { + if (!resobj.isNull("actor")) { Account account = parseAccountResponse(context, resobj.getJSONObject("actor")); AccountAdmin accountAdmin = new AccountAdmin(); accountAdmin.setId(account.getId()); @@ -5450,26 +5593,29 @@ public class API { } - if( !resobj.isNull("action_taken_by_account")) { + if (!resobj.isNull("action_taken_by_account")) { report.setAction_taken_by_account(parseAccountAdminResponse(context, resobj.getJSONObject("action_taken_by_account"))); } report.setStatuses(parseStatuses(context, resobj.getJSONArray("statuses"))); - }catch (Exception ignored){ignored.printStackTrace();} + } catch (Exception ignored) { + ignored.printStackTrace(); + } return report; } /** * Parse json response for list of accounts for admins + * * @param jsonArray JSONArray * @return List */ - private List parseAccountAdminResponse(JSONArray jsonArray){ + private List parseAccountAdminResponse(JSONArray jsonArray) { List accountAdmins = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ) { + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); AccountAdmin accountAdmin = parseAccountAdminResponse(context, resobj); accountAdmins.add(accountAdmin); @@ -5483,99 +5629,103 @@ public class API { /** * Parse json response an unique account for admins + * * @param resobj JSONObject * @return Account */ - private static AccountAdmin parseAccountAdminResponse(Context context, JSONObject resobj){ + private static AccountAdmin parseAccountAdminResponse(Context context, JSONObject resobj) { AccountAdmin accountAdmin = new AccountAdmin(); try { accountAdmin.setId(resobj.get("id").toString()); - if( !resobj.isNull("username")) { + if (!resobj.isNull("username")) { accountAdmin.setUsername(resobj.getString("username")); } - if( !resobj.isNull("nickname")) { + if (!resobj.isNull("nickname")) { accountAdmin.setUsername(resobj.getString("nickname")); } - if( !resobj.isNull("created_at")) { + if (!resobj.isNull("created_at")) { accountAdmin.setCreated_at(Helper.mstStringToDate(context, resobj.getString("created_at"))); } - if( !resobj.isNull("email")) { + if (!resobj.isNull("email")) { accountAdmin.setEmail(resobj.getString("email")); } - if( !resobj.isNull("role")) { + if (!resobj.isNull("role")) { accountAdmin.setRole(resobj.getString("role")); } - if( !resobj.isNull("roles")) { - if(resobj.getJSONObject("roles").getBoolean("admin")){ + if (!resobj.isNull("roles")) { + if (resobj.getJSONObject("roles").getBoolean("admin")) { accountAdmin.setRole("admin"); - }else if(resobj.getJSONObject("roles").getBoolean("moderator")){ + } else if (resobj.getJSONObject("roles").getBoolean("moderator")) { accountAdmin.setRole("moderator"); - }else{ + } else { accountAdmin.setRole("user"); } } - if( !resobj.isNull("ip")) { + if (!resobj.isNull("ip")) { accountAdmin.setIp(resobj.getString("ip")); } - if( !resobj.isNull("domain")) { + if (!resobj.isNull("domain")) { accountAdmin.setDomain(resobj.getString("domain")); } - if( !resobj.isNull("account")) { + if (!resobj.isNull("account")) { accountAdmin.setAccount(parseAccountResponse(context, resobj.getJSONObject("account"))); - }else{ + } else { Account account = new Account(); account.setId(accountAdmin.getId()); account.setAcct(accountAdmin.getUsername()); account.setDisplay_name(accountAdmin.getUsername()); accountAdmin.setAccount(account); } - if( !resobj.isNull("confirmed")) { + if (!resobj.isNull("confirmed")) { accountAdmin.setConfirmed(resobj.getBoolean("confirmed")); - }else{ + } else { accountAdmin.setConfirmed(true); } - if( !resobj.isNull("suspended")) { + if (!resobj.isNull("suspended")) { accountAdmin.setSuspended(resobj.getBoolean("suspended")); - }else{ + } else { accountAdmin.setSuspended(false); } - if( !resobj.isNull("silenced")) { + if (!resobj.isNull("silenced")) { accountAdmin.setSilenced(resobj.getBoolean("silenced")); - }else{ + } else { accountAdmin.setSilenced(false); } - if( !resobj.isNull("disabled")) { + if (!resobj.isNull("disabled")) { accountAdmin.setDisabled(resobj.getBoolean("disabled")); - }else{ - if( !resobj.isNull("deactivated")) { + } else { + if (!resobj.isNull("deactivated")) { accountAdmin.setDisabled(resobj.getBoolean("deactivated")); - }else{ + } else { accountAdmin.setDisabled(false); } } - if( !resobj.isNull("approved")) { + if (!resobj.isNull("approved")) { accountAdmin.setApproved(resobj.getBoolean("approved")); - }else{ + } else { accountAdmin.setApproved(true); } - }catch (Exception ignored){ignored.printStackTrace();} + } catch (Exception ignored) { + ignored.printStackTrace(); + } return accountAdmin; } /** * Parse json response for list of accounts + * * @param jsonArray JSONArray * @return List */ - private List parseAccountResponse(JSONArray jsonArray){ + private List parseAccountResponse(JSONArray jsonArray) { List accounts = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ) { + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Account account = parseAccountResponse(context, resobj); accounts.add(account); @@ -5589,11 +5739,12 @@ public class API { /** * Parse json response an unique account + * * @param resobj JSONObject * @return Account */ @SuppressWarnings("InfiniteRecursion") - private static Account parseAccountResponse(Context context, JSONObject resobj){ + private static Account parseAccountResponse(Context context, JSONObject resobj) { Account account = new Account(); try { @@ -5603,9 +5754,9 @@ public class API { account.setAcct(resobj.get("acct").toString()); account.setDisplay_name(resobj.get("display_name").toString()); account.setLocked(Boolean.parseBoolean(resobj.get("locked").toString())); - if( resobj.has("created_at") && !resobj.isNull("created_at")) { + if (resobj.has("created_at") && !resobj.isNull("created_at")) { account.setCreated_at(Helper.mstStringToDate(context, resobj.get("created_at").toString())); - }else { + } else { account.setCreated_at(new Date()); } account.setFollowers_count(Integer.valueOf(resobj.get("followers_count").toString())); @@ -5614,109 +5765,113 @@ public class API { account.setNote(resobj.get("note").toString()); try { account.setBot(Boolean.parseBoolean(resobj.get("bot").toString())); - }catch (Exception e){ + } catch (Exception e) { account.setBot(false); } - try{ + try { account.setMoved_to_account(parseAccountResponse(context, resobj.getJSONObject("moved"))); - }catch (Exception ignored){account.setMoved_to_account(null);} + } catch (Exception ignored) { + account.setMoved_to_account(null); + } account.setUrl(resobj.get("url").toString()); account.setAvatar(resobj.get("avatar").toString()); account.setAvatar_static(resobj.get("avatar_static").toString()); account.setHeader(resobj.get("header").toString()); account.setHeader_static(resobj.get("header_static").toString()); - try{ + try { account.setSocial(resobj.get("software").toString().toUpperCase()); - }catch (Exception ignored){ + } catch (Exception ignored) { account.setSocial("MASTODON"); } - try{ - if( resobj.has("pleroma") ) { + try { + if (resobj.has("pleroma")) { account.setSocial("PLEROMA"); - try{ + try { account.setModerator(resobj.getJSONObject("pleroma").getBoolean("is_moderator")); account.setAdmin(resobj.getJSONObject("pleroma").getBoolean("is_admin")); - }catch (Exception ignored){ + } catch (Exception ignored) { account.setModerator(false); account.setAdmin(false); } } - }catch (Exception ignored){} + } catch (Exception ignored) { + } try { JSONArray fields = resobj.getJSONArray("fields"); LinkedHashMap fieldsMap = new LinkedHashMap<>(); LinkedHashMap fieldsMapVerified = new LinkedHashMap<>(); - if( fields != null){ - for(int j = 0 ; j < fields.length() ; j++){ - fieldsMap.put(fields.getJSONObject(j).getString("name"),fields.getJSONObject(j).getString("value")); + if (fields != null) { + for (int j = 0; j < fields.length(); j++) { + fieldsMap.put(fields.getJSONObject(j).getString("name"), fields.getJSONObject(j).getString("value")); try { - fieldsMapVerified.put(fields.getJSONObject(j).getString("name"),(fields.getJSONObject(j).getString("verified_at")!= null && !fields.getJSONObject(j).getString("verified_at").equals("null"))); - }catch (Exception e){ - fieldsMapVerified.put(fields.getJSONObject(j).getString("name"),false); + fieldsMapVerified.put(fields.getJSONObject(j).getString("name"), (fields.getJSONObject(j).getString("verified_at") != null && !fields.getJSONObject(j).getString("verified_at").equals("null"))); + } catch (Exception e) { + fieldsMapVerified.put(fields.getJSONObject(j).getString("name"), false); } } } account.setFields(fieldsMap); account.setFieldsVerified(fieldsMapVerified); - }catch (Exception ignored){} - + } catch (Exception ignored) { + } //Retrieves emjis List emojiList = new ArrayList<>(); try { JSONArray emojisTag = resobj.getJSONArray("emojis"); - if( emojisTag != null){ - for(int j = 0 ; j < emojisTag.length() ; j++){ + if (emojisTag != null) { + for (int j = 0; j < emojisTag.length(); j++) { JSONObject emojisObj = emojisTag.getJSONObject(j); Emojis emojis = parseEmojis(emojisObj); emojiList.add(emojis); } } account.setEmojis(emojiList); - }catch (Exception e){ + } catch (Exception e) { account.setEmojis(new ArrayList<>()); } - if( resobj.has("source")){ + if (resobj.has("source")) { JSONObject source = resobj.getJSONObject("source"); - try{ - if( source.has("privacy")) { + try { + if (source.has("privacy")) { account.setPrivacy(source.getString("privacy")); - }else{ + } else { account.setPrivacy("public"); } - if( source.has("sensitive")) { + if (source.has("sensitive")) { account.setSensitive(source.getBoolean("sensitive")); - }else{ + } else { account.setSensitive(false); } - }catch (Exception e){ + } catch (Exception e) { account.setPrivacy("public"); account.setSensitive(false); e.printStackTrace(); } } - } catch (JSONException ignored) {} catch (ParseException e) { + } catch (JSONException ignored) { + } catch (ParseException e) { e.printStackTrace(); } return account; } - private List parseOpencollectiveAccountResponse(Context context, RetrieveOpenCollectiveAsyncTask.Type type, JSONArray jsonArray){ + private List parseOpencollectiveAccountResponse(Context context, RetrieveOpenCollectiveAsyncTask.Type type, JSONArray jsonArray) { List accounts = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ) { + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Account account = parseOpencollectiveAccountResponse(context, type, resobj); - if( type == RetrieveOpenCollectiveAsyncTask.Type.BACKERS && account.getSocial() != null && account.getSocial().equals("OPENCOLLECTIVE_BACKER")) + if (type == RetrieveOpenCollectiveAsyncTask.Type.BACKERS && account.getSocial() != null && account.getSocial().equals("OPENCOLLECTIVE_BACKER")) accounts.add(account); - else if( type == RetrieveOpenCollectiveAsyncTask.Type.SPONSORS && account.getSocial() != null && account.getSocial().equals("OPENCOLLECTIVE_SPONSOR")) + else if (type == RetrieveOpenCollectiveAsyncTask.Type.SPONSORS && account.getSocial() != null && account.getSocial().equals("OPENCOLLECTIVE_SPONSOR")) accounts.add(account); i++; } @@ -5728,11 +5883,12 @@ public class API { /** * Parse json response an unique account + * * @param resobj JSONObject * @return Account */ @SuppressWarnings("InfiniteRecursion") - private static Account parseOpencollectiveAccountResponse(Context context, RetrieveOpenCollectiveAsyncTask.Type type, JSONObject resobj){ + private static Account parseOpencollectiveAccountResponse(Context context, RetrieveOpenCollectiveAsyncTask.Type type, JSONObject resobj) { Account account = new Account(); try { @@ -5754,14 +5910,15 @@ public class API { account.setAvatar_static(resobj.get("image").toString()); account.setHeader(null); account.setHeader_static(null); - if(resobj.get("role").toString().equals("BACKER")) + if (resobj.get("role").toString().equals("BACKER")) account.setSocial("OPENCOLLECTIVE_BACKER"); - else if(resobj.get("role").toString().equals("SPONSOR")) + else if (resobj.get("role").toString().equals("SPONSOR")) account.setSocial("OPENCOLLECTIVE_SPONSOR"); else account.setSocial("OPENCOLLECTIVE"); - } catch (JSONException ignored) {} catch (ParseException e) { + } catch (JSONException ignored) { + } catch (ParseException e) { e.printStackTrace(); } return account; @@ -5769,11 +5926,12 @@ public class API { /** * Parse json response an unique account + * * @param resobj JSONObject * @return Account */ @SuppressWarnings("InfiniteRecursion") - private static Account parseMisskeyAccountResponse(Context context, String instance, JSONObject resobj){ + private static Account parseMisskeyAccountResponse(Context context, String instance, JSONObject resobj) { Account account = new Account(); try { @@ -5781,9 +5939,9 @@ public class API { account.setUsername(resobj.get("username").toString()); String host = null; String acct; - if( resobj.isNull("host")) { + if (resobj.isNull("host")) { acct = resobj.get("username").toString(); - }else{ + } else { host = resobj.get("host").toString(); acct = resobj.get("username").toString() + "@" + host; } @@ -5791,20 +5949,20 @@ public class API { account.setDisplay_name(resobj.get("name").toString()); account.setCreated_at(new Date()); - account.setUrl("https://" + instance + "/@"+account.getUsername()); + account.setUrl("https://" + instance + "/@" + account.getUsername()); account.setAvatar(resobj.get("avatarUrl").toString()); account.setAvatar_static(resobj.get("avatarUrl").toString()); try { account.setBot(Boolean.parseBoolean(resobj.get("isBot").toString())); - }catch (Exception e){ + } catch (Exception e) { account.setBot(false); } //Retrieves emjis List emojiList = new ArrayList<>(); - if( resobj.has("emojis")){ + if (resobj.has("emojis")) { JSONArray emojisTag = resobj.getJSONArray("emojis"); - if( emojisTag != null){ - for(int j = 0 ; j < emojisTag.length() ; j++){ + if (emojisTag != null) { + for (int j = 0; j < emojisTag.length(); j++) { JSONObject emojisObj = emojisTag.getJSONObject(j); Emojis emojis = parseEmojis(emojisObj); emojiList.add(emojis); @@ -5812,18 +5970,20 @@ public class API { } } account.setEmojis(emojiList); - } catch (JSONException ignored) {ignored.printStackTrace();} + } catch (JSONException ignored) { + ignored.printStackTrace(); + } return account; } - /** * Parse json response an unique relationship + * * @param resobj JSONObject * @return Relationship */ - private Relationship parseRelationshipResponse(JSONObject resobj){ + private Relationship parseRelationshipResponse(JSONObject resobj) { Relationship relationship = new Relationship(); try { @@ -5834,22 +5994,22 @@ public class API { relationship.setMuting(Boolean.valueOf(resobj.get("muting").toString())); try { relationship.setMuting_notifications(Boolean.valueOf(resobj.get("muting_notifications").toString())); - }catch (Exception ignored){ + } catch (Exception ignored) { relationship.setMuting_notifications(true); } try { relationship.setEndorsed(Boolean.valueOf(resobj.get("endorsed").toString())); - }catch (Exception ignored){ + } catch (Exception ignored) { relationship.setMuting_notifications(false); } try { relationship.setShowing_reblogs(Boolean.valueOf(resobj.get("showing_reblogs").toString())); - }catch (Exception ignored){ + } catch (Exception ignored) { relationship.setMuting_notifications(false); } try { relationship.setBlocked_by(resobj.getBoolean("blocked_by")); - }catch (Exception ignored){ + } catch (Exception ignored) { relationship.setBlocked_by(false); } relationship.setRequested(Boolean.valueOf(resobj.get("requested").toString())); @@ -5862,15 +6022,16 @@ public class API { /** * Parse json response for list of relationship + * * @param jsonArray JSONArray * @return List */ - private List parseRelationshipResponse(JSONArray jsonArray){ + private List parseRelationshipResponse(JSONArray jsonArray) { List relationships = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ) { + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Relationship relationship = parseRelationshipResponse(resobj); relationships.add(relationship); @@ -5884,10 +6045,11 @@ public class API { /** * Parse json response for the context + * * @param jsonObject JSONObject * @return Context */ - private app.fedilab.android.client.Entities.Context parseContext(JSONObject jsonObject){ + private app.fedilab.android.client.Entities.Context parseContext(JSONObject jsonObject) { app.fedilab.android.client.Entities.Context context = new app.fedilab.android.client.Entities.Context(); try { @@ -5900,32 +6062,35 @@ public class API { } - /** * Parse json response for list of relationship + * * @param jsonArray JSONArray * @return List */ - private static List parseAttachmentResponse(JSONArray jsonArray){ + private static List parseAttachmentResponse(JSONArray jsonArray) { List attachments = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ) { + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Attachment attachment = parseAttachmentResponse(resobj); attachments.add(attachment); i++; } - } catch (JSONException ignored) { } + } catch (JSONException ignored) { + } return attachments; } + /** * Parse json response an unique attachment + * * @param resobj JSONObject * @return Relationship */ - public static Attachment parseAttachmentResponse(JSONObject resobj){ + public static Attachment parseAttachmentResponse(JSONObject resobj) { Attachment attachment = new Attachment(); try { @@ -5934,32 +6099,38 @@ public class API { attachment.setUrl(resobj.get("url").toString()); try { attachment.setDescription(resobj.get("description").toString()); - }catch (JSONException ignore){} - try{ + } catch (JSONException ignore) { + } + try { attachment.setRemote_url(resobj.get("remote_url").toString()); - }catch (JSONException ignore){} - try{ + } catch (JSONException ignore) { + } + try { attachment.setPreview_url(resobj.get("preview_url").toString()); - }catch (JSONException ignore){} - try{ + } catch (JSONException ignore) { + } + try { attachment.setMeta(resobj.get("meta").toString()); - }catch (JSONException ignore){} - try{ + } catch (JSONException ignore) { + } + try { attachment.setText_url(resobj.get("text_url").toString()); - }catch (JSONException ignore){} + } catch (JSONException ignore) { + } - } catch (JSONException ignored) {} + } catch (JSONException ignored) { + } return attachment; } - /** * Parse json response an unique notification + * * @param resobj JSONObject * @return Account */ - public static Notification parseNotificationResponse(Context context, JSONObject resobj){ + public static Notification parseNotificationResponse(Context context, JSONObject resobj) { Notification notification = new Notification(); try { @@ -5967,11 +6138,13 @@ public class API { notification.setType(resobj.get("type").toString()); notification.setCreated_at(Helper.mstStringToDate(context, resobj.get("created_at").toString())); notification.setAccount(parseAccountResponse(context, resobj.getJSONObject("account"))); - try{ + try { notification.setStatus(parseStatuses(context, resobj.getJSONObject("status"))); - }catch (Exception ignored){} + } catch (Exception ignored) { + } notification.setCreated_at(Helper.mstStringToDate(context, resobj.get("created_at").toString())); - } catch (JSONException ignored) {} catch (ParseException e) { + } catch (JSONException ignored) { + } catch (ParseException e) { e.printStackTrace(); } return notification; @@ -5979,15 +6152,16 @@ public class API { /** * Parse json response for list of notifications + * * @param jsonArray JSONArray * @return List */ - private List parseNotificationResponse(JSONArray jsonArray){ + private List parseNotificationResponse(JSONArray jsonArray) { List notifications = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ) { + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Notification notification = parseNotificationResponse(context, resobj); @@ -6001,13 +6175,13 @@ public class API { } - /** * Set the error message + * * @param statusCode int code - * @param error Throwable error + * @param error Throwable error */ - private void setError(int statusCode, Throwable error){ + private void setError(int statusCode, Throwable error) { APIError = new Error(); APIError.setStatusCode(statusCode); String message = statusCode + " - " + error.getMessage(); @@ -6016,7 +6190,7 @@ public class API { String errorM = jsonObject.get("error").toString(); message = "Error " + statusCode + " : " + errorM; } catch (JSONException e) { - if(error.getMessage().split(".").length > 0) { + if (error.getMessage().split(".").length > 0) { String errorM = error.getMessage().split(".")[0]; message = "Error " + statusCode + " : " + errorM; } @@ -6025,11 +6199,11 @@ public class API { apiResponse.setError(APIError); } - private void setDefaultError(Exception e){ + private void setDefaultError(Exception e) { APIError = new Error(); - if( e.getLocalizedMessage() != null && e.getLocalizedMessage().trim().length() > 0) + if (e.getLocalizedMessage() != null && e.getLocalizedMessage().trim().length() > 0) APIError.setError(e.getLocalizedMessage()); - else if( e.getMessage() != null && e.getMessage().trim().length() > 0) + else if (e.getMessage() != null && e.getMessage().trim().length() > 0) APIError.setError(e.getMessage()); else APIError.setError(context.getString(R.string.toast_error)); @@ -6037,7 +6211,7 @@ public class API { } - public Error getError(){ + public Error getError() { return APIError; } @@ -6045,9 +6219,11 @@ public class API { private String getAbsoluteUrl(String action) { return Helper.instanceWithProtocol(this.context, this.instance) + "/api/v1" + action; } + private String getAbsoluteUr2l(String action) { return Helper.instanceWithProtocol(this.context, this.instance) + "/api/v2" + action; } + private String getAbsoluteUrlRemote(String remote, String action) { return "https://" + remote + "/api/v1" + action; } @@ -6057,7 +6233,7 @@ public class API { } private String getAbsoluteUrlCommunitywiki(String action) { - return "https://communitywiki.org/trunk/api/v1" + action; + return "https://communitywiki.org/trunk/api/v1" + action; } } diff --git a/app/src/main/java/app/fedilab/android/client/CustomSharing.java b/app/src/main/java/app/fedilab/android/client/CustomSharing.java index 8259a8c20..50161fe5c 100644 --- a/app/src/main/java/app/fedilab/android/client/CustomSharing.java +++ b/app/src/main/java/app/fedilab/android/client/CustomSharing.java @@ -41,7 +41,7 @@ public class CustomSharing { public CustomSharing(Context context) { this.context = context; - if( context == null) { + if (context == null) { CustomSharingError = new Error(); return; } @@ -71,17 +71,18 @@ public class CustomSharing { return customSharingResponse; } - public Error getError(){ + public Error getError() { return CustomSharingError; } /** * Set the error message + * * @param statusCode int code - * @param error Throwable error + * @param error Throwable error */ - private void setError(int statusCode, Throwable error){ + private void setError(int statusCode, Throwable error) { CustomSharingError = new Error(); CustomSharingError.setStatusCode(statusCode); String message = statusCode + " - " + error.getMessage(); @@ -90,7 +91,7 @@ public class CustomSharing { String errorM = jsonObject.get("error").toString(); message = "Error " + statusCode + " : " + errorM; } catch (JSONException e) { - if(error.getMessage().split(".").length > 0) { + if (error.getMessage().split(".").length > 0) { String errorM = error.getMessage().split(".")[0]; message = "Error " + statusCode + " : " + errorM; } diff --git a/app/src/main/java/app/fedilab/android/client/Entities/Account.java b/app/src/main/java/app/fedilab/android/client/Entities/Account.java index e2c64490a..96253701d 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/Account.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/Account.java @@ -25,9 +25,11 @@ import android.os.Build; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; + import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; + import android.text.Html; import android.text.Spannable; import android.text.SpannableString; @@ -137,7 +139,6 @@ public class Account implements Parcelable { private boolean emojiFound = false; - @Override public int describeContents() { return 0; @@ -249,7 +250,7 @@ public class Account implements Parcelable { this.isModerator = in.readByte() != 0; this.isAdmin = in.readByte() != 0; this.privacy = in.readString(); - this.sensitive =in.readByte() != 0; + this.sensitive = in.readByte() != 0; this.locale = in.readString(); this.invite_request = in.readString(); this.created_by_application_id = in.readString(); @@ -470,7 +471,7 @@ public class Account implements Parcelable { } - public enum followAction{ + public enum followAction { FOLLOW, NOT_FOLLOW, BLOCK, @@ -675,62 +676,64 @@ public class Account implements Parcelable { /** * Makes the move to account clickable + * * @param context Context * @return SpannableString */ - public SpannableString moveToText(final android.content.Context context){ + public SpannableString moveToText(final android.content.Context context) { SpannableString spannableString = null; - if( this.getMoved_to_account() != null) { - spannableString = new SpannableString(context.getString(R.string.account_moved_to, this.getAcct(), "@"+this.getMoved_to_account().getAcct())); - int startPositionTar = spannableString.toString().indexOf("@"+this.getMoved_to_account().getAcct()); - int endPositionTar = startPositionTar + ("@"+this.getMoved_to_account().getAcct()).length(); + if (this.getMoved_to_account() != null) { + spannableString = new SpannableString(context.getString(R.string.account_moved_to, this.getAcct(), "@" + this.getMoved_to_account().getAcct())); + int startPositionTar = spannableString.toString().indexOf("@" + this.getMoved_to_account().getAcct()); + int endPositionTar = startPositionTar + ("@" + this.getMoved_to_account().getAcct()).length(); final Account idTar = this.getMoved_to_account(); - if( endPositionTar <= spannableString.toString().length() && endPositionTar >= startPositionTar) + if (endPositionTar <= spannableString.toString().length() && endPositionTar >= startPositionTar) spannableString.setSpan(new ClickableSpan() { - @Override - public void onClick(@NonNull View textView) { - Intent intent = new Intent(context, ShowAccountActivity.class); - Bundle b = new Bundle(); - b.putParcelable("account", idTar); - intent.putExtras(b); - context.startActivity(intent); - } - @Override - public void updateDrawState(@NonNull TextPaint ds) { - super.updateDrawState(ds); - } - }, + @Override + public void onClick(@NonNull View textView) { + Intent intent = new Intent(context, ShowAccountActivity.class); + Bundle b = new Bundle(); + b.putParcelable("account", idTar); + intent.putExtras(b); + context.startActivity(intent); + } + + @Override + public void updateDrawState(@NonNull TextPaint ds) { + super.updateDrawState(ds); + } + }, startPositionTar, endPositionTar, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); } return spannableString; } - public void makeEmojisAccountProfile(final Context context, final OnRetrieveEmojiAccountInterface listener, Account account){ - if( ((Activity)context).isFinishing() ) + public void makeEmojisAccountProfile(final Context context, final OnRetrieveEmojiAccountInterface listener, Account account) { + if (((Activity) context).isFinishing()) return; - if( fields == null) + if (fields == null) fields = new LinkedHashMap<>(); - if( fieldsSpan == null) + if (fieldsSpan == null) fieldsSpan = new LinkedHashMap<>(); - if( account.getDisplay_name() != null) + if (account.getDisplay_name() != null) displayNameSpan = new SpannableString(account.getDisplay_name()); ArrayList accountsMentionUnknown = new ArrayList<>(); - if( account.getFields() != null && account.getFields().size() > 0) { + if (account.getFields() != null && account.getFields().size() > 0) { Iterator it = account.getFields().entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); SpannableString fieldSpan; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) - fieldSpan = new SpannableString(Html.fromHtml((String)pair.getValue(), FROM_HTML_MODE_LEGACY)); + fieldSpan = new SpannableString(Html.fromHtml((String) pair.getValue(), FROM_HTML_MODE_LEGACY)); else //noinspection deprecation - fieldSpan = new SpannableString(Html.fromHtml((String)pair.getValue())); - fieldsSpan.put(new SpannableString((String)pair.getKey()), fieldSpan); + fieldSpan = new SpannableString(Html.fromHtml((String) pair.getValue())); + fieldsSpan.put(new SpannableString((String) pair.getKey()), fieldSpan); Pattern aLink = Pattern.compile("(<\\s?a\\s?href=\"https?:\\/\\/([\\da-z\\.-]+\\.[a-z\\.]{2,10})\\/(@[\\/\\w._-]*)\"\\s?[^.]*<\\s?\\/\\s?a\\s?>)"); - Matcher matcherALink = aLink.matcher((String)pair.getValue()); - while (matcherALink.find()){ - String acct = matcherALink.group(3).replace("@",""); + Matcher matcherALink = aLink.matcher((String) pair.getValue()); + while (matcherALink.find()) { + String acct = matcherALink.group(3).replace("@", ""); String instance = matcherALink.group(2); Account accountMention = new Account(); accountMention.setAcct(acct); @@ -752,24 +755,25 @@ public class Account implements Parcelable { Matcher matcher = Helper.xmppPattern.matcher(fieldSpan); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - while (matcher.find()){ + while (matcher.find()) { URLSpan[] urls = fieldSpan.getSpans(0, fieldSpan.length(), URLSpan.class); - for(URLSpan span : urls) + for (URLSpan span : urls) fieldSpan.removeSpan(span); int matchStart = matcher.start(0); int matchEnd = matcher.end(); final String url = fieldSpan.toString().substring(matchStart, matchEnd); - if( matchEnd <= fieldSpan.toString().length() && matchEnd >= matchStart) { + if (matchEnd <= fieldSpan.toString().length() && matchEnd >= matchStart) { fieldSpan.setSpan(new ClickableSpan() { @Override public void onClick(@NonNull View textView) { try { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); context.startActivity(intent); - }catch (Exception e){ + } catch (Exception e) { Toasty.error(context, context.getString(R.string.toast_no_apps), Toast.LENGTH_LONG).show(); } } + @Override public void updateDrawState(@NonNull TextPaint ds) { super.updateDrawState(ds); @@ -787,14 +791,14 @@ public class Account implements Parcelable { } matcher = android.util.Patterns.EMAIL_ADDRESS.matcher(fieldSpan); - while (matcher.find()){ + while (matcher.find()) { URLSpan[] urls = fieldSpan.getSpans(0, fieldSpan.length(), URLSpan.class); - for(URLSpan span : urls) + for (URLSpan span : urls) fieldSpan.removeSpan(span); int matchStart = matcher.start(0); int matchEnd = matcher.end(); final String email = fieldSpan.toString().substring(matchStart, matchEnd); - if( matchEnd <= fieldSpan.toString().length() && matchEnd >= matchStart) { + if (matchEnd <= fieldSpan.toString().length() && matchEnd >= matchStart) { fieldSpan.setSpan(new ClickableSpan() { @Override public void onClick(@NonNull View textView) { @@ -803,10 +807,11 @@ public class Account implements Parcelable { emailIntent.setType("plain/text"); emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{email}); context.startActivity(Intent.createChooser(emailIntent, context.getString(R.string.send_email))); - }catch (Exception e){ + } catch (Exception e) { Toasty.error(context, context.getString(R.string.toast_no_apps), Toast.LENGTH_LONG).show(); } } + @Override public void updateDrawState(@NonNull TextPaint ds) { super.updateDrawState(ds); @@ -824,14 +829,14 @@ public class Account implements Parcelable { } matcher = hashtagPattern.matcher(fieldSpan); - while (matcher.find()){ + while (matcher.find()) { URLSpan[] urls = fieldSpan.getSpans(0, fieldSpan.length(), URLSpan.class); - for(URLSpan span : urls) + for (URLSpan span : urls) fieldSpan.removeSpan(span); int matchStart = matcher.start(1); int matchEnd = matcher.end(); final String tag = fieldSpan.toString().substring(matchStart, matchEnd); - if( matchEnd <= fieldSpan.toString().length() && matchEnd >= matchStart) + if (matchEnd <= fieldSpan.toString().length() && matchEnd >= matchStart) fieldSpan.setSpan(new ClickableSpan() { @Override public void onClick(@NonNull View textView) { @@ -841,6 +846,7 @@ public class Account implements Parcelable { intent.putExtras(b); context.startActivity(intent); } + @Override public void updateDrawState(@NonNull TextPaint ds) { super.updateDrawState(ds); @@ -854,36 +860,37 @@ public class Account implements Parcelable { } }, matchStart, matchEnd, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); } - if( accountsMentionUnknown.size() > 0 ) { - for(Account accountMention: accountsMentionUnknown){ + if (accountsMentionUnknown.size() > 0) { + for (Account accountMention : accountsMentionUnknown) { String targetedAccount = "@" + accountMention.getAcct(); if (fieldSpan.toString().toLowerCase().contains(targetedAccount.toLowerCase())) { //Accounts can be mentioned several times so we have to loop - for(int startPosition = -1 ; (startPosition = fieldSpan.toString().toLowerCase().indexOf(targetedAccount.toLowerCase(), startPosition + 1)) != -1 ; startPosition++){ + for (int startPosition = -1; (startPosition = fieldSpan.toString().toLowerCase().indexOf(targetedAccount.toLowerCase(), startPosition + 1)) != -1; startPosition++) { URLSpan[] urls = fieldSpan.getSpans(0, fieldSpan.length(), URLSpan.class); - for(URLSpan span : urls) + for (URLSpan span : urls) fieldSpan.removeSpan(span); int endPosition = startPosition + targetedAccount.length(); - if( endPosition <= fieldSpan.toString().length() && endPosition >= startPosition) + if (endPosition <= fieldSpan.toString().length() && endPosition >= startPosition) fieldSpan.setSpan(new ClickableSpan() { - @Override - public void onClick(@NonNull View textView) { - CrossActions.doCrossProfile(context,accountMention); - } - @Override - public void updateDrawState(@NonNull TextPaint ds) { - super.updateDrawState(ds); - ds.setUnderlineText(false); - if (theme == THEME_DARK) - ds.setColor(ContextCompat.getColor(context, R.color.dark_link_toot)); - else if (theme == THEME_BLACK) - ds.setColor(ContextCompat.getColor(context, R.color.black_link_toot)); - else if (theme == THEME_LIGHT) - ds.setColor(ContextCompat.getColor(context, R.color.mastodonC4)); - } - }, - startPosition, endPosition, - Spanned.SPAN_INCLUSIVE_EXCLUSIVE); + @Override + public void onClick(@NonNull View textView) { + CrossActions.doCrossProfile(context, accountMention); + } + + @Override + public void updateDrawState(@NonNull TextPaint ds) { + super.updateDrawState(ds); + ds.setUnderlineText(false); + if (theme == THEME_DARK) + ds.setColor(ContextCompat.getColor(context, R.color.dark_link_toot)); + else if (theme == THEME_BLACK) + ds.setColor(ContextCompat.getColor(context, R.color.black_link_toot)); + else if (theme == THEME_LIGHT) + ds.setColor(ContextCompat.getColor(context, R.color.mastodonC4)); + } + }, + startPosition, endPosition, + Spanned.SPAN_INCLUSIVE_EXCLUSIVE); } } } @@ -903,20 +910,21 @@ public class Account implements Parcelable { matcher = Patterns.WEB_URL.matcher(fieldSpan); else matcher = Helper.urlPattern.matcher(fieldSpan); - while (matcher.find()){ + while (matcher.find()) { URLSpan[] urls = fieldSpan.getSpans(0, fieldSpan.length(), URLSpan.class); - for(URLSpan span : urls) + for (URLSpan span : urls) fieldSpan.removeSpan(span); int matchStart = matcher.start(0); int matchEnd = matcher.end(); final String url = fieldSpan.toString().substring(matchStart, matchEnd); - if( matchEnd <= fieldSpan.toString().length() && matchEnd >= matchStart) { + if (matchEnd <= fieldSpan.toString().length() && matchEnd >= matchStart) { int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); fieldSpan.setSpan(new ClickableSpan() { @Override public void onClick(@NonNull View textView) { Helper.openBrowser(context, url); } + @Override public void updateDrawState(@NonNull TextPaint ds) { super.updateDrawState(ds); @@ -938,11 +946,10 @@ public class Account implements Parcelable { } - final List emojis = account.getEmojis(); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); boolean disableAnimatedEmoji = sharedpreferences.getBoolean(Helper.SET_DISABLE_ANIMATED_EMOJI, false); - if( emojis != null && emojis.size() > 0 ) { + if (emojis != null && emojis.size() > 0) { final int[] i = {0}; for (final Emojis emoji : emojis) { @@ -962,7 +969,7 @@ public class Account implements Parcelable { } else { resource = Drawable.createFromPath(resourceFile.getAbsolutePath()); } - if( resource == null){ + if (resource == null) { return; } final String targetedEmoji = ":" + emoji.getShortcode() + ":"; @@ -971,13 +978,13 @@ public class Account implements Parcelable { //emojis can be used several times so we have to loop for (int startPosition = -1; (startPosition = noteSpan.toString().indexOf(targetedEmoji, startPosition + 1)) != -1; startPosition++) { final int endPosition = startPosition + targetedEmoji.length(); - if (endPosition <= noteSpan.toString().length() && endPosition >= startPosition){ + if (endPosition <= noteSpan.toString().length() && endPosition >= startPosition) { ImageSpan imageSpan; - if( !disableAnimatedEmoji) { + if (!disableAnimatedEmoji) { resource.setBounds(0, 0, (int) Helper.convertDpToPixel(20, context), (int) Helper.convertDpToPixel(20, context)); resource.setVisible(true, true); imageSpan = new ImageSpan(resource); - }else{ + } else { resource.setVisible(true, true); Bitmap bitmap = drawableToBitmap(resource.getCurrent()); imageSpan = new ImageSpan(context, @@ -994,13 +1001,13 @@ public class Account implements Parcelable { //emojis can be used several times so we have to loop for (int startPosition = -1; (startPosition = displayNameSpan.toString().indexOf(targetedEmoji, startPosition + 1)) != -1; startPosition++) { final int endPosition = startPosition + targetedEmoji.length(); - if (endPosition <= displayNameSpan.toString().length() && endPosition >= startPosition){ + if (endPosition <= displayNameSpan.toString().length() && endPosition >= startPosition) { ImageSpan imageSpan; - if( !disableAnimatedEmoji) { + if (!disableAnimatedEmoji) { resource.setBounds(0, 0, (int) Helper.convertDpToPixel(20, context), (int) Helper.convertDpToPixel(20, context)); resource.setVisible(true, true); imageSpan = new ImageSpan(resource); - }else{ + } else { resource.setVisible(true, true); Bitmap bitmap = drawableToBitmap(resource.getCurrent()); imageSpan = new ImageSpan(context, @@ -1022,13 +1029,13 @@ public class Account implements Parcelable { //emojis can be used several times so we have to loop for (int startPosition = -1; (startPosition = fieldSpan.toString().indexOf(targetedEmoji, startPosition + 1)) != -1; startPosition++) { final int endPosition = startPosition + targetedEmoji.length(); - if (endPosition <= fieldSpan.toString().length() && endPosition >= startPosition){ + if (endPosition <= fieldSpan.toString().length() && endPosition >= startPosition) { ImageSpan imageSpan; - if( !disableAnimatedEmoji) { + if (!disableAnimatedEmoji) { resource.setBounds(0, 0, (int) Helper.convertDpToPixel(20, context), (int) Helper.convertDpToPixel(20, context)); resource.setVisible(true, true); imageSpan = new ImageSpan(resource); - }else{ + } else { resource.setVisible(true, true); Bitmap bitmap = drawableToBitmap(resource.getCurrent()); imageSpan = new ImageSpan(context, @@ -1041,7 +1048,7 @@ public class Account implements Parcelable { } } fieldsSpan.put((SpannableString) pair.getKey(), fieldSpan); - }else + } else fieldsSpan.put(keySpan, fieldSpan); } @@ -1056,10 +1063,11 @@ public class Account implements Parcelable { } }); - }catch (Exception ignored){} + } catch (Exception ignored) { + } } - }else { + } else { if (listener != null) listener.onRetrieveEmojiAccount(account); } @@ -1067,18 +1075,18 @@ public class Account implements Parcelable { } - public static void makeAccountNameEmoji(final Context context, final OnRetrieveEmojiAccountInterface listener, Account account){ - if( ((Activity)context).isFinishing() ) + public static void makeAccountNameEmoji(final Context context, final OnRetrieveEmojiAccountInterface listener, Account account) { + if (((Activity) context).isFinishing()) return; account.setdisplayNameSpan(new SpannableString(account.getDisplay_name())); SpannableString displayNameSpan = account.getdisplayNameSpan(); - if( displayNameSpan == null) + if (displayNameSpan == null) return; final List emojis = account.getEmojis(); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); boolean disableAnimatedEmoji = sharedpreferences.getBoolean(Helper.SET_DISABLE_ANIMATED_EMOJI, false); - if( emojis != null && emojis.size() > 0 ) { + if (emojis != null && emojis.size() > 0) { final int[] i = {0}; for (final Emojis emoji : emojis) { try { @@ -1093,13 +1101,13 @@ public class Account implements Parcelable { //emojis can be used several times so we have to loop for (int startPosition = -1; (startPosition = displayNameSpan.toString().indexOf(targetedEmoji, startPosition + 1)) != -1; startPosition++) { final int endPosition = startPosition + targetedEmoji.length(); - if (endPosition <= displayNameSpan.toString().length() && endPosition >= startPosition){ + if (endPosition <= displayNameSpan.toString().length() && endPosition >= startPosition) { ImageSpan imageSpan; - if( !disableAnimatedEmoji) { + if (!disableAnimatedEmoji) { resource.setBounds(0, 0, (int) Helper.convertDpToPixel(20, context), (int) Helper.convertDpToPixel(20, context)); resource.setVisible(true, true); imageSpan = new ImageSpan(resource); - }else{ + } else { Bitmap bitmap = drawableToBitmap(resource.getCurrent()); imageSpan = new ImageSpan(context, Bitmap.createScaledBitmap(bitmap, (int) Helper.convertDpToPixel(20, context), @@ -1121,15 +1129,16 @@ public class Account implements Parcelable { }); - }catch (Exception ignored){} + } catch (Exception ignored) { + } } } } @NotNull - public String toString(){ - return this.getAcct()+ " - " + this.getUrl(); + public String toString() { + return this.getAcct() + " - " + this.getUrl(); } diff --git a/app/src/main/java/app/fedilab/android/client/Entities/AccountAdmin.java b/app/src/main/java/app/fedilab/android/client/Entities/AccountAdmin.java index 112567a7b..fcde9bf24 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/AccountAdmin.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/AccountAdmin.java @@ -13,6 +13,7 @@ package app.fedilab.android.client.Entities; * * You should have received a copy of the GNU General Public License along with Fedilab; if not, * see . */ + import android.os.Parcel; import android.os.Parcelable; diff --git a/app/src/main/java/app/fedilab/android/client/Entities/AccountCreation.java b/app/src/main/java/app/fedilab/android/client/Entities/AccountCreation.java index 2d38eba37..82ea26b71 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/AccountCreation.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/AccountCreation.java @@ -1,4 +1,5 @@ package app.fedilab.android.client.Entities; + /* Copyright 2019 Thomas Schneider * * This file is a part of Fedilab diff --git a/app/src/main/java/app/fedilab/android/client/Entities/AdminAction.java b/app/src/main/java/app/fedilab/android/client/Entities/AdminAction.java index 05703feb7..727e74e5a 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/AdminAction.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/AdminAction.java @@ -19,7 +19,6 @@ import app.fedilab.android.client.API; public class AdminAction { - private API.adminAction type; private boolean send_email_notification; private String text; @@ -84,7 +83,6 @@ public class AdminAction { } - public boolean isUnresolved() { return unresolved; } diff --git a/app/src/main/java/app/fedilab/android/client/Entities/Application.java b/app/src/main/java/app/fedilab/android/client/Entities/Application.java index f88a74088..7cd177d4d 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/Application.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/Application.java @@ -28,7 +28,8 @@ public class Application implements Parcelable { private String name; private String website; - public Application(){} + public Application() { + } protected Application(Parcel in) { name = in.readString(); diff --git a/app/src/main/java/app/fedilab/android/client/Entities/Attachment.java b/app/src/main/java/app/fedilab/android/client/Entities/Attachment.java index 9e012f7f3..dd185f799 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/Attachment.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/Attachment.java @@ -22,7 +22,7 @@ import android.os.Parcelable; * Manages Media */ -public class Attachment implements Parcelable{ +public class Attachment implements Parcelable { private String id; private String type; diff --git a/app/src/main/java/app/fedilab/android/client/Entities/Card.java b/app/src/main/java/app/fedilab/android/client/Entities/Card.java index d96f3667f..f8c6ac585 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/Card.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/Card.java @@ -41,7 +41,8 @@ public class Card implements Parcelable { private int height; private int width; - public Card(){} + public Card() { + } public static final Creator CREATOR = new Creator() { @Override @@ -89,7 +90,6 @@ public class Card implements Parcelable { } - public String getUrl() { return url; } diff --git a/app/src/main/java/app/fedilab/android/client/Entities/Emojis.java b/app/src/main/java/app/fedilab/android/client/Entities/Emojis.java index 0e6320307..fe2c75528 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/Emojis.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/Emojis.java @@ -32,7 +32,8 @@ public class Emojis implements Parcelable { private Drawable drawable; private boolean drawableFound; - public Emojis(){} + public Emojis() { + } public String getShortcode() { return shortcode; diff --git a/app/src/main/java/app/fedilab/android/client/Entities/Error.java b/app/src/main/java/app/fedilab/android/client/Entities/Error.java index ccf3b97b8..6d50838b7 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/Error.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/Error.java @@ -23,6 +23,7 @@ public class Error { private String error = null; private int statusCode = -1; + public String getError() { return error; } diff --git a/app/src/main/java/app/fedilab/android/client/Entities/InstanceNodeInfo.java b/app/src/main/java/app/fedilab/android/client/Entities/InstanceNodeInfo.java index cba5e3d9f..a04928286 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/InstanceNodeInfo.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/InstanceNodeInfo.java @@ -45,7 +45,9 @@ public class InstanceNodeInfo { this.openRegistrations = openRegistrations; } - public boolean isConnectionError() { return connectionError; } + public boolean isConnectionError() { + return connectionError; + } public void setConnectionError(boolean connectionError) { this.connectionError = connectionError; diff --git a/app/src/main/java/app/fedilab/android/client/Entities/InstanceSocial.java b/app/src/main/java/app/fedilab/android/client/Entities/InstanceSocial.java index a22ac7c8c..50fba54c5 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/InstanceSocial.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/InstanceSocial.java @@ -45,7 +45,6 @@ public class InstanceSocial { private String thumbnail; - public String getVersion() { return version; } diff --git a/app/src/main/java/app/fedilab/android/client/Entities/ManageTimelines.java b/app/src/main/java/app/fedilab/android/client/Entities/ManageTimelines.java index 72b9f7770..25d80d1bc 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/ManageTimelines.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/ManageTimelines.java @@ -23,11 +23,14 @@ import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.graphics.PorterDuff; import android.os.Bundle; + import com.google.android.material.tabs.TabLayout; + import androidx.fragment.app.FragmentTransaction; import androidx.core.content.ContextCompat; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.PopupMenu; + import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; @@ -150,7 +153,7 @@ public class ManageTimelines { this.listTimeline = listTimeline; } - public enum Type{ + public enum Type { HOME, DIRECT, NOTIFICATION, @@ -164,8 +167,8 @@ public class ManageTimelines { } - public static Type typeFromDb(String value){ - switch (value){ + public static Type typeFromDb(String value) { + switch (value) { case "HOME": return Type.HOME; case "DIRECT": @@ -190,8 +193,8 @@ public class ManageTimelines { return null; } - public static String typeToDb(Type type){ - switch (type){ + public static String typeToDb(Type type) { + switch (type) { case HOME: return "HOME"; case DIRECT: @@ -217,11 +220,11 @@ public class ManageTimelines { } - public static RetrieveFeedsAsyncTask.Type transform(Context context, Type type){ + public static RetrieveFeedsAsyncTask.Type transform(Context context, Type type) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); - if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA ){ - switch (type){ + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { + switch (type) { case HOME: return RetrieveFeedsAsyncTask.Type.HOME; case DIRECT: @@ -257,7 +260,7 @@ public class ManageTimelines { return RetrieveFeedsAsyncTask.Type.LIST; } return null; - }else if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA){ + } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { switch (type) { case HOME: return RetrieveFeedsAsyncTask.Type.GNU_HOME; @@ -269,7 +272,7 @@ public class ManageTimelines { return RetrieveFeedsAsyncTask.Type.GNU_LOCAL; } return null; - }else if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU){ + } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU) { switch (type) { case HOME: return RetrieveFeedsAsyncTask.Type.GNU_HOME; @@ -290,24 +293,24 @@ public class ManageTimelines { } - public TabLayout createTabs(Context context, TabLayout tabLayout, java.util.List manageTimelines){ + public TabLayout createTabs(Context context, TabLayout tabLayout, java.util.List manageTimelines) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); tabLayout.removeAllTabs(); int position = 0; - for(ManageTimelines tl: manageTimelines){ + for (ManageTimelines tl : manageTimelines) { TabLayout.Tab tb = tabLayout.newTab(); ImageView icon = null; - if( tl.getType() != Type.TAG && tl.getType() != Type.INSTANCE && tl.getType() != Type.LIST) { + if (tl.getType() != Type.TAG && tl.getType() != Type.INSTANCE && tl.getType() != Type.LIST) { tb.setCustomView(R.layout.tab_badge); - if( tb.getCustomView() != null) + if (tb.getCustomView() != null) icon = tb.getCustomView().findViewById(R.id.tab_icon); } - if( icon != null){ - if( tl.getPosition() == 0) + if (icon != null) { + if (tl.getPosition() == 0) icon.setColorFilter(ContextCompat.getColor(context, R.color.mastodonC4), PorterDuff.Mode.SRC_IN); - switch (tl.getType()){ + switch (tl.getType()) { case HOME: icon.setImageResource(R.drawable.ic_home); icon.setContentDescription(context.getString(R.string.home_menu)); @@ -343,36 +346,36 @@ public class ManageTimelines { icon.setColorFilter(ContextCompat.getColor(context, R.color.dark_text), PorterDuff.Mode.SRC_IN); } tabLayout.addTab(tb); - }else{ + } else { String name = ""; - if( tl.getType() == Type.TAG){ - if( tl.getTagTimeline().getDisplayname() != null) { + if (tl.getType() == Type.TAG) { + if (tl.getTagTimeline().getDisplayname() != null) { name = tl.getTagTimeline().getDisplayname(); - }else { + } else { name = tl.getTagTimeline().getName(); } - }else if( tl.getType() == Type.INSTANCE ){ + } else if (tl.getType() == Type.INSTANCE) { name = tl.getRemoteInstance().getHost(); - }else if( tl.getType() == Type.LIST){ + } else if (tl.getType() == Type.LIST) { name = tl.getListTimeline().getTitle(); } - TextView tv=(TextView)LayoutInflater.from(context).inflate(R.layout.custom_tab_instance,null); + TextView tv = (TextView) LayoutInflater.from(context).inflate(R.layout.custom_tab_instance, null); tv.setText(name); if (theme == THEME_LIGHT) { tv.setTextColor(ContextCompat.getColor(context, R.color.action_light_header)); } tb.setCustomView(tv); - if( tl.getPosition() == 0){ + if (tl.getPosition() == 0) { tv.setTextColor(ContextCompat.getColor(context, R.color.mastodonC4)); } tabLayout.addTab(tb); } final LinearLayout tabStrip = (LinearLayout) tabLayout.getChildAt(0); - if( tl.getType() == Type.NOTIFICATION){ + if (tl.getType() == Type.NOTIFICATION) { notificationClik(context, tl, tabLayout); - }else if( tl.getType() == Type.PUBLIC || tl.getType() == Type.LOCAL || tl.getType() == Type.ART || tl.getType() == Type.HOME) { - if( tabStrip != null && tabStrip.getChildCount() > position) { + } else if (tl.getType() == Type.PUBLIC || tl.getType() == Type.LOCAL || tl.getType() == Type.ART || tl.getType() == Type.HOME) { + if (tabStrip != null && tabStrip.getChildCount() > position) { int finalPosition1 = position; tabStrip.getChildAt(position).setOnLongClickListener(new View.OnLongClickListener() { @Override @@ -382,8 +385,8 @@ public class ManageTimelines { } }); } - }else if( tl.getType() == Type.TAG) { - if( tabStrip != null && tabStrip.getChildCount() > position) { + } else if (tl.getType() == Type.TAG) { + if (tabStrip != null && tabStrip.getChildCount() > position) { int finalPosition = position; tabStrip.getChildAt(position).setOnLongClickListener(new View.OnLongClickListener() { @Override @@ -393,8 +396,8 @@ public class ManageTimelines { } }); } - }else if( tl.getType() == Type.INSTANCE && (tl.getRemoteInstance().getType().equals("MASTODON") || tl.getRemoteInstance().getType().equals("PEERTUBE") || tl.getRemoteInstance().getType().equals("PLEROMA")|| tl.getRemoteInstance().getType().equals("GNU"))) { - if( tabStrip != null && tabStrip.getChildCount() > position) { + } else if (tl.getType() == Type.INSTANCE && (tl.getRemoteInstance().getType().equals("MASTODON") || tl.getRemoteInstance().getType().equals("PEERTUBE") || tl.getRemoteInstance().getType().equals("PLEROMA") || tl.getRemoteInstance().getType().equals("GNU"))) { + if (tabStrip != null && tabStrip.getChildCount() > position) { int finalPosition = position; tabStrip.getChildAt(position).setOnLongClickListener(new View.OnLongClickListener() { @Override @@ -404,8 +407,8 @@ public class ManageTimelines { } }); } - }else if (tl.getType() == Type.LIST){ - if( tabStrip != null && tabStrip.getChildCount() > position) { + } else if (tl.getType() == Type.LIST) { + if (tabStrip != null && tabStrip.getChildCount() > position) { tabStrip.getChildAt(position).setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { @@ -426,13 +429,11 @@ public class ManageTimelines { } - - - private void notificationClik(Context context, ManageTimelines tl, TabLayout tabLayout){ + private void notificationClik(Context context, ManageTimelines tl, TabLayout tabLayout) { final LinearLayout tabStrip = (LinearLayout) tabLayout.getChildAt(0); - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA ) - if( tabStrip != null && tabStrip.getChildCount() > tl.getPosition()){ - tabStrip.getChildAt( tl.getPosition()).setOnLongClickListener(new View.OnLongClickListener() { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) + if (tabStrip != null && tabStrip.getChildCount() > tl.getPosition()) { + tabStrip.getChildAt(tl.getPosition()).setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { //Only shown if the tab has focus @@ -463,7 +464,7 @@ public class ManageTimelines { popup.setOnDismissListener(new PopupMenu.OnDismissListener() { @Override public void onDismiss(PopupMenu menu) { - if( mPageReferenceMap != null) { + if (mPageReferenceMap != null) { TabLayoutNotificationsFragment tabLayoutNotificationsFragment = (TabLayoutNotificationsFragment) mPageReferenceMap.get(tl.getPosition()); assert tabLayoutNotificationsFragment != null; tabLayoutNotificationsFragment.refreshAll(); @@ -534,13 +535,11 @@ public class ManageTimelines { } - - - private void manageFilters(Context context, ManageTimelines tl, LinearLayout tabStrip, int position){ + private void manageFilters(Context context, ManageTimelines tl, LinearLayout tabStrip, int position) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); //Only shown if the tab has focus PopupMenu popup = new PopupMenu(context, tabStrip.getChildAt(position)); - if( tl.getType() == Type.ART){ + if (tl.getType() == Type.ART) { popup.getMenuInflater() .inflate(R.menu.option_tag_timeline, popup.getMenu()); Menu menu = popup.getMenu(); @@ -559,14 +558,14 @@ public class ManageTimelines { itemNone.setVisible(false); action_displayname.setVisible(false); itemMedia.setVisible(false); - // itemDelete.setVisible(false); + // itemDelete.setVisible(false); itemShowNSFW.setChecked(show_nsfw[0]); final boolean[] changes = {false}; popup.setOnDismissListener(new PopupMenu.OnDismissListener() { @Override public void onDismiss(PopupMenu menu) { - if(changes[0]) { - if( mPageReferenceMap != null) { + if (changes[0]) { + if (mPageReferenceMap != null) { FragmentTransaction fragTransaction = ((MainActivity) context).getSupportFragmentManager().beginTransaction(); DisplayStatusFragment displayStatusFragment = (DisplayStatusFragment) mPageReferenceMap.get(tl.getPosition()); assert displayStatusFragment != null; @@ -605,22 +604,22 @@ public class ManageTimelines { } }); popup.show(); - }else{ + } else { popup.getMenuInflater() .inflate(R.menu.option_filter_toots, popup.getMenu()); Menu menu = popup.getMenu(); final MenuItem itemShowBoosts = menu.findItem(R.id.action_show_boosts); final MenuItem itemShowReplies = menu.findItem(R.id.action_show_replies); final MenuItem itemFilter = menu.findItem(R.id.action_filter); - if( mPageReferenceMap == null) { + if (mPageReferenceMap == null) { return; } DisplayStatusFragment displayStatusFragment = (DisplayStatusFragment) mPageReferenceMap.get(tl.getPosition()); - if(tl.getType() != Type.HOME){ + if (tl.getType() != Type.HOME) { itemShowBoosts.setVisible(false); itemShowReplies.setVisible(false); itemFilter.setVisible(true); - }else { + } else { itemShowBoosts.setVisible(true); itemShowReplies.setVisible(true); itemFilter.setVisible(true); @@ -629,23 +628,23 @@ public class ManageTimelines { final boolean[] show_replies = {sharedpreferences.getBoolean(Helper.SET_SHOW_REPLIES, true)}; String show_filtered = null; - if(displayStatusFragment != null && displayStatusFragment.getUserVisibleHint() && tl.getType() == Type.HOME) + if (displayStatusFragment != null && displayStatusFragment.getUserVisibleHint() && tl.getType() == Type.HOME) show_filtered = sharedpreferences.getString(Helper.SET_FILTER_REGEX_HOME, null); - if(displayStatusFragment != null && displayStatusFragment.getUserVisibleHint() && tl.getType() == Type.LOCAL) + if (displayStatusFragment != null && displayStatusFragment.getUserVisibleHint() && tl.getType() == Type.LOCAL) show_filtered = sharedpreferences.getString(Helper.SET_FILTER_REGEX_LOCAL, null); - if(displayStatusFragment != null && displayStatusFragment.getUserVisibleHint() && tl.getType() == Type.PUBLIC) + if (displayStatusFragment != null && displayStatusFragment.getUserVisibleHint() && tl.getType() == Type.PUBLIC) show_filtered = sharedpreferences.getString(Helper.SET_FILTER_REGEX_PUBLIC, null); itemShowBoosts.setChecked(show_boosts[0]); itemShowReplies.setChecked(show_replies[0]); - if( show_filtered != null && show_filtered.length() > 0){ + if (show_filtered != null && show_filtered.length() > 0) { itemFilter.setTitle(show_filtered); } popup.setOnDismissListener(new PopupMenu.OnDismissListener() { @Override public void onDismiss(PopupMenu menu) { - if(displayStatusFragment != null && displayStatusFragment.getUserVisibleHint()) + if (displayStatusFragment != null && displayStatusFragment.getUserVisibleHint()) displayStatusFragment.refreshFilter(); } }); @@ -653,9 +652,9 @@ public class ManageTimelines { int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } String finalShow_filtered = show_filtered; @@ -692,8 +691,8 @@ public class ManageTimelines { break; case R.id.action_filter: AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, style); - LayoutInflater inflater = ((MainActivity)context).getLayoutInflater(); - View dialogView = inflater.inflate(R.layout.filter_regex, new LinearLayout(context), false); + LayoutInflater inflater = ((MainActivity) context).getLayoutInflater(); + View dialogView = inflater.inflate(R.layout.filter_regex, new LinearLayout(context), false); dialogBuilder.setView(dialogView); final EditText editText = dialogView.findViewById(R.id.filter_regex); Toast alertRegex = Toasty.warning(context, context.getString(R.string.alert_regex), Toast.LENGTH_LONG); @@ -701,22 +700,24 @@ public class ManageTimelines { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } + @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } + @Override public void afterTextChanged(Editable s) { try { Pattern.compile("(" + s.toString() + ")", Pattern.CASE_INSENSITIVE); - }catch (Exception e){ - if( !alertRegex.getView().isShown()){ + } catch (Exception e) { + if (!alertRegex.getView().isShown()) { alertRegex.show(); } } } }); - if( finalShow_filtered != null) { + if (finalShow_filtered != null) { editText.setText(finalShow_filtered); editText.setSelection(editText.getText().toString().length()); } @@ -724,15 +725,15 @@ public class ManageTimelines { @Override public void onClick(DialogInterface dialog, int id) { itemFilter.setTitle(editText.getText().toString().trim()); - if(displayStatusFragment != null && displayStatusFragment.getUserVisibleHint() && tl.getType() == Type.HOME) { + if (displayStatusFragment != null && displayStatusFragment.getUserVisibleHint() && tl.getType() == Type.HOME) { editor.putString(Helper.SET_FILTER_REGEX_HOME, editText.getText().toString().trim()); MainActivity.regex_home = editText.getText().toString().trim(); } - if(displayStatusFragment != null && displayStatusFragment.getUserVisibleHint() && tl.getType() == Type.LOCAL) { + if (displayStatusFragment != null && displayStatusFragment.getUserVisibleHint() && tl.getType() == Type.LOCAL) { editor.putString(Helper.SET_FILTER_REGEX_LOCAL, editText.getText().toString().trim()); MainActivity.regex_local = editText.getText().toString().trim(); } - if(displayStatusFragment != null && displayStatusFragment.getUserVisibleHint() && tl.getType() == Type.PUBLIC) { + if (displayStatusFragment != null && displayStatusFragment.getUserVisibleHint() && tl.getType() == Type.PUBLIC) { editor.putString(Helper.SET_FILTER_REGEX_PUBLIC, editText.getText().toString().trim()); MainActivity.regex_public = editText.getText().toString().trim(); } @@ -751,27 +752,27 @@ public class ManageTimelines { } - private void tagClick(Context context, ManageTimelines tl, LinearLayout tabStrip, int position){ + private void tagClick(Context context, ManageTimelines tl, LinearLayout tabStrip, int position) { PopupMenu popup = new PopupMenu(context, tabStrip.getChildAt(position)); - TabLayout tabLayout = ((MainActivity)context).findViewById(R.id.tabLayout); + TabLayout tabLayout = ((MainActivity) context).findViewById(R.id.tabLayout); SQLiteDatabase db = Sqlite.getInstance(context, DB_NAME, null, Sqlite.DB_VERSION).open(); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } String tag; tagTimeline = tl.getTagTimeline(); - if( tagTimeline == null) + if (tagTimeline == null) return; - if( tagTimeline.getDisplayname() != null) + if (tagTimeline.getDisplayname() != null) tag = tagTimeline.getDisplayname(); else tag = tagTimeline.getName(); @@ -794,22 +795,22 @@ public class ManageTimelines { popup.setOnDismissListener(new PopupMenu.OnDismissListener() { @Override public void onDismiss(PopupMenu menu) { - if(changes[0]) { - if( mPageReferenceMap == null) + if (changes[0]) { + if (mPageReferenceMap == null) return; - FragmentTransaction fragTransaction = ((MainActivity)context).getSupportFragmentManager().beginTransaction(); + FragmentTransaction fragTransaction = ((MainActivity) context).getSupportFragmentManager().beginTransaction(); DisplayStatusFragment displayStatusFragment = (DisplayStatusFragment) mPageReferenceMap.get(tl.getPosition()); - if( displayStatusFragment == null) + if (displayStatusFragment == null) return; fragTransaction.detach(displayStatusFragment); Bundle bundle = new Bundle(); bundle.putString("tag", tl.getTagTimeline().getName()); bundle.putInt("timelineId", tl.getId()); - bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.TAG); - if( mediaOnly[0]) - bundle.putString("instanceType","ART"); + bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.TAG); + if (mediaOnly[0]) + bundle.putString("instanceType", "ART"); else - bundle.putString("instanceType","MASTODON"); + bundle.putString("instanceType", "MASTODON"); displayStatusFragment.setArguments(bundle); fragTransaction.attach(displayStatusFragment); fragTransaction.commit(); @@ -836,7 +837,7 @@ public class ManageTimelines { changes[0] = true; switch (item.getItemId()) { case R.id.action_show_media_only: - mediaOnly[0] =!mediaOnly[0]; + mediaOnly[0] = !mediaOnly[0]; tagTimeline.setART(mediaOnly[0]); new SearchDAO(context, db).updateSearch(tagTimeline); tl.setTagTimeline(tagTimeline); @@ -853,14 +854,14 @@ public class ManageTimelines { break; case R.id.action_any: AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, style); - LayoutInflater inflater = ((MainActivity)context).getLayoutInflater(); - View dialogView = inflater.inflate(R.layout.tags_any, new LinearLayout(context), false); + LayoutInflater inflater = ((MainActivity) context).getLayoutInflater(); + View dialogView = inflater.inflate(R.layout.tags_any, new LinearLayout(context), false); dialogBuilder.setView(dialogView); final EditText editText = dialogView.findViewById(R.id.filter_any); - if(tagTimeline.getAny() != null) { + if (tagTimeline.getAny() != null) { String valuesTag = ""; - for(String val: tagTimeline.getAny()) - valuesTag += val+" "; + for (String val : tagTimeline.getAny()) + valuesTag += val + " "; editText.setText(valuesTag); editText.setSelection(editText.getText().toString().length()); } @@ -881,14 +882,14 @@ public class ManageTimelines { break; case R.id.action_all: dialogBuilder = new AlertDialog.Builder(context, style); - inflater = ((MainActivity)context).getLayoutInflater(); + inflater = ((MainActivity) context).getLayoutInflater(); dialogView = inflater.inflate(R.layout.tags_all, null); dialogBuilder.setView(dialogView); final EditText editTextAll = dialogView.findViewById(R.id.filter_all); - if( tagTimeline.getAll() != null) { + if (tagTimeline.getAll() != null) { String valuesTag = ""; - for(String val: tagTimeline.getAll()) - valuesTag += val+" "; + for (String val : tagTimeline.getAll()) + valuesTag += val + " "; editTextAll.setText(valuesTag); editTextAll.setSelection(editTextAll.getText().toString().length()); } @@ -909,14 +910,14 @@ public class ManageTimelines { break; case R.id.action_none: dialogBuilder = new AlertDialog.Builder(context, style); - inflater = ((MainActivity)context). getLayoutInflater(); + inflater = ((MainActivity) context).getLayoutInflater(); dialogView = inflater.inflate(R.layout.tags_all, null); dialogBuilder.setView(dialogView); final EditText editTextNone = dialogView.findViewById(R.id.filter_all); - if( tagTimeline.getNone() != null) { + if (tagTimeline.getNone() != null) { String valuesTag = ""; - for(String val: tagTimeline.getNone()) - valuesTag += val+" "; + for (String val : tagTimeline.getNone()) + valuesTag += val + " "; editTextNone.setText(valuesTag); editTextNone.setSelection(editTextNone.getText().toString().length()); } @@ -937,11 +938,11 @@ public class ManageTimelines { break; case R.id.action_displayname: dialogBuilder = new AlertDialog.Builder(context, style); - inflater = ((MainActivity)context).getLayoutInflater(); + inflater = ((MainActivity) context).getLayoutInflater(); dialogView = inflater.inflate(R.layout.tags_name, null); dialogBuilder.setView(dialogView); final EditText editTextName = dialogView.findViewById(R.id.column_name); - if( tagTimeline.getDisplayname() != null) { + if (tagTimeline.getDisplayname() != null) { editTextName.setText(tagTimeline.getDisplayname()); editTextName.setSelection(editTextName.getText().toString().length()); } @@ -949,9 +950,9 @@ public class ManageTimelines { @Override public void onClick(DialogInterface dialog, int id) { String values = editTextName.getText().toString(); - if( values.trim().length() == 0) + if (values.trim().length() == 0) values = tag; - if( tabLayout.getTabAt(position) != null) + if (tabLayout.getTabAt(position) != null) tabLayout.getTabAt(position).setText(values); tagTimeline.setDisplayname(values); new SearchDAO(context, db).updateSearch(tagTimeline); @@ -971,8 +972,7 @@ public class ManageTimelines { } - - private void instanceClick(Context context, ManageTimelines tl, LinearLayout tabStrip, int position){ + private void instanceClick(Context context, ManageTimelines tl, LinearLayout tabStrip, int position) { PopupMenu popup = new PopupMenu(context, tabStrip.getChildAt(position)); @@ -982,22 +982,22 @@ public class ManageTimelines { int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } remoteInstance = tl.getRemoteInstance(); - if( remoteInstance == null) + if (remoteInstance == null) return; currentFilter = remoteInstance.getFilteredWith(); final boolean[] changes = {false}; String title; - if( currentFilter == null) { + if (currentFilter == null) { title = "✔ " + context.getString(R.string.all); - }else{ + } else { title = context.getString(R.string.all); } @@ -1020,11 +1020,11 @@ public class ManageTimelines { } }); changes[0] = true; - FragmentTransaction fragTransaction = ((MainActivity)context).getSupportFragmentManager().beginTransaction(); - if( mPageReferenceMap == null) + FragmentTransaction fragTransaction = ((MainActivity) context).getSupportFragmentManager().beginTransaction(); + if (mPageReferenceMap == null) return true; DisplayStatusFragment displayStatusFragment = (DisplayStatusFragment) mPageReferenceMap.get(tl.getPosition()); - if( displayStatusFragment == null) + if (displayStatusFragment == null) return false; tl.getRemoteInstance().setFilteredWith(null); remoteInstance.setFilteredWith(null); @@ -1034,10 +1034,10 @@ public class ManageTimelines { new TimelinesDAO(context, db).updateRemoteInstance(tl); fragTransaction.detach(displayStatusFragment); Bundle bundle = new Bundle(); - bundle.putString("remote_instance", tl.getRemoteInstance().getHost()!=null?tl.getRemoteInstance().getHost():""); + bundle.putString("remote_instance", tl.getRemoteInstance().getHost() != null ? tl.getRemoteInstance().getHost() : ""); bundle.putString("instanceType", tl.getRemoteInstance().getType()); bundle.putInt("timelineId", tl.getId()); - bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE); + bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE); displayStatusFragment.setArguments(bundle); fragTransaction.attach(displayStatusFragment); fragTransaction.commit(); @@ -1048,25 +1048,25 @@ public class ManageTimelines { java.util.List tags = remoteInstance.getTags(); - if( tags != null && tags.size() > 0){ + if (tags != null && tags.size() > 0) { java.util.Collections.sort(tags); - for(String tag: tags){ - if( tag == null || tag.length() == 0 ) + for (String tag : tags) { + if (tag == null || tag.length() == 0) continue; - if( currentFilter != null && currentFilter.equals(tag)) { + if (currentFilter != null && currentFilter.equals(tag)) { title = "✔ " + tag; - }else{ + } else { title = tag; } MenuItem item = popup.getMenu().add(0, 0, Menu.NONE, title); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { - FragmentTransaction fragTransaction = ((MainActivity)context).getSupportFragmentManager().beginTransaction(); - if( mPageReferenceMap == null) + FragmentTransaction fragTransaction = ((MainActivity) context).getSupportFragmentManager().beginTransaction(); + if (mPageReferenceMap == null) return true; DisplayStatusFragment displayStatusFragment = (DisplayStatusFragment) mPageReferenceMap.get(tl.getPosition()); - if( displayStatusFragment == null) + if (displayStatusFragment == null) return false; tl.getRemoteInstance().setFilteredWith(tag); remoteInstance.setFilteredWith(tag); @@ -1076,11 +1076,11 @@ public class ManageTimelines { currentFilter = tl.getRemoteInstance().getFilteredWith(); fragTransaction.detach(displayStatusFragment); Bundle bundle = new Bundle(); - bundle.putString("remote_instance", tl.getRemoteInstance().getHost()!=null?tl.getRemoteInstance().getHost():""); + bundle.putString("remote_instance", tl.getRemoteInstance().getHost() != null ? tl.getRemoteInstance().getHost() : ""); bundle.putString("instanceType", tl.getRemoteInstance().getType()); bundle.putInt("timelineId", tl.getId()); bundle.putString("currentfilter", tl.getRemoteInstance().getFilteredWith()); - bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE_FILTERED); + bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE_FILTERED); displayStatusFragment.setArguments(bundle); fragTransaction.attach(displayStatusFragment); fragTransaction.commit(); @@ -1110,14 +1110,14 @@ public class ManageTimelines { }); changes[0] = true; AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, style); - LayoutInflater inflater = ((MainActivity)context).getLayoutInflater(); - View dialogView = inflater.inflate(R.layout.tags_instance, new LinearLayout(context), false); + LayoutInflater inflater = ((MainActivity) context).getLayoutInflater(); + View dialogView = inflater.inflate(R.layout.tags_instance, new LinearLayout(context), false); dialogBuilder.setView(dialogView); final EditText editText = dialogView.findViewById(R.id.filter_words); - if(remoteInstance.getTags() != null) { + if (remoteInstance.getTags() != null) { String valuesTag = ""; - for(String val: remoteInstance.getTags()) - valuesTag += val+" "; + for (String val : remoteInstance.getTags()) + valuesTag += val + " "; editText.setText(valuesTag); editText.setSelection(editText.getText().toString().length()); } @@ -1145,23 +1145,23 @@ public class ManageTimelines { popup.setOnDismissListener(new PopupMenu.OnDismissListener() { @Override public void onDismiss(PopupMenu menu) { - if(changes[0]) { - FragmentTransaction fragTransaction = ((MainActivity)context).getSupportFragmentManager().beginTransaction(); - if( mPageReferenceMap == null) + if (changes[0]) { + FragmentTransaction fragTransaction = ((MainActivity) context).getSupportFragmentManager().beginTransaction(); + if (mPageReferenceMap == null) return; DisplayStatusFragment displayStatusFragment = (DisplayStatusFragment) mPageReferenceMap.get(tl.getPosition()); - if( displayStatusFragment == null) + if (displayStatusFragment == null) return; fragTransaction.detach(displayStatusFragment); Bundle bundle = new Bundle(); - bundle.putString("remote_instance", tl.getRemoteInstance().getHost()!=null?tl.getRemoteInstance().getHost():""); + bundle.putString("remote_instance", tl.getRemoteInstance().getHost() != null ? tl.getRemoteInstance().getHost() : ""); bundle.putString("instanceType", tl.getRemoteInstance().getType()); bundle.putInt("timelineId", tl.getId()); - if( currentFilter == null){ - bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE); - }else{ + if (currentFilter == null) { + bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE); + } else { bundle.putString("currentfilter", tl.getRemoteInstance().getFilteredWith()); - bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE_FILTERED); + bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE_FILTERED); } displayStatusFragment.setArguments(bundle); fragTransaction.attach(displayStatusFragment); diff --git a/app/src/main/java/app/fedilab/android/client/Entities/Mention.java b/app/src/main/java/app/fedilab/android/client/Entities/Mention.java index 84450eacc..04b67fa6a 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/Mention.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/Mention.java @@ -36,7 +36,8 @@ public class Mention implements Parcelable { id = in.readString(); } - public Mention(){} + public Mention() { + } public static final Creator CREATOR = new Creator() { @Override diff --git a/app/src/main/java/app/fedilab/android/client/Entities/Notification.java b/app/src/main/java/app/fedilab/android/client/Entities/Notification.java index 4ba996cea..95a03df63 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/Notification.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/Notification.java @@ -23,8 +23,10 @@ import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Parcel; import android.os.Parcelable; + import androidx.annotation.NonNull; import androidx.annotation.Nullable; + import android.text.Spannable; import android.text.SpannableString; import android.text.style.ImageSpan; @@ -73,7 +75,10 @@ public class Notification implements Parcelable { status = in.readParcelable(Status.class.getClassLoader()); } - public Notification(){}; + public Notification() { + } + + ; public static final Creator CREATOR = new Creator() { @Override @@ -146,101 +151,103 @@ public class Notification implements Parcelable { } - public static void makeEmojis(final Context context, final OnRetrieveEmojiInterface listener, Notification notification){ + public static void makeEmojis(final Context context, final OnRetrieveEmojiInterface listener, Notification notification) { - if( ((Activity)context).isFinishing() ) + if (((Activity) context).isFinishing()) return; Status status = notification.getStatus(); java.util.List emojis = null; - if (status != null){ + if (status != null) { emojis = status.getEmojis(); } List emojisAccounts = notification.getAccount().getEmojis(); String typeString = ""; - switch (notification.getType()){ + switch (notification.getType()) { case "mention": - if( notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) - typeString = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true),context.getString(R.string.notif_mention)); + if (notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) + typeString = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true), context.getString(R.string.notif_mention)); else - typeString = String.format("@%s %s", notification.getAccount().getUsername(),context.getString(R.string.notif_mention)); + typeString = String.format("@%s %s", notification.getAccount().getUsername(), context.getString(R.string.notif_mention)); break; case "poll": - typeString = context.getString(R.string.notif_poll);; + typeString = context.getString(R.string.notif_poll); + ; break; case "reblog": - if( notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) - typeString = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true),context.getString(R.string.notif_reblog)); + if (notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) + typeString = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true), context.getString(R.string.notif_reblog)); else - typeString = String.format("@%s %s", notification.getAccount().getUsername(),context.getString(R.string.notif_reblog)); + typeString = String.format("@%s %s", notification.getAccount().getUsername(), context.getString(R.string.notif_reblog)); break; case "favourite": - if( notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) - typeString = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true),context.getString(R.string.notif_favourite)); + if (notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) + typeString = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true), context.getString(R.string.notif_favourite)); else - typeString = String.format("@%s %s", notification.getAccount().getUsername(),context.getString(R.string.notif_favourite)); + typeString = String.format("@%s %s", notification.getAccount().getUsername(), context.getString(R.string.notif_favourite)); break; case "follow": - if( notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) - typeString = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true),context.getString(R.string.notif_follow)); + if (notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) + typeString = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true), context.getString(R.string.notif_follow)); else - typeString = String.format("@%s %s", notification.getAccount().getUsername(),context.getString(R.string.notif_follow)); + typeString = String.format("@%s %s", notification.getAccount().getUsername(), context.getString(R.string.notif_follow)); break; } SpannableString displayNameSpan = new SpannableString(typeString); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); boolean disableAnimatedEmoji = sharedpreferences.getBoolean(Helper.SET_DISABLE_ANIMATED_EMOJI, false); - if( emojisAccounts != null && emojisAccounts.size() > 0 ) { + if (emojisAccounts != null && emojisAccounts.size() > 0) { final int[] j = {0}; for (final Emojis emoji : emojisAccounts) { Glide.with(context) - .asDrawable() - .load(emoji.getUrl()) - .listener(new RequestListener() { - @Override - public boolean onResourceReady(Drawable resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) { - return false; - } - @Override - public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) { - j[0]++; - if( j[0] == (emojisAccounts.size())) { - listener.onRetrieveEmoji(notification); + .asDrawable() + .load(emoji.getUrl()) + .listener(new RequestListener() { + @Override + public boolean onResourceReady(Drawable resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) { + return false; } - return false; - } - }) - .into(new SimpleTarget() { - @Override - public void onResourceReady(@NonNull Drawable resource, @Nullable Transition transition) { - final String targetedEmoji = ":" + emoji.getShortcode() + ":"; - if (displayNameSpan.toString().contains(targetedEmoji)) { - //emojis can be used several times so we have to loop - for (int startPosition = -1; (startPosition = displayNameSpan.toString().indexOf(targetedEmoji, startPosition + 1)) != -1; startPosition++) { - final int endPosition = startPosition + targetedEmoji.length(); - if(endPosition <= displayNameSpan.toString().length() && endPosition >= startPosition) { - resource.setBounds(0,0,(int) Helper.convertDpToPixel(20, context),(int) Helper.convertDpToPixel(20, context)); - resource.setVisible(true, true); - ImageSpan imageSpan = new ImageSpan(resource); - displayNameSpan.setSpan( - imageSpan, startPosition, - endPosition, Spannable.SPAN_INCLUSIVE_EXCLUSIVE); + + @Override + public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) { + j[0]++; + if (j[0] == (emojisAccounts.size())) { + listener.onRetrieveEmoji(notification); + } + return false; + } + }) + .into(new SimpleTarget() { + @Override + public void onResourceReady(@NonNull Drawable resource, @Nullable Transition transition) { + final String targetedEmoji = ":" + emoji.getShortcode() + ":"; + if (displayNameSpan.toString().contains(targetedEmoji)) { + //emojis can be used several times so we have to loop + for (int startPosition = -1; (startPosition = displayNameSpan.toString().indexOf(targetedEmoji, startPosition + 1)) != -1; startPosition++) { + final int endPosition = startPosition + targetedEmoji.length(); + if (endPosition <= displayNameSpan.toString().length() && endPosition >= startPosition) { + resource.setBounds(0, 0, (int) Helper.convertDpToPixel(20, context), (int) Helper.convertDpToPixel(20, context)); + resource.setVisible(true, true); + ImageSpan imageSpan = new ImageSpan(resource); + displayNameSpan.setSpan( + imageSpan, startPosition, + endPosition, Spannable.SPAN_INCLUSIVE_EXCLUSIVE); + } } } + j[0]++; + if (j[0] == (emojisAccounts.size())) { + notification.getAccount().setdisplayNameSpan(displayNameSpan); + listener.onRetrieveEmoji(notification); + } } - j[0]++; - if( j[0] == (emojisAccounts.size())) { - notification.getAccount().setdisplayNameSpan(displayNameSpan); - listener.onRetrieveEmoji(notification); - } - } - }); + }); } } - if( status != null && emojis != null && emojis.size() > 0 ) { + if (status != null && emojis != null && emojis.size() > 0) { SpannableString contentSpan = status.getContentSpan(); SpannableString contentSpanCW = status.getContentSpanCW(); final int[] i = {0}; @@ -249,16 +256,17 @@ public class Notification implements Parcelable { Glide.with(context) .asFile() .load(emoji.getUrl()) - .listener(new RequestListener() { + .listener(new RequestListener() { @Override public boolean onResourceReady(File resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) { return false; } + @Override public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) { i[0]++; - if( i[0] == (finalEmojis.size())) { - listener.onRetrieveEmoji(status,false); + if (i[0] == (finalEmojis.size())) { + listener.onRetrieveEmoji(status, false); } return false; } @@ -274,7 +282,7 @@ public class Notification implements Parcelable { } else { resource = Drawable.createFromPath(resourceFile.getAbsolutePath()); } - if( resource == null){ + if (resource == null) { return; } final String targetedEmoji = ":" + emoji.getShortcode() + ":"; @@ -282,13 +290,13 @@ public class Notification implements Parcelable { //emojis can be used several times so we have to loop for (int startPosition = -1; (startPosition = contentSpan.toString().indexOf(targetedEmoji, startPosition + 1)) != -1; startPosition++) { final int endPosition = startPosition + targetedEmoji.length(); - if( endPosition <= contentSpan.toString().length() && endPosition >= startPosition) { + if (endPosition <= contentSpan.toString().length() && endPosition >= startPosition) { ImageSpan imageSpan; - if( !disableAnimatedEmoji) { + if (!disableAnimatedEmoji) { resource.setBounds(0, 0, (int) Helper.convertDpToPixel(20, context), (int) Helper.convertDpToPixel(20, context)); resource.setVisible(true, true); imageSpan = new ImageSpan(resource); - }else{ + } else { Bitmap bitmap = drawableToBitmap(resource); imageSpan = new ImageSpan(context, Bitmap.createScaledBitmap(bitmap, (int) Helper.convertDpToPixel(20, context), @@ -304,13 +312,13 @@ public class Notification implements Parcelable { //emojis can be used several times so we have to loop for (int startPosition = -1; (startPosition = contentSpanCW.toString().indexOf(targetedEmoji, startPosition + 1)) != -1; startPosition++) { final int endPosition = startPosition + targetedEmoji.length(); - if( endPosition <= contentSpanCW.toString().length() && endPosition >= startPosition) { + if (endPosition <= contentSpanCW.toString().length() && endPosition >= startPosition) { ImageSpan imageSpan; - if( !disableAnimatedEmoji) { + if (!disableAnimatedEmoji) { resource.setBounds(0, 0, (int) Helper.convertDpToPixel(20, context), (int) Helper.convertDpToPixel(20, context)); resource.setVisible(true, true); imageSpan = new ImageSpan(resource); - }else { + } else { resource.setVisible(true, true); Bitmap bitmap = drawableToBitmap(resource); imageSpan = new ImageSpan(context, @@ -324,7 +332,7 @@ public class Notification implements Parcelable { } } i[0]++; - if( i[0] == (finalEmojis.size())) { + if (i[0] == (finalEmojis.size())) { status.setContentSpan(contentSpan); status.setContentSpanCW(contentSpanCW); status.setEmojiFound(true); diff --git a/app/src/main/java/app/fedilab/android/client/Entities/Peertube.java b/app/src/main/java/app/fedilab/android/client/Entities/Peertube.java index d95dcd3d4..452777327 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/Peertube.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/Peertube.java @@ -47,8 +47,8 @@ public class Peertube { private boolean commentsEnabled; private boolean sensitive; private HashMap category; - private HashMap license; - private HashMap language; + private HashMap license; + private HashMap language; private HashMap privacy; private HashMap channelForUpdate; private String myRating = "none"; @@ -175,37 +175,38 @@ public class Peertube { } public String getFileUrl(String resolution) { - if( resolution == null) + if (resolution == null) resolution = this.getResolution().get(0); - if(resolution == null) + if (resolution == null) return null; - return "https://" + this.host + "/static/webseed/" + getUuid()+ "-" + resolution + ".mp4"; + return "https://" + this.host + "/static/webseed/" + getUuid() + "-" + resolution + ".mp4"; } public String getTorrentUrl(String resolution) { - if( resolution == null) + if (resolution == null) resolution = this.getResolution().get(0); - if(resolution == null) + if (resolution == null) return null; - return "https://" + this.host + "/static/torrents/" + getUuid()+ "-" + resolution + ".torrent"; + return "https://" + this.host + "/static/torrents/" + getUuid() + "-" + resolution + ".torrent"; } public String getTorrentDownloadUrl(String resolution) { - if( resolution == null) + if (resolution == null) resolution = this.getResolution().get(0); - if(resolution == null) + if (resolution == null) return null; - return "https://" + this.host + "/download/torrents/" + getUuid()+ "-" + resolution + ".torrent"; + return "https://" + this.host + "/download/torrents/" + getUuid() + "-" + resolution + ".torrent"; } + public String getFileDownloadUrl(String resolution) { - if( resolution == null) + if (resolution == null) resolution = this.getResolution().get(0); - if(resolution == null) + if (resolution == null) return null; - return "https://" + this.host + "/download/videos/" + getUuid()+ "-" + resolution + ".mp4"; + return "https://" + this.host + "/download/videos/" + getUuid() + "-" + resolution + ".mp4"; } public List getResolution() { @@ -249,8 +250,6 @@ public class Peertube { } - - public String getMyRating() { return myRating; } diff --git a/app/src/main/java/app/fedilab/android/client/Entities/PeertubeAccountNotification.java b/app/src/main/java/app/fedilab/android/client/Entities/PeertubeAccountNotification.java index 2bce5061e..b93e1a2ee 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/PeertubeAccountNotification.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/PeertubeAccountNotification.java @@ -15,7 +15,6 @@ package app.fedilab.android.client.Entities; - /** * Created by Thomas on 23/01/2019. */ diff --git a/app/src/main/java/app/fedilab/android/client/Entities/PeertubeInformation.java b/app/src/main/java/app/fedilab/android/client/Entities/PeertubeInformation.java index 504a971a1..fa4e3fd49 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/PeertubeInformation.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/PeertubeInformation.java @@ -30,6 +30,7 @@ public class PeertubeInformation { public static final LinkedHashMap langueMapped; + static { LinkedHashMap aMap = new LinkedHashMap<>(); aMap.put("ca", "ca-ES"); diff --git a/app/src/main/java/app/fedilab/android/client/Entities/PeertubeNotification.java b/app/src/main/java/app/fedilab/android/client/Entities/PeertubeNotification.java index 5902b58de..2a18cde90 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/PeertubeNotification.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/PeertubeNotification.java @@ -15,14 +15,13 @@ package app.fedilab.android.client.Entities; - import java.util.Date; /** * Created by Thomas on 23/01/2019. */ -public class PeertubeNotification { +public class PeertubeNotification { private String id; private boolean read; @@ -32,7 +31,10 @@ public class PeertubeNotification { private PeertubeVideoNotification peertubeVideoNotification; private PeertubeActorFollow peertubeActorFollow; - public PeertubeNotification(){}; + public PeertubeNotification() { + } + + ; public String getId() { return id; diff --git a/app/src/main/java/app/fedilab/android/client/Entities/PeertubeVideoNotification.java b/app/src/main/java/app/fedilab/android/client/Entities/PeertubeVideoNotification.java index 291b3ab52..7b5844b1c 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/PeertubeVideoNotification.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/PeertubeVideoNotification.java @@ -15,7 +15,6 @@ package app.fedilab.android.client.Entities; - /** * Created by Thomas on 23/01/2019. */ diff --git a/app/src/main/java/app/fedilab/android/client/Entities/PleromaAdmin.java b/app/src/main/java/app/fedilab/android/client/Entities/PleromaAdmin.java index a4f53f788..e4f124782 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/PleromaAdmin.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/PleromaAdmin.java @@ -30,7 +30,8 @@ public class PleromaAdmin implements Parcelable { private String password; private String tags; - public PleromaAdmin(){} + public PleromaAdmin() { + } public String getNickname() { diff --git a/app/src/main/java/app/fedilab/android/client/Entities/RemoteInstance.java b/app/src/main/java/app/fedilab/android/client/Entities/RemoteInstance.java index 3283f5194..201197fd5 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/RemoteInstance.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/RemoteInstance.java @@ -34,7 +34,8 @@ public class RemoteInstance implements Parcelable { private List tags; private String filteredWith; - public RemoteInstance(){} + public RemoteInstance() { + } public String getHost() { diff --git a/app/src/main/java/app/fedilab/android/client/Entities/Schedule.java b/app/src/main/java/app/fedilab/android/client/Entities/Schedule.java index 8ba4dd2b0..56d1fd885 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/Schedule.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/Schedule.java @@ -33,7 +33,8 @@ public class Schedule implements Parcelable { private Status status; private List attachmentList; - public Schedule(){} + public Schedule() { + } public String getId() { diff --git a/app/src/main/java/app/fedilab/android/client/Entities/Status.java b/app/src/main/java/app/fedilab/android/client/Entities/Status.java index 3e0820aca..f93ae9508 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/Status.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/Status.java @@ -26,9 +26,11 @@ import android.os.Build; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; + import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; + import android.text.Html; import android.text.Spannable; import android.text.SpannableString; @@ -98,7 +100,7 @@ import static app.fedilab.android.helper.Helper.drawableToBitmap; * Manage Status (ie: toots) */ -public class Status implements Parcelable{ +public class Status implements Parcelable { private String id; private String uri; @@ -146,7 +148,9 @@ public class Status implements Parcelable{ private int numberLines = -1; private boolean showSpoiler = false; - public Status(){} + public Status() { + } + private List conversationProfilePicture; private String webviewURL = null; @@ -381,6 +385,7 @@ public class Status implements Parcelable{ public void setShortReply(boolean shortReply) { this.shortReply = shortReply; } + public Status getReblog() { return reblog; } @@ -413,10 +418,11 @@ public class Status implements Parcelable{ this.favourites_count = favourites_count; } - public SpannableString getDisplayNameSpan(){ + public SpannableString getDisplayNameSpan() { return this.displayNameSpan; } - public void setDisplayNameSpan(SpannableString displayNameSpan){ + + public void setDisplayNameSpan(SpannableString displayNameSpan) { this.displayNameSpan = displayNameSpan; } @@ -436,9 +442,13 @@ public class Status implements Parcelable{ this.favourited = favourited; } - public void setPinned(boolean pinned) { this.pinned = pinned; } + public void setPinned(boolean pinned) { + this.pinned = pinned; + } - public boolean isPinned() { return pinned; } + public boolean isPinned() { + return pinned; + } public boolean isSensitive() { return sensitive; @@ -594,8 +604,6 @@ public class Status implements Parcelable{ } - - public void setEmojiFound(boolean emojiFound) { isEmojiFound = emojiFound; } @@ -605,25 +613,25 @@ public class Status implements Parcelable{ } - public static void transform(Context context, Status status){ + public static void transform(Context context, Status status) { - if( ((Activity)context).isFinishing() || status == null) + if (((Activity) context).isFinishing() || status == null) return; SpannableString spannableStringContent, spannableStringCW; - if( (status.getReblog() != null && status.getReblog().getContent() == null) || (status.getReblog() == null && status.getContent() == null)) + if ((status.getReblog() != null && status.getReblog().getContent() == null) || (status.getReblog() == null && status.getContent() == null)) return; - String content = status.getReblog() != null ?status.getReblog().getContent():status.getContent(); + String content = status.getReblog() != null ? status.getReblog().getContent() : status.getContent(); Pattern aLink = Pattern.compile("]*(((?!<\\/a).)*)<\\/a>"); Matcher matcherALink = aLink.matcher(content); int count = 0; - while (matcherALink.find()){ + while (matcherALink.find()) { String beforemodification; String urlText = matcherALink.group(3); urlText = urlText.substring(1); beforemodification = urlText; - if( !beforemodification.startsWith("http")) { + if (!beforemodification.startsWith("http")) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) urlText = new SpannableString(Html.fromHtml(urlText, Html.FROM_HTML_MODE_LEGACY)).toString(); else @@ -632,11 +640,11 @@ public class Status implements Parcelable{ urlText = urlText.replace("http://", "").replace("https://", "").replace("www.", ""); if (urlText.length() > 31) { urlText = urlText.substring(0, 30); - urlText += "…"+count; + urlText += "…" + count; count++; } - }else if( urlText.startsWith("@")){ - urlText += "|"+count; + } else if (urlText.startsWith("@")) { + urlText += "|" + count; count++; } content = content.replaceFirst(Pattern.quote(beforemodification), Matcher.quoteReplacement(urlText)); @@ -645,7 +653,7 @@ public class Status implements Parcelable{ Matcher matcher = Helper.youtubePattern.matcher(content); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); boolean invidious = sharedpreferences.getBoolean(Helper.SET_INVIDIOUS, false); - if( invidious ) { + if (invidious) { while (matcher.find()) { final String youtubeId = matcher.group(2); String invidiousHost = sharedpreferences.getString(Helper.SET_INVIDIOUS_HOST, Helper.DEFAULT_INVIDIOUS_HOST); @@ -658,19 +666,19 @@ public class Status implements Parcelable{ List imgs = new ArrayList<>(); int i = 1; while (matcher.find()) { - content = content.replaceAll(Pattern.quote(matcher.group(0)), "
[media_"+i+"]
"); - imgs.add("[media_"+i+"]|"+matcher.group(1)); + content = content.replaceAll(Pattern.quote(matcher.group(0)), "
[media_" + i + "]
"); + imgs.add("[media_" + i + "]|" + matcher.group(1)); i++; } status.setImageURL(imgs); - content = content.replaceAll("(<\\s?p\\s?>)>(((?!(<\\/p>)|(<\\s?p\\s?>|<\\s?br\\s?\\/?>|<\\s?\\/p\\s?>$)","
$2

"); - content = content.replaceAll("^<\\s?p\\s?>(.*)<\\s?\\/p\\s?>$","$1"); + content = content.replaceAll("(<\\s?p\\s?>)>(((?!(<\\/p>)|(<\\s?p\\s?>|<\\s?br\\s?\\/?>|<\\s?\\/p\\s?>$)", "

$2

"); + content = content.replaceAll("^<\\s?p\\s?>(.*)<\\s?\\/p\\s?>$", "$1"); spannableStringContent = new SpannableString(content); final int[] j = {0}; - if( status.getImageURL() != null && status.getImageURL().size() > 0){ - for(String val: status.getImageURL()){ + if (status.getImageURL() != null && status.getImageURL().size() > 0) { + for (String val : status.getImageURL()) { String[] valArray = val.split("\\|"); - if( valArray.length > 1 ){ + if (valArray.length > 1) { String contentOriginal = valArray[0]; String url = valArray[1]; Glide.with(context) @@ -684,7 +692,7 @@ public class Status implements Parcelable{ //emojis can be used several times so we have to loop for (int startPosition = -1; (startPosition = spannableStringContent.toString().indexOf(targetedEmoji, startPosition + 1)) != -1; startPosition++) { final int endPosition = startPosition + targetedEmoji.length(); - if( endPosition <= spannableStringContent.toString().length() && endPosition >= startPosition) { + if (endPosition <= spannableStringContent.toString().length() && endPosition >= startPosition) { spannableStringContent.setSpan( new ImageSpan(context, Bitmap.createScaledBitmap(resource, (int) Helper.convertDpToPixel(300, context), @@ -694,7 +702,7 @@ public class Status implements Parcelable{ } } j[0]++; - if( j[0] == (status.getImageURL().size())) { + if (j[0] == (status.getImageURL().size())) { status.setContentSpan(spannableStringContent); } } @@ -704,28 +712,28 @@ public class Status implements Parcelable{ } } String spoilerText = ""; - if( status.getReblog() != null && status.getReblog().getSpoiler_text() != null) + if (status.getReblog() != null && status.getReblog().getSpoiler_text() != null) spoilerText = status.getReblog().getSpoiler_text(); - else if( status.getSpoiler_text() != null) + else if (status.getSpoiler_text() != null) spoilerText = status.getSpoiler_text(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) spannableStringCW = new SpannableString(Html.fromHtml(spoilerText, Html.FROM_HTML_MODE_LEGACY)); else spannableStringCW = new SpannableString(Html.fromHtml(spoilerText)); - if( spannableStringContent.length() > 0) + if (spannableStringContent.length() > 0) status.setContentSpan(treatment(context, spannableStringContent, status)); - if( spannableStringCW.length() > 0) + if (spannableStringCW.length() > 0) status.setContentSpanCW(spannableStringCW); - SpannableString displayNameSpan = new SpannableString(status.reblog!=null?status.getReblog().getAccount().getDisplay_name():status.getAccount().getDisplay_name()); - if( displayNameSpan.length() > 0) + SpannableString displayNameSpan = new SpannableString(status.reblog != null ? status.getReblog().getAccount().getDisplay_name() : status.getAccount().getDisplay_name()); + if (displayNameSpan.length() > 0) status.setDisplayNameSpan(displayNameSpan); } - private static SpannableString treatment(final Context context, SpannableString spannableString, Status status){ + private static SpannableString treatment(final Context context, SpannableString spannableString, Status status) { URLSpan[] urls = spannableString.getSpans(0, spannableString.length(), URLSpan.class); - for(URLSpan span : urls) + for (URLSpan span : urls) spannableString.removeSpan(span); List mentions = status.getReblog() != null ? status.getReblog().getMentions() : status.getMentions(); @@ -738,7 +746,7 @@ public class Status implements Parcelable{ HashMap targetedURL = new HashMap<>(); HashMap accountsMentionUnknown = new HashMap<>(); String liveInstance = Helper.getLiveInstance(context); - while (matcher.find()){ + while (matcher.find()) { String key; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) @@ -747,23 +755,21 @@ public class Status implements Parcelable{ key = new SpannableString(Html.fromHtml(matcher.group(3))).toString(); key = key.substring(1); - if( !key.startsWith("#") && !key.startsWith("@") && !key.trim().equals("") && !matcher.group(2).contains("search?tag=") && !matcher.group(2).contains(liveInstance+"/users/")) { + if (!key.startsWith("#") && !key.startsWith("@") && !key.trim().equals("") && !matcher.group(2).contains("search?tag=") && !matcher.group(2).contains(liveInstance + "/users/")) { String url; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { url = Html.fromHtml(matcher.group(2), Html.FROM_HTML_MODE_LEGACY).toString(); - } - else { + } else { url = Html.fromHtml(matcher.group(2)).toString(); } targetedURL.put(key, url); - }else if( key.startsWith("@") || matcher.group(2).contains(liveInstance+"/users/") ){ + } else if (key.startsWith("@") || matcher.group(2).contains(liveInstance + "/users/")) { String acct; String url; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { url = Html.fromHtml(matcher.group(2), Html.FROM_HTML_MODE_LEGACY).toString(); - } - else { + } else { url = Html.fromHtml(matcher.group(2)).toString(); } @@ -775,7 +781,7 @@ public class Status implements Parcelable{ } catch (URISyntaxException e) { e.printStackTrace(); } - if( key.startsWith("@")) + if (key.startsWith("@")) acct = key.substring(1).split("\\|")[0]; else acct = key.split("\\|")[0]; @@ -784,23 +790,23 @@ public class Status implements Parcelable{ account.setInstance(instance); account.setUrl(url); String accountId = null; - for(Mention mention: mentions){ + for (Mention mention : mentions) { String[] accountMentionAcct = mention.getAcct().split("@"); //Different isntance - if( accountMentionAcct.length > 1){ - if (mention.getAcct().equals(account.getAcct()+"@"+account.getInstance())) { + if (accountMentionAcct.length > 1) { + if (mention.getAcct().equals(account.getAcct() + "@" + account.getInstance())) { accountId = mention.getId(); break; } - }else{ - if ( mention.getAcct().equals(account.getAcct())) { + } else { + if (mention.getAcct().equals(account.getAcct())) { accountId = mention.getId(); break; } } } - if( accountId != null){ + if (accountId != null) { account.setId(accountId); } accountsMentionUnknown.put(key, account); @@ -809,9 +815,9 @@ public class Status implements Parcelable{ SpannableString spannableStringT; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) - spannableStringT = new SpannableString(Html.fromHtml(spannableString.toString().replaceAll("[\\s]{2}","  "), Html.FROM_HTML_MODE_LEGACY)); + spannableStringT = new SpannableString(Html.fromHtml(spannableString.toString().replaceAll("[\\s]{2}", "  "), Html.FROM_HTML_MODE_LEGACY)); else - spannableStringT = new SpannableString(Html.fromHtml(spannableString.toString().replaceAll("[\\s]{2}","  "))); + spannableStringT = new SpannableString(Html.fromHtml(spannableString.toString().replaceAll("[\\s]{2}", "  "))); replaceQuoteSpans(context, spannableStringT); URLSpan[] spans = spannableStringT.getSpans(0, spannableStringT.length(), URLSpan.class); for (URLSpan span : spans) { @@ -819,17 +825,18 @@ public class Status implements Parcelable{ } matcher = Helper.twitterPattern.matcher(spannableStringT); - while (matcher.find()){ + while (matcher.find()) { int matchStart = matcher.start(2); int matchEnd = matcher.end(); final String twittername = matcher.group(2); - if( matchEnd <= spannableStringT.toString().length() && matchEnd >= matchStart) + if (matchEnd <= spannableStringT.toString().length() && matchEnd >= matchStart) spannableStringT.setSpan(new ClickableSpan() { @Override public void onClick(@NonNull View textView) { - Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://twitter.com/"+twittername.substring(1).replace("@twitter.com",""))); + Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://twitter.com/" + twittername.substring(1).replace("@twitter.com", ""))); context.startActivity(intent); } + @Override public void updateDrawState(@NonNull TextPaint ds) { super.updateDrawState(ds); @@ -844,11 +851,11 @@ public class Status implements Parcelable{ }, matchStart, matchEnd, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); } - if( accountsMentionUnknown.size() > 0 ) { + if (accountsMentionUnknown.size() > 0) { Iterator it = accountsMentionUnknown.entrySet().iterator(); while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); + Map.Entry pair = (Map.Entry) it.next(); String key = (String) pair.getKey(); Account account = (Account) pair.getValue(); String targetedAccount = "@" + account.getAcct(); @@ -856,124 +863,126 @@ public class Status implements Parcelable{ int startPosition = spannableStringT.toString().toLowerCase().indexOf(key.toLowerCase()); int endPosition = startPosition + key.length(); - if( key.contains("|")) { + if (key.contains("|")) { key = key.split("\\|")[0]; SpannableStringBuilder ssb = new SpannableStringBuilder(); ssb.append(spannableStringT, 0, spannableStringT.length()); - if( ssb.length() >= endPosition) { - ssb.replace(startPosition,endPosition, key); + if (ssb.length() >= endPosition) { + ssb.replace(startPosition, endPosition, key); } spannableStringT = SpannableString.valueOf(ssb); endPosition = startPosition + key.length(); } //Accounts can be mentioned several times so we have to loop - if( endPosition <= spannableStringT.toString().length() && endPosition >= startPosition) + if (endPosition <= spannableStringT.toString().length() && endPosition >= startPosition) spannableStringT.setSpan(new ClickableSpan() { - @Override - public void onClick(@NonNull View textView) { - if( account.getId() == null) { - CrossActions.doCrossProfile(context, account); - }else{ - Intent intent = new Intent(context, ShowAccountActivity.class); - Bundle b = new Bundle(); - b.putString("accountId", account.getId()); - intent.putExtras(b); - context.startActivity(intent); - } - } - @Override - public void updateDrawState(@NonNull TextPaint ds) { - super.updateDrawState(ds); - ds.setUnderlineText(false); - if (theme == THEME_DARK) - ds.setColor(ContextCompat.getColor(context, R.color.dark_link_toot)); - else if (theme == THEME_BLACK) - ds.setColor(ContextCompat.getColor(context, R.color.black_link_toot)); - else if (theme == THEME_LIGHT) - ds.setColor(ContextCompat.getColor(context, R.color.light_link_toot)); - } - }, - startPosition, endPosition, - Spanned.SPAN_INCLUSIVE_EXCLUSIVE); + @Override + public void onClick(@NonNull View textView) { + if (account.getId() == null) { + CrossActions.doCrossProfile(context, account); + } else { + Intent intent = new Intent(context, ShowAccountActivity.class); + Bundle b = new Bundle(); + b.putString("accountId", account.getId()); + intent.putExtras(b); + context.startActivity(intent); + } + } + + @Override + public void updateDrawState(@NonNull TextPaint ds) { + super.updateDrawState(ds); + ds.setUnderlineText(false); + if (theme == THEME_DARK) + ds.setColor(ContextCompat.getColor(context, R.color.dark_link_toot)); + else if (theme == THEME_BLACK) + ds.setColor(ContextCompat.getColor(context, R.color.black_link_toot)); + else if (theme == THEME_LIGHT) + ds.setColor(ContextCompat.getColor(context, R.color.light_link_toot)); + } + }, + startPosition, endPosition, + Spanned.SPAN_INCLUSIVE_EXCLUSIVE); } it.remove(); } } - if( targetedURL.size() > 0 ){ + if (targetedURL.size() > 0) { Iterator it = targetedURL.entrySet().iterator(); while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); + Map.Entry pair = (Map.Entry) it.next(); String key = (String) pair.getKey(); String url = (String) pair.getValue(); if (spannableStringT.toString().toLowerCase().contains(key.toLowerCase())) { //Accounts can be mentioned several times so we have to loop int startPosition = spannableStringT.toString().toLowerCase().indexOf(key.toLowerCase()); int endPosition = startPosition + key.length(); - if( key.contains("…") && !key.endsWith("…")) { - key = key.split("…")[0]+"…"; + if (key.contains("…") && !key.endsWith("…")) { + key = key.split("…")[0] + "…"; SpannableStringBuilder ssb = new SpannableStringBuilder(); ssb.append(spannableStringT, 0, spannableStringT.length()); - if( ssb.length() >= endPosition) { + if (ssb.length() >= endPosition) { ssb.replace(startPosition, endPosition, key); } spannableStringT = SpannableString.valueOf(ssb); endPosition = startPosition + key.length(); } - if( endPosition <= spannableStringT.toString().length() && endPosition >= startPosition) { + if (endPosition <= spannableStringT.toString().length() && endPosition >= startPosition) { spannableStringT.setSpan(new ClickableSpan() { - @Override - public void onClick(@NonNull View textView) { - String finalUrl = url; - Pattern link = Pattern.compile("https?:\\/\\/([\\da-z\\.-]+\\.[a-z\\.]{2,10})\\/(@[\\w._-]*[0-9]*)(\\/[0-9]{1,})?$"); - Matcher matcherLink = link.matcher(url); - if( matcherLink.find() && !url.contains("medium.com")){ - if( matcherLink.group(3) != null && matcherLink.group(3).length() > 0 ){ //It's a toot - CrossActions.doCrossConversation(context, finalUrl); - }else{//It's an account - Account account = new Account(); - String acct = matcherLink.group(2); - if( acct != null){ - if( acct.startsWith("@")) - acct = acct.substring(1); - account.setAcct(acct); - account.setInstance(matcherLink.group(1)); - CrossActions.doCrossProfile(context, account); - } + @Override + public void onClick(@NonNull View textView) { + String finalUrl = url; + Pattern link = Pattern.compile("https?:\\/\\/([\\da-z\\.-]+\\.[a-z\\.]{2,10})\\/(@[\\w._-]*[0-9]*)(\\/[0-9]{1,})?$"); + Matcher matcherLink = link.matcher(url); + if (matcherLink.find() && !url.contains("medium.com")) { + if (matcherLink.group(3) != null && matcherLink.group(3).length() > 0) { //It's a toot + CrossActions.doCrossConversation(context, finalUrl); + } else {//It's an account + Account account = new Account(); + String acct = matcherLink.group(2); + if (acct != null) { + if (acct.startsWith("@")) + acct = acct.substring(1); + account.setAcct(acct); + account.setInstance(matcherLink.group(1)); + CrossActions.doCrossProfile(context, account); + } - } + } - }else { - link = Pattern.compile("(https?:\\/\\/[\\da-z\\.-]+\\.[a-z\\.]{2,10})\\/videos\\/watch\\/(\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12})$"); - matcherLink = link.matcher(url); - if( matcherLink.find()){ //Peertubee video - Intent intent = new Intent(context, PeertubeActivity.class); - Bundle b = new Bundle(); - String url = matcherLink.group(1) + "/videos/watch/" + matcherLink.group(2); - b.putString("peertubeLinkToFetch", url); - b.putString("peertube_instance", matcherLink.group(1).replace("https://","").replace("http://","")); - b.putString("video_id", matcherLink.group(2)); - intent.putExtras(b); - context.startActivity(intent); - }else { - if( !url.startsWith("http://") && ! url.startsWith("https://")) - finalUrl = "http://" + url; - Helper.openBrowser(context, finalUrl); - } + } else { + link = Pattern.compile("(https?:\\/\\/[\\da-z\\.-]+\\.[a-z\\.]{2,10})\\/videos\\/watch\\/(\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12})$"); + matcherLink = link.matcher(url); + if (matcherLink.find()) { //Peertubee video + Intent intent = new Intent(context, PeertubeActivity.class); + Bundle b = new Bundle(); + String url = matcherLink.group(1) + "/videos/watch/" + matcherLink.group(2); + b.putString("peertubeLinkToFetch", url); + b.putString("peertube_instance", matcherLink.group(1).replace("https://", "").replace("http://", "")); + b.putString("video_id", matcherLink.group(2)); + intent.putExtras(b); + context.startActivity(intent); + } else { + if (!url.startsWith("http://") && !url.startsWith("https://")) + finalUrl = "http://" + url; + Helper.openBrowser(context, finalUrl); + } - } - } - @Override - public void updateDrawState(@NonNull TextPaint ds) { - super.updateDrawState(ds); - ds.setUnderlineText(false); - if (theme == THEME_DARK) - ds.setColor(ContextCompat.getColor(context, R.color.dark_link_toot)); - else if (theme == THEME_BLACK) - ds.setColor(ContextCompat.getColor(context, R.color.black_link_toot)); - else if (theme == THEME_LIGHT) - ds.setColor(ContextCompat.getColor(context, R.color.light_link_toot)); - } - }, + } + } + + @Override + public void updateDrawState(@NonNull TextPaint ds) { + super.updateDrawState(ds); + ds.setUnderlineText(false); + if (theme == THEME_DARK) + ds.setColor(ContextCompat.getColor(context, R.color.dark_link_toot)); + else if (theme == THEME_BLACK) + ds.setColor(ContextCompat.getColor(context, R.color.black_link_toot)); + else if (theme == THEME_LIGHT) + ds.setColor(ContextCompat.getColor(context, R.color.light_link_toot)); + } + }, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); } @@ -982,15 +991,15 @@ public class Status implements Parcelable{ } } matcher = Helper.hashtagPattern.matcher(spannableStringT); - while (matcher.find()){ + while (matcher.find()) { int matchStart = matcher.start(1); int matchEnd = matcher.end(); final String tag = spannableStringT.toString().substring(matchStart, matchEnd); - if( matchEnd <= spannableStringT.toString().length() && matchEnd >= matchStart) + if (matchEnd <= spannableStringT.toString().length() && matchEnd >= matchStart) spannableStringT.setSpan(new ClickableSpan() { @Override public void onClick(@NonNull View textView) { - if(MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { Intent intent = new Intent(context, HashTagActivity.class); Bundle b = new Bundle(); b.putString("tag", tag.substring(1)); @@ -998,6 +1007,7 @@ public class Status implements Parcelable{ context.startActivity(intent); } } + @Override public void updateDrawState(@NonNull TextPaint ds) { super.updateDrawState(ds); @@ -1013,17 +1023,17 @@ public class Status implements Parcelable{ } - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU){ + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU) { matcher = Helper.groupPattern.matcher(spannableStringT); - while (matcher.find()){ + while (matcher.find()) { int matchStart = matcher.start(1); int matchEnd = matcher.end(); final String groupname = spannableStringT.toString().substring(matchStart, matchEnd); - if( matchEnd <= spannableStringT.toString().length() && matchEnd >= matchStart) + if (matchEnd <= spannableStringT.toString().length() && matchEnd >= matchStart) spannableStringT.setSpan(new ClickableSpan() { @Override public void onClick(@NonNull View textView) { - if(MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { Intent intent = new Intent(context, GroupActivity.class); Bundle b = new Bundle(); b.putString("groupname", groupname.substring(1)); @@ -1031,6 +1041,7 @@ public class Status implements Parcelable{ context.startActivity(intent); } } + @Override public void updateDrawState(@NonNull TextPaint ds) { super.updateDrawState(ds); @@ -1049,11 +1060,11 @@ public class Status implements Parcelable{ return spannableStringT; } - public static void transformTranslation(Context context, Status status){ + public static void transformTranslation(Context context, Status status) { - if( ((Activity)context).isFinishing() || status == null) + if (((Activity) context).isFinishing() || status == null) return; - if( (status.getReblog() != null && status.getReblog().getContent() == null) || (status.getReblog() == null && status.getContent() == null)) + if ((status.getReblog() != null && status.getReblog().getContent() == null) || (status.getReblog() == null && status.getContent() == null)) return; SpannableString spannableStringTranslated; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) @@ -1063,40 +1074,41 @@ public class Status implements Parcelable{ status.setContentSpanTranslated(treatment(context, spannableStringTranslated, status)); String displayName; - if( status.getReblog() != null){ + if (status.getReblog() != null) { displayName = status.getReblog().getAccount().getDisplay_name(); - }else { + } else { displayName = status.getAccount().getDisplay_name(); } SpannableString contentSpanTranslated = status.getContentSpanTranslated(); Matcher matcherALink = Patterns.WEB_URL.matcher(contentSpanTranslated.toString()); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - while (matcherALink.find()){ + while (matcherALink.find()) { int matchStart = matcherALink.start(); int matchEnd = matcherALink.end(); final String url = contentSpanTranslated.toString().substring(matcherALink.start(1), matcherALink.end(1)); - if( matchEnd <= contentSpanTranslated.toString().length() && matchEnd >= matchStart) + if (matchEnd <= contentSpanTranslated.toString().length() && matchEnd >= matchStart) contentSpanTranslated.setSpan(new ClickableSpan() { - @Override - public void onClick(@NonNull View textView) { - String finalUrl = url; - if( !url.startsWith("http://") && ! url.startsWith("https://")) - finalUrl = "http://" + url; - Helper.openBrowser(context, finalUrl); - } - @Override - public void updateDrawState(@NonNull TextPaint ds) { - super.updateDrawState(ds); - ds.setUnderlineText(false); - if (theme == THEME_DARK) - ds.setColor(ContextCompat.getColor(context, R.color.dark_link_toot)); - else if (theme == THEME_BLACK) - ds.setColor(ContextCompat.getColor(context, R.color.black_link_toot)); - else if (theme == THEME_LIGHT) - ds.setColor(ContextCompat.getColor(context, R.color.light_link_toot)); - } - }, + @Override + public void onClick(@NonNull View textView) { + String finalUrl = url; + if (!url.startsWith("http://") && !url.startsWith("https://")) + finalUrl = "http://" + url; + Helper.openBrowser(context, finalUrl); + } + + @Override + public void updateDrawState(@NonNull TextPaint ds) { + super.updateDrawState(ds); + ds.setUnderlineText(false); + if (theme == THEME_DARK) + ds.setColor(ContextCompat.getColor(context, R.color.dark_link_toot)); + else if (theme == THEME_BLACK) + ds.setColor(ContextCompat.getColor(context, R.color.black_link_toot)); + else if (theme == THEME_LIGHT) + ds.setColor(ContextCompat.getColor(context, R.color.light_link_toot)); + } + }, matchStart, matchEnd, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); @@ -1107,18 +1119,18 @@ public class Status implements Parcelable{ } - public static void makeEmojis(final Context context, final OnRetrieveEmojiInterface listener, Status status){ + public static void makeEmojis(final Context context, final OnRetrieveEmojiInterface listener, Status status) { - if( ((Activity)context).isFinishing() ) + if (((Activity) context).isFinishing()) return; - if( status.getAccount() == null) + if (status.getAccount() == null) return; - if( status.getReblog() != null && status.getReblog().getEmojis() == null) + if (status.getReblog() != null && status.getReblog().getEmojis() == null) return; - if( status.getReblog() == null && status.getEmojis() == null) + if (status.getReblog() == null && status.getEmojis() == null) return; final List emojis = status.getReblog() != null ? status.getReblog().getEmojis() : status.getEmojis(); - final List emojisAccounts = status.getReblog() != null ?status.getReblog().getAccount().getEmojis():status.getAccount().getEmojis(); + final List emojisAccounts = status.getReblog() != null ? status.getReblog().getAccount().getEmojis() : status.getAccount().getEmojis(); Account.makeAccountNameEmoji(context, null, status.getAccount()); @@ -1128,13 +1140,13 @@ public class Status implements Parcelable{ SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); boolean disableAnimatedEmoji = sharedpreferences.getBoolean(Helper.SET_DISABLE_ANIMATED_EMOJI, false); - if( emojisAccounts != null && emojisAccounts.size() > 0 ) { + if (emojisAccounts != null && emojisAccounts.size() > 0) { final int[] i = {0}; for (final Emojis emoji : emojisAccounts) { Glide.with(context) .asDrawable() .load(emoji.getUrl()) - .listener(new RequestListener() { + .listener(new RequestListener() { @Override public boolean onResourceReady(Drawable resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) { return false; @@ -1143,8 +1155,8 @@ public class Status implements Parcelable{ @Override public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) { i[0]++; - if( i[0] == (emojisAccounts.size())) { - listener.onRetrieveEmoji(status,false); + if (i[0] == (emojisAccounts.size())) { + listener.onRetrieveEmoji(status, false); } return false; } @@ -1157,14 +1169,14 @@ public class Status implements Parcelable{ //emojis can be used several times so we have to loop for (int startPosition = -1; (startPosition = displayNameSpan.toString().indexOf(targetedEmoji, startPosition + 1)) != -1; startPosition++) { final int endPosition = startPosition + targetedEmoji.length(); - if(endPosition <= displayNameSpan.toString().length() && endPosition >= startPosition) { + if (endPosition <= displayNameSpan.toString().length() && endPosition >= startPosition) { ImageSpan imageSpan; - if( !disableAnimatedEmoji) { - resource.setBounds(0,0,(int) Helper.convertDpToPixel(20, context),(int) Helper.convertDpToPixel(20, context)); + if (!disableAnimatedEmoji) { + resource.setBounds(0, 0, (int) Helper.convertDpToPixel(20, context), (int) Helper.convertDpToPixel(20, context)); resource.setVisible(true, true); imageSpan = new ImageSpan(resource); - }else{ + } else { resource.setVisible(true, true); Bitmap bitmap = drawableToBitmap(resource.getCurrent()); imageSpan = new ImageSpan(context, @@ -1178,7 +1190,7 @@ public class Status implements Parcelable{ } } i[0]++; - if( i[0] == (emojisAccounts.size())) { + if (i[0] == (emojisAccounts.size())) { status.setDisplayNameSpan(displayNameSpan); listener.onRetrieveEmoji(status, false); } @@ -1188,13 +1200,13 @@ public class Status implements Parcelable{ } } - if( emojis != null && emojis.size() > 0 ) { + if (emojis != null && emojis.size() > 0) { final int[] i = {0}; for (final Emojis emoji : emojis) { Glide.with(context) .asFile() .load(emoji.getUrl()) - .listener(new RequestListener() { + .listener(new RequestListener() { @Override public boolean onResourceReady(File resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) { return false; @@ -1203,8 +1215,8 @@ public class Status implements Parcelable{ @Override public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) { i[0]++; - if( i[0] == (emojis.size())) { - listener.onRetrieveEmoji(status,false); + if (i[0] == (emojis.size())) { + listener.onRetrieveEmoji(status, false); } return false; } @@ -1220,7 +1232,7 @@ public class Status implements Parcelable{ } else { resource = Drawable.createFromPath(resourceFile.getAbsolutePath()); } - if( resource == null){ + if (resource == null) { return; } final String targetedEmoji = ":" + emoji.getShortcode() + ":"; @@ -1228,14 +1240,14 @@ public class Status implements Parcelable{ //emojis can be used several times so we have to loop for (int startPosition = -1; (startPosition = contentSpan.toString().indexOf(targetedEmoji, startPosition + 1)) != -1; startPosition++) { final int endPosition = startPosition + targetedEmoji.length(); - if( endPosition <= contentSpan.toString().length() && endPosition >= startPosition) { + if (endPosition <= contentSpan.toString().length() && endPosition >= startPosition) { ImageSpan imageSpan; - if( !disableAnimatedEmoji) { + if (!disableAnimatedEmoji) { resource.setBounds(0, 0, (int) Helper.convertDpToPixel(20, context), (int) Helper.convertDpToPixel(20, context)); resource.setVisible(true, true); imageSpan = new ImageSpan(resource); - }else{ + } else { Bitmap bitmap = drawableToBitmap(resource.getCurrent()); imageSpan = new ImageSpan(context, Bitmap.createScaledBitmap(bitmap, (int) Helper.convertDpToPixel(20, context), @@ -1251,13 +1263,13 @@ public class Status implements Parcelable{ //emojis can be used several times so we have to loop for (int startPosition = -1; (startPosition = contentSpanCW.toString().indexOf(targetedEmoji, startPosition + 1)) != -1; startPosition++) { final int endPosition = startPosition + targetedEmoji.length(); - if( endPosition <= contentSpanCW.toString().length() && endPosition >= startPosition) { + if (endPosition <= contentSpanCW.toString().length() && endPosition >= startPosition) { ImageSpan imageSpan; - if( !disableAnimatedEmoji) { + if (!disableAnimatedEmoji) { resource.setBounds(0, 0, (int) Helper.convertDpToPixel(20, context), (int) Helper.convertDpToPixel(20, context)); resource.setVisible(true, true); imageSpan = new ImageSpan(resource); - }else{ + } else { resource.setVisible(true, true); Bitmap bitmap = drawableToBitmap(resource.getCurrent()); imageSpan = new ImageSpan(context, @@ -1271,7 +1283,7 @@ public class Status implements Parcelable{ } } i[0]++; - if( i[0] == (emojis.size())) { + if (i[0] == (emojis.size())) { status.setContentSpan(contentSpan); status.setContentSpanCW(contentSpanCW); status.setEmojiFound(true); @@ -1285,13 +1297,13 @@ public class Status implements Parcelable{ } - public static void makeImage(final Context context, final OnRetrieveImageInterface listener, Status status){ + public static void makeImage(final Context context, final OnRetrieveImageInterface listener, Status status) { - if( ((Activity)context).isFinishing() ) + if (((Activity) context).isFinishing()) return; - if( status.getAccount() == null) + if (status.getAccount() == null) return; - if( status.getImageURL() == null || status.getImageURL().size() == 0) + if (status.getImageURL() == null || status.getImageURL().size() == 0) return; SpannableString contentSpan = status.getContentSpan(); @@ -1303,7 +1315,7 @@ public class Status implements Parcelable{ Glide.with(context) .asBitmap() .load(imgURL) - .listener(new RequestListener() { + .listener(new RequestListener() { @Override public boolean onResourceReady(Bitmap resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) { return false; @@ -1312,8 +1324,8 @@ public class Status implements Parcelable{ @Override public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) { i[0]++; - if( i[0] == (status.getImageURL().size())) { - listener.onRetrieveImage(status,false); + if (i[0] == (status.getImageURL().size())) { + listener.onRetrieveImage(status, false); } return false; } @@ -1324,7 +1336,7 @@ public class Status implements Parcelable{ int w = resource.getWidth(); int h = resource.getHeight(); - if( w > 300 ){ + if (w > 300) { h = (h * 300) / w; w = 300; } @@ -1333,7 +1345,7 @@ public class Status implements Parcelable{ //emojis can be used several times so we have to loop for (int startPosition = -1; (startPosition = contentSpan.toString().indexOf(targetedEmoji, startPosition + 1)) != -1; startPosition++) { final int endPosition = startPosition + targetedEmoji.length(); - if( endPosition <= contentSpan.toString().length() && endPosition >= startPosition) + if (endPosition <= contentSpan.toString().length() && endPosition >= startPosition) contentSpan.setSpan( new ImageSpan(context, Bitmap.createScaledBitmap(resource, (int) Helper.convertDpToPixel(w, context), @@ -1342,7 +1354,7 @@ public class Status implements Parcelable{ } } i[0]++; - if( i[0] == (status.getImageURL().size())) { + if (i[0] == (status.getImageURL().size())) { status.setContentSpan(contentSpan); status.setImageFound(true); listener.onRetrieveImage(status, false); @@ -1354,13 +1366,13 @@ public class Status implements Parcelable{ } - public static void makeEmojisTranslation(final Context context, final OnRetrieveEmojiInterface listener, Status status){ + public static void makeEmojisTranslation(final Context context, final OnRetrieveEmojiInterface listener, Status status) { - if( ((Activity)context).isFinishing() ) + if (((Activity) context).isFinishing()) return; SpannableString spannableStringTranslated = null; SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - if( status.getContentTranslated() != null) { + if (status.getContentTranslated() != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) spannableStringTranslated = new SpannableString(Html.fromHtml(status.getContentTranslated(), Html.FROM_HTML_MODE_LEGACY)); else @@ -1369,14 +1381,14 @@ public class Status implements Parcelable{ } final List emojis = status.getReblog() != null ? status.getReblog().getEmojis() : status.getEmojis(); - if( emojis != null && emojis.size() > 0 ) { + if (emojis != null && emojis.size() > 0) { final int[] i = {0}; for (final Emojis emoji : emojis) { final SpannableString finalSpannableStringTranslated = spannableStringTranslated; Glide.with(context) .asBitmap() .load(emoji.getUrl()) - .listener(new RequestListener() { + .listener(new RequestListener() { @Override public boolean onResourceReady(Bitmap resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) { return false; @@ -1385,8 +1397,8 @@ public class Status implements Parcelable{ @Override public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) { i[0]++; - if( i[0] == (emojis.size())) { - if( finalSpannableStringTranslated != null) + if (i[0] == (emojis.size())) { + if (finalSpannableStringTranslated != null) status.setContentSpanTranslated(finalSpannableStringTranslated); listener.onRetrieveEmoji(status, true); } @@ -1402,17 +1414,17 @@ public class Status implements Parcelable{ //emojis can be used several times so we have to loop for (int startPosition = -1; (startPosition = finalSpannableStringTranslated.toString().indexOf(targetedEmoji, startPosition + 1)) != -1; startPosition++) { final int endPosition = startPosition + targetedEmoji.length(); - if( endPosition <= finalSpannableStringTranslated.toString().length() && endPosition >= startPosition) + if (endPosition <= finalSpannableStringTranslated.toString().length() && endPosition >= startPosition) finalSpannableStringTranslated.setSpan( - new ImageSpan(context, - Bitmap.createScaledBitmap(resource, (int) Helper.convertDpToPixel(20, context), - (int) Helper.convertDpToPixel(20, context), false)), startPosition, - endPosition, Spannable.SPAN_INCLUSIVE_EXCLUSIVE); + new ImageSpan(context, + Bitmap.createScaledBitmap(resource, (int) Helper.convertDpToPixel(20, context), + (int) Helper.convertDpToPixel(20, context), false)), startPosition, + endPosition, Spannable.SPAN_INCLUSIVE_EXCLUSIVE); } } i[0]++; - if( i[0] == (emojis.size())) { - if( finalSpannableStringTranslated != null) + if (i[0] == (emojis.size())) { + if (finalSpannableStringTranslated != null) status.setContentSpanTranslated(finalSpannableStringTranslated); status.setEmojiTranslateFound(true); listener.onRetrieveEmoji(status, true); @@ -1435,7 +1447,7 @@ public class Status implements Parcelable{ SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); int colord; - if( theme == THEME_BLACK) + if (theme == THEME_BLACK) colord = ContextCompat.getColor(context, R.color.dark_blockquote); else colord = ContextCompat.getColor(context, R.color.mastodonC4); @@ -1478,6 +1490,7 @@ public class Status implements Parcelable{ public void setClickable(boolean clickable) { isClickable = clickable; } + public boolean isClickable() { return isClickable; } @@ -1499,7 +1512,6 @@ public class Status implements Parcelable{ } - @Override public boolean equals(Object otherStatus) { return otherStatus != null && (otherStatus == this || otherStatus instanceof Status && this.getId().equals(((Status) otherStatus).getId())); @@ -1720,12 +1732,12 @@ public class Status implements Parcelable{ SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); boolean isCompactMode = sharedpreferences.getBoolean(Helper.SET_COMPACT_MODE, false); boolean isConsoleMode = sharedpreferences.getBoolean(Helper.SET_CONSOLE_MODE, false); - if( isCompactMode) - this.viewType = COMPACT_STATUS; - else if( isConsoleMode) - this.viewType = CONSOLE_STATUS; + if (isCompactMode) + this.viewType = COMPACT_STATUS; + else if (isConsoleMode) + this.viewType = CONSOLE_STATUS; else - this.viewType = DISPLAYED_STATUS; + this.viewType = DISPLAYED_STATUS; } diff --git a/app/src/main/java/app/fedilab/android/client/Entities/Suggestion.java b/app/src/main/java/app/fedilab/android/client/Entities/Suggestion.java index a587652cf..07e054637 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/Suggestion.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/Suggestion.java @@ -20,7 +20,7 @@ public class Suggestion { private String imageUrl; private suggestionType type; - public enum suggestionType{ + public enum suggestionType { TAG, ACCOUNT, EMOJI diff --git a/app/src/main/java/app/fedilab/android/client/Entities/Tag.java b/app/src/main/java/app/fedilab/android/client/Entities/Tag.java index cf679206c..e398bad49 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/Tag.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/Tag.java @@ -27,7 +27,8 @@ public class Tag implements Parcelable { private String name; private String url; - public Tag(){} + public Tag() { + } protected Tag(Parcel in) { name = in.readString(); diff --git a/app/src/main/java/app/fedilab/android/client/Entities/Version.java b/app/src/main/java/app/fedilab/android/client/Entities/Version.java index 57dc205b4..1b2a14365 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/Version.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/Version.java @@ -3,7 +3,6 @@ package app.fedilab.android.client.Entities; import androidx.annotation.NonNull; - /** * Created by Thomas on 15/09/2017. */ @@ -17,25 +16,26 @@ public class Version implements Comparable { } public Version(String version) { - if(version == null) + if (version == null) version = "2.1"; - if( version.contains("+")){ + if (version.contains("+")) { String[] versionA = version.split("\\+"); version = versionA[0]; } - if( version.endsWith(".")) + if (version.endsWith(".")) version = version.substring(0, version.length() - 1); version = version.replaceAll("[^\\d.]", ""); - if(!version.matches("[0-9]+(\\.[0-9]+)*")) + if (!version.matches("[0-9]+(\\.[0-9]+)*")) version = "2.1"; this.version = version; } - @Override public int compareTo(@NonNull Version that) { + @Override + public int compareTo(@NonNull Version that) { String[] thisParts = this.get().split("\\."); String[] thatParts = that.get().split("\\."); int length = Math.max(thisParts.length, thatParts.length); - for(int i = 0; i < length; i++) { + for (int i = 0; i < length; i++) { try { int thisPart = i < thisParts.length ? Integer.parseInt(thisParts[i]) : 0; @@ -45,12 +45,15 @@ public class Version implements Comparable { return -1; if (thisPart > thatPart) return 1; - }catch (NumberFormatException e){return 1;} + } catch (NumberFormatException e) { + return 1; + } } return 0; } - @Override public boolean equals(Object that) { + @Override + public boolean equals(Object that) { return this == that || that != null && this.getClass() == that.getClass() && this.compareTo((Version) that) == 0; } diff --git a/app/src/main/java/app/fedilab/android/client/GNUAPI.java b/app/src/main/java/app/fedilab/android/client/GNUAPI.java index 3d145c92c..f062a77df 100644 --- a/app/src/main/java/app/fedilab/android/client/GNUAPI.java +++ b/app/src/main/java/app/fedilab/android/client/GNUAPI.java @@ -19,6 +19,7 @@ import android.content.Intent; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; + import androidx.localbroadcastmanager.content.LocalBroadcastManager; import org.json.JSONArray; @@ -66,7 +67,6 @@ import static app.fedilab.android.helper.Helper.PREF_KEY_OAUTH_TOKEN; public class GNUAPI { - private Account account; private Context context; private Attachment attachment; @@ -84,21 +84,22 @@ public class GNUAPI { PUBLIC, LOCKED } + public GNUAPI(Context context) { this.context = context; SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - tootPerPage =sharedpreferences.getInt(Helper.SET_TOOT_PER_PAGE, Helper.TOOTS_PER_PAGE); + tootPerPage = sharedpreferences.getInt(Helper.SET_TOOT_PER_PAGE, Helper.TOOTS_PER_PAGE); accountPerPage = Helper.ACCOUNTS_PER_PAGE; notificationPerPage = Helper.NOTIFICATIONS_PER_PAGE; this.prefKeyOauthTokenT = sharedpreferences.getString(PREF_KEY_OAUTH_TOKEN, null); userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - if( Helper.getLiveInstance(context) != null) + if (Helper.getLiveInstance(context) != null) this.instance = Helper.getLiveInstance(context); else { SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(context)); Account account = new AccountDAO(context, db).getUniqAccount(userId, instance); - if( account == null) { + if (account == null) { APIError = new Error(); APIError.setError(context.getString(R.string.toast_error)); return; @@ -111,7 +112,7 @@ public class GNUAPI { public GNUAPI(Context context, String instance, String token) { this.context = context; - if( context == null) { + if (context == null) { apiResponse = new APIResponse(); APIError = new Error(); return; @@ -120,12 +121,12 @@ public class GNUAPI { tootPerPage = sharedpreferences.getInt(Helper.SET_TOOT_PER_PAGE, Helper.TOOTS_PER_PAGE); accountPerPage = Helper.ACCOUNTS_PER_PAGE; notificationPerPage = Helper.NOTIFICATIONS_PER_PAGE; - if( instance != null) + if (instance != null) this.instance = instance; else this.instance = Helper.getLiveInstance(context); - if( token != null) + if (token != null) this.prefKeyOauthTokenT = token; else this.prefKeyOauthTokenT = sharedpreferences.getString(PREF_KEY_OAUTH_TOKEN, null); @@ -134,8 +135,6 @@ public class GNUAPI { } - - /*** * Update credential of the authenticated user *synchronously* * @return APIResponse @@ -143,24 +142,24 @@ public class GNUAPI { public APIResponse updateCredential(String display_name, String note, ByteArrayInputStream avatar, String avatarName, ByteArrayInputStream header, String headerName, accountPrivacy privacy, HashMap customFields) { HashMap requestParams = new HashMap<>(); - if( display_name != null) + if (display_name != null) try { - requestParams.put("name",URLEncoder.encode(display_name, "UTF-8")); + requestParams.put("name", URLEncoder.encode(display_name, "UTF-8")); } catch (UnsupportedEncodingException e) { - requestParams.put("name",display_name); + requestParams.put("name", display_name); } - if( note != null) + if (note != null) try { - requestParams.put("description",URLEncoder.encode(note, "UTF-8")); + requestParams.put("description", URLEncoder.encode(note, "UTF-8")); } catch (UnsupportedEncodingException e) { - requestParams.put("description",note); + requestParams.put("description", note); } - if( privacy != null) - requestParams.put("locked",privacy== accountPrivacy.LOCKED?"true":"false"); + if (privacy != null) + requestParams.put("locked", privacy == accountPrivacy.LOCKED ? "true" : "false"); try { - if( requestParams.size() > 0) - new HttpsConnection(context, this.instance).patch(getAbsoluteUrl("/accounts/update_profile"), 60, requestParams, avatar, null, null, null, prefKeyOauthTokenT); - if( avatar!= null && avatarName != null) + if (requestParams.size() > 0) + new HttpsConnection(context, this.instance).patch(getAbsoluteUrl("/accounts/update_profile"), 60, requestParams, avatar, null, null, null, prefKeyOauthTokenT); + if (avatar != null && avatarName != null) new HttpsConnection(context, this.instance).patch(getAbsoluteUrl("/accounts/update_profile_image"), 60, null, avatar, avatarName, null, null, prefKeyOauthTokenT); } catch (HttpsConnection.HttpsConnectionException e) { @@ -202,6 +201,7 @@ public class GNUAPI { /** * Returns an account + * * @param accountId String account fetched * @return Account entity */ @@ -209,7 +209,7 @@ public class GNUAPI { account = new Account(); HashMap params = new HashMap<>(); - params.put("user_id",accountId); + params.put("user_id", accountId); try { String response = new HttpsConnection(context, this.instance).get(getAbsoluteUrl("/users/show.json"), 60, params, prefKeyOauthTokenT); account = parseAccountResponse(context, new JSONObject(response)); @@ -231,34 +231,36 @@ public class GNUAPI { /** * Retrieves group *synchronously* + * * @param max_id String id max * @return APIResponse */ @SuppressWarnings("SameParameterValue") - public APIResponse getGroups(String max_id){ + public APIResponse getGroups(String max_id) { return getGroups(max_id, null); } /** * Retrieves group *synchronously* - * @param max_id String id max + * + * @param max_id String id max * @param since_id String since the id * @return APIResponse */ @SuppressWarnings("SameParameterValue") - private APIResponse getGroups(String max_id, String since_id){ + private APIResponse getGroups(String max_id, String since_id) { HashMap params = new HashMap<>(); - if( max_id != null ) + if (max_id != null) params.put("max_id", max_id); - if( since_id != null ) + if (since_id != null) params.put("since_id", since_id); accounts = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); String response = httpsConnection.get(getAbsoluteUrl("/statusnet/groups/list.json"), 60, params, prefKeyOauthTokenT); accounts = parseGroups(context, new JSONArray(response)); - if( accounts.size() > 0) { + if (accounts.size() > 0) { apiResponse.setSince_id(accounts.get(0).getId()); apiResponse.setMax_id(accounts.get(accounts.size() - 1).getId()); } @@ -279,15 +281,16 @@ public class GNUAPI { /** * Parse json response for several groups + * * @param jsonArray JSONArray * @return List */ - private static List parseGroups(Context context, JSONArray jsonArray){ + private static List parseGroups(Context context, JSONArray jsonArray) { List groups = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ){ + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Account group = parseGroups(context, resobj); @@ -303,10 +306,11 @@ public class GNUAPI { /** * Parse json response for unique group + * * @param resobj JSONObject * @return Account */ - private static Account parseGroups(Context context, JSONObject resobj){ + private static Account parseGroups(Context context, JSONObject resobj) { Account group = new Account(); try { group.setId(resobj.get("id").toString()); @@ -324,11 +328,13 @@ public class GNUAPI { group.setFollowers_count(resobj.getInt("member_count")); //group.setMini_logo(resobj.getString("mini_logo")); //group.setModified(Helper.mstStringToDate(context, resobj.getString("modified"))); - group.setAcct("!"+resobj.getString("nickname")); + group.setAcct("!" + resobj.getString("nickname")); group.setAvatar_static(resobj.getString("original_logo")); group.setHeader(resobj.getString("stream_logo")); group.setUrl(resobj.getString("url")); - } catch (JSONException ignored) {ignored.printStackTrace();} catch (ParseException e) { + } catch (JSONException ignored) { + ignored.printStackTrace(); + } catch (ParseException e) { e.printStackTrace(); } @@ -338,28 +344,30 @@ public class GNUAPI { /** * Retrieves group timeline *synchronously* + * * @param groupName String id group - * @param max_id String id max + * @param max_id String id max * @return APIResponse */ - public APIResponse getGroupTimeline(String groupName, String max_id){ + public APIResponse getGroupTimeline(String groupName, String max_id) { return getGroupTimeline(groupName, max_id, null); } /** * Retrieves group timeline *synchronously* + * * @param groupName String id group - * @param max_id String id max - * @param since_id String since the id + * @param max_id String id max + * @param since_id String since the id * @return APIResponse */ - private APIResponse getGroupTimeline(String groupName, String max_id, String since_id){ + private APIResponse getGroupTimeline(String groupName, String max_id, String since_id) { HashMap params = new HashMap<>(); - if( max_id != null ) + if (max_id != null) params.put("max_id", max_id); - if( since_id != null ) + if (since_id != null) params.put("since_id", since_id); statuses = new ArrayList<>(); try { @@ -368,7 +376,7 @@ public class GNUAPI { url = getAbsoluteUrl(String.format("/statusnet/groups/timeline/%s.json", groupName)); String response = httpsConnection.get(url, 60, params, prefKeyOauthTokenT); statuses = parseStatuses(context, new JSONArray(response)); - if( statuses.size() > 0) { + if (statuses.size() > 0) { apiResponse.setSince_id(statuses.get(0).getId()); apiResponse.setMax_id(statuses.get(statuses.size() - 1).getId()); } @@ -388,9 +396,9 @@ public class GNUAPI { } - /** * Returns a relationship between the authenticated account and an account + * * @param accountId String account fetched * @return Relationship entity */ @@ -402,12 +410,12 @@ public class GNUAPI { try { String response; - if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU) { - params.put("target_id",accountId); + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU) { + params.put("target_id", accountId); response = new HttpsConnection(context, this.instance).get(getAbsoluteUrl("/friendships/show.json"), 60, params, prefKeyOauthTokenT); relationship = parseRelationshipResponse(new JSONObject(response)); - }else if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { - params.put("user_id",accountId); + } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + params.put("user_id", accountId); response = new HttpsConnection(context, this.instance).get(getAbsoluteUrl("/users/show.json"), 60, params, prefKeyOauthTokenT); JSONObject resobj = new JSONObject(response); try { @@ -418,12 +426,12 @@ public class GNUAPI { relationship.setBlocking(Boolean.valueOf(resobj.get("statusnet_blocking").toString())); try { relationship.setMuting(Boolean.valueOf(resobj.get("muting").toString())); - }catch (Exception ignored){ + } catch (Exception ignored) { relationship.setMuting(false); } try { relationship.setMuting_notifications(!Boolean.valueOf(resobj.get("notifications_enabled").toString())); - }catch (Exception ignored){ + } catch (Exception ignored) { relationship.setMuting_notifications(false); } relationship.setEndorsed(false); @@ -450,18 +458,17 @@ public class GNUAPI { } - - /** * Returns a relationship between the authenticated account and an account + * * @param accounts ArrayList accounts fetched * @return Relationship entity */ public APIResponse getRelationship(List accounts) { HashMap params = new HashMap<>(); - if( accounts != null && accounts.size() > 0 ) { + if (accounts != null && accounts.size() > 0) { StringBuilder parameters = new StringBuilder(); - for(Account account: accounts) + for (Account account : accounts) parameters.append("target_id[]=").append(account.getId()).append("&"); parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1).substring(12)); params.put("target_id[]", parameters.toString()); @@ -555,7 +562,7 @@ public class GNUAPI { * @return APIResponse */ @SuppressWarnings("SameParameterValue") - private APIResponse getStatus(String accountId,boolean exclude_replies, String max_id, String since_id, int limit) { + private APIResponse getStatus(String accountId, boolean exclude_replies, String max_id, String since_id, int limit) { HashMap params = new HashMap<>(); if (max_id != null) @@ -572,7 +579,7 @@ public class GNUAPI { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); String response = httpsConnection.get(getAbsoluteUrl("/statuses/user_timeline.json"), 60, params, prefKeyOauthTokenT); statuses = parseStatuses(context, new JSONArray(response)); - if( statuses.size() > 0) { + if (statuses.size() > 0) { apiResponse.setSince_id(statuses.get(0).getId()); apiResponse.setMax_id(statuses.get(statuses.size() - 1).getId()); } @@ -593,12 +600,11 @@ public class GNUAPI { } - /** * Retrieves accounts that reblogged the status *synchronously* * - * @param statusId String Id of the status - * @param max_id String id max + * @param statusId String Id of the status + * @param max_id String id max * @return APIResponse */ @SuppressWarnings("SameParameterValue") @@ -635,8 +641,8 @@ public class GNUAPI { /** * Retrieves accounts that favourited the status *synchronously* * - * @param statusId String Id of the status - * @param max_id String id max + * @param statusId String Id of the status + * @param max_id String id max * @return APIResponse */ @SuppressWarnings("SameParameterValue") @@ -673,7 +679,7 @@ public class GNUAPI { /** * Retrieves one status *synchronously* * - * @param statusId String Id of the status + * @param statusId String Id of the status * @return APIResponse */ public APIResponse getStatusbyId(String statusId) { @@ -702,7 +708,7 @@ public class GNUAPI { /** * Retrieves the context of status with replies *synchronously* * - * @param statusId Id of the status + * @param statusId Id of the status * @return List */ public app.fedilab.android.client.Entities.Context getStatusContext(String statusId, boolean directtimeline) { @@ -710,7 +716,7 @@ public class GNUAPI { try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); String response; - if( !directtimeline) + if (!directtimeline) response = httpsConnection.get(getAbsoluteUrl(String.format("/statusnet/conversation/%s.json", statusId)), 60, null, prefKeyOauthTokenT); else { HashMap params = new HashMap<>(); @@ -718,14 +724,14 @@ public class GNUAPI { response = httpsConnection.get(getAbsoluteUrl("/direct_messages/conversation.json"), 60, params, prefKeyOauthTokenT); } statuses = parseStatuses(context, new JSONArray(response)); - if( statuses != null && statuses.size() > 0){ + if (statuses != null && statuses.size() > 0) { ArrayList descendants = new ArrayList<>(); statusContext.setAncestors(statuses); statusContext.setDescendants(descendants); } } catch (HttpsConnection.HttpsConnectionException e) { - if(e.getStatusCode() != 404) + if (e.getStatusCode() != 404) setError(e.getStatusCode(), e); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); @@ -742,24 +748,27 @@ public class GNUAPI { /** * Retrieves direct timeline for the account *synchronously* - * @param max_id String id max + * + * @param max_id String id max * @return APIResponse */ - public APIResponse getDirectTimeline( String max_id) { + public APIResponse getDirectTimeline(String max_id) { return getDirectTimeline(max_id, null, tootPerPage); } /** * Retrieves conversation timeline for the account *synchronously* - * @param max_id String id max + * + * @param max_id String id max * @return APIResponse */ - public APIResponse getConversationTimeline( String max_id) { + public APIResponse getConversationTimeline(String max_id) { return getConversationTimeline(max_id, null, tootPerPage); } /** * Retrieves direct timeline for the account since an Id value *synchronously* + * * @return APIResponse */ public APIResponse getConversationTimelineSinceId(String since_id) { @@ -768,6 +777,7 @@ public class GNUAPI { /** * Retrieves conversation timeline for the account *synchronously* + * * @param max_id String id max * @param since_id String since the id * @param limit int limit - max value 40 @@ -782,7 +792,7 @@ public class GNUAPI { params.put("since_id", since_id); if (0 > limit || limit > 80) limit = 80; - params.put("limit",String.valueOf(limit)); + params.put("limit", String.valueOf(limit)); List conversations = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); @@ -807,6 +817,7 @@ public class GNUAPI { /** * Retrieves direct timeline for the account since an Id value *synchronously* + * * @return APIResponse */ public APIResponse getDirectTimelineSinceId(String since_id) { @@ -815,6 +826,7 @@ public class GNUAPI { /** * Retrieves direct timeline for the account *synchronously* + * * @param max_id String id max * @param since_id String since the id * @param limit int limit - max value 40 @@ -829,13 +841,13 @@ public class GNUAPI { params.put("since_id", since_id); if (0 > limit || limit > 80) limit = 80; - params.put("count",String.valueOf(limit)); + params.put("count", String.valueOf(limit)); statuses = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); String response = httpsConnection.get(getAbsoluteUrl("/direct_messages.json"), 60, params, prefKeyOauthTokenT); statuses = parseStatuses(context, new JSONArray(response)); - if( statuses.size() > 0) { + if (statuses.size() > 0) { apiResponse.setSince_id(statuses.get(0).getId()); apiResponse.setMax_id(statuses.get(statuses.size() - 1).getId()); } @@ -858,16 +870,18 @@ public class GNUAPI { /** * Retrieves home timeline for the account *synchronously* - * @param max_id String id max + * + * @param max_id String id max * @return APIResponse */ - public APIResponse getHomeTimeline( String max_id) { + public APIResponse getHomeTimeline(String max_id) { return getHomeTimeline(max_id, null, null, tootPerPage); } /** * Retrieves home timeline for the account since an Id value *synchronously* + * * @return APIResponse */ public APIResponse getHomeTimelineSinceId(String since_id) { @@ -876,6 +890,7 @@ public class GNUAPI { /** * Retrieves home timeline for the account from a min Id value *synchronously* + * * @return APIResponse */ public APIResponse getHomeTimelineMinId(String min_id) { @@ -885,6 +900,7 @@ public class GNUAPI { /** * Retrieves home timeline for the account *synchronously* + * * @param max_id String id max * @param since_id String since the id * @param limit int limit - max value 40 @@ -909,7 +925,7 @@ public class GNUAPI { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); String response = httpsConnection.get(getAbsoluteUrl("/statuses/home_timeline.json"), 60, params, prefKeyOauthTokenT); statuses = parseStatuses(context, new JSONArray(response)); - if( statuses.size() > 0) { + if (statuses.size() > 0) { apiResponse.setSince_id(statuses.get(0).getId()); apiResponse.setMax_id(statuses.get(statuses.size() - 1).getId()); } @@ -930,32 +946,32 @@ public class GNUAPI { } - - - /** * Retrieves public timeline for the account *synchronously* - * @param local boolean only local timeline + * + * @param local boolean only local timeline * @param max_id String id max * @return APIResponse */ - public APIResponse getPublicTimeline(String instanceName, boolean local, String max_id){ + public APIResponse getPublicTimeline(String instanceName, boolean local, String max_id) { return getPublicTimeline(local, instanceName, max_id, null, tootPerPage); } /** * Retrieves public timeline for the account *synchronously* - * @param local boolean only local timeline + * + * @param local boolean only local timeline * @param max_id String id max * @return APIResponse */ - public APIResponse getPublicTimeline(boolean local, String max_id){ + public APIResponse getPublicTimeline(boolean local, String max_id) { return getPublicTimeline(local, null, max_id, null, tootPerPage); } /** * Retrieves public timeline for the account since an Id value *synchronously* - * @param local boolean only local timeline + * + * @param local boolean only local timeline * @param since_id String id since * @return APIResponse */ @@ -965,8 +981,9 @@ public class GNUAPI { /** * Retrieves instance timeline since an Id value *synchronously* + * * @param instanceName String instance name - * @param since_id String id since + * @param since_id String id since * @return APIResponse */ public APIResponse getInstanceTimelineSinceId(String instanceName, String since_id) { @@ -975,35 +992,36 @@ public class GNUAPI { /** * Retrieves public timeline for the account *synchronously* - * @param local boolean only local timeline - * @param max_id String id max + * + * @param local boolean only local timeline + * @param max_id String id max * @param since_id String since the id - * @param limit int limit - max value 40 + * @param limit int limit - max value 40 * @return APIResponse */ - private APIResponse getPublicTimeline(boolean local, String instanceName, String max_id, String since_id, int limit){ + private APIResponse getPublicTimeline(boolean local, String instanceName, String max_id, String since_id, int limit) { HashMap params = new HashMap<>(); - if( local) + if (local) params.put("local", Boolean.toString(true)); - if( max_id != null ) + if (max_id != null) params.put("max_id", max_id); - if( since_id != null ) + if (since_id != null) params.put("since_id", since_id); - if( 0 > limit || limit > 40) + if (0 > limit || limit > 40) limit = 40; - params.put("count",String.valueOf(limit)); + params.put("count", String.valueOf(limit)); statuses = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); String url; - if(local) + if (local) url = getAbsoluteUrl("/statuses/public_timeline.json"); else url = getAbsoluteUrl("/statuses/public_and_external_timeline.json"); String response = httpsConnection.get(url, 60, params, prefKeyOauthTokenT); statuses = parseStatuses(context, new JSONArray(response)); - if( statuses.size() > 0) { + if (statuses.size() > 0) { apiResponse.setSince_id(statuses.get(0).getId()); apiResponse.setMax_id(statuses.get(statuses.size() - 1).getId()); } @@ -1023,42 +1041,41 @@ public class GNUAPI { } - - - - public APIResponse getCustomArtTimeline(boolean local, String tag, String max_id, List any, List all, List none){ + public APIResponse getCustomArtTimeline(boolean local, String tag, String max_id, List any, List all, List none) { return getArtTimeline(local, tag, max_id, null, any, all, none); } - public APIResponse getArtTimeline(boolean local, String max_id, List any, List all, List none){ + public APIResponse getArtTimeline(boolean local, String max_id, List any, List all, List none) { return getArtTimeline(local, null, max_id, null, any, all, none); } - public APIResponse getCustomArtTimelineSinceId(boolean local, String tag, String since_id, List any, List all, List none){ + public APIResponse getCustomArtTimelineSinceId(boolean local, String tag, String since_id, List any, List all, List none) { return getArtTimeline(local, tag, null, since_id, any, all, none); } - public APIResponse getArtTimelineSinceId(boolean local, String since_id, List any, List all, List none){ + public APIResponse getArtTimelineSinceId(boolean local, String since_id, List any, List all, List none) { return getArtTimeline(local, null, null, since_id, any, all, none); } + /** * Retrieves art timeline - * @param local boolean only local timeline + * + * @param local boolean only local timeline * @param max_id String id max * @return APIResponse */ - private APIResponse getArtTimeline(boolean local, String tag, String max_id, String since_id, List any, List all, List none){ - if( tag == null) + private APIResponse getArtTimeline(boolean local, String tag, String max_id, String since_id, List any, List all, List none) { + if (tag == null) tag = "mastoart"; APIResponse apiResponse = getPublicTimelineTag(tag, local, true, max_id, since_id, tootPerPage, any, all, none); APIResponse apiResponseReply = new APIResponse(); - if( apiResponse != null){ + if (apiResponse != null) { apiResponseReply.setMax_id(apiResponse.getMax_id()); apiResponseReply.setSince_id(apiResponse.getSince_id()); apiResponseReply.setStatuses(new ArrayList<>()); - if( apiResponse.getStatuses() != null && apiResponse.getStatuses().size() > 0){ - for( Status status: apiResponse.getStatuses()){ - if( status.getMedia_attachments() != null ) { + if (apiResponse.getStatuses() != null && apiResponse.getStatuses().size() > 0) { + for (Status status : apiResponse.getStatuses()) { + if (status.getMedia_attachments() != null) { String statusSerialized = Helper.statusToStringStorage(status); for (Attachment attachment : status.getMedia_attachments()) { Status newStatus = Helper.restoreStatusFromString(statusSerialized); @@ -1076,86 +1093,91 @@ public class GNUAPI { /** * Retrieves public tag timeline *synchronously* - * @param tag String - * @param local boolean only local timeline + * + * @param tag String + * @param local boolean only local timeline * @param max_id String id max * @return APIResponse */ @SuppressWarnings("SameParameterValue") - public APIResponse getPublicTimelineTag(String tag, boolean local, String max_id, List any, List all, List none){ + public APIResponse getPublicTimelineTag(String tag, boolean local, String max_id, List any, List all, List none) { return getPublicTimelineTag(tag, local, false, max_id, null, tootPerPage, any, all, none); } /** * Retrieves public tag timeline *synchronously* - * @param tag String - * @param local boolean only local timeline + * + * @param tag String + * @param local boolean only local timeline * @param since_id String since id * @return APIResponse */ @SuppressWarnings("SameParameterValue") - public APIResponse getPublicTimelineTagSinceId(String tag, boolean local, String since_id, List any, List all, List none){ + public APIResponse getPublicTimelineTagSinceId(String tag, boolean local, String since_id, List any, List all, List none) { return getPublicTimelineTag(tag, local, false, null, since_id, tootPerPage, any, all, none); } + /** * Retrieves public tag timeline *synchronously* - * @param tag String - * @param local boolean only local timeline - * @param max_id String id max + * + * @param tag String + * @param local boolean only local timeline + * @param max_id String id max * @param since_id String since the id - * @param limit int limit - max value 40 + * @param limit int limit - max value 40 * @return APIResponse */ @SuppressWarnings("SameParameterValue") - private APIResponse getPublicTimelineTag(String tag, boolean local, boolean onlymedia, String max_id, String since_id, int limit, List any, List all, List none){ + private APIResponse getPublicTimelineTag(String tag, boolean local, boolean onlymedia, String max_id, String since_id, int limit, List any, List all, List none) { HashMap params = new HashMap<>(); - if( local) + if (local) params.put("local", Boolean.toString(true)); - if( max_id != null ) + if (max_id != null) params.put("max_id", max_id); - if( since_id != null ) + if (since_id != null) params.put("since_id", since_id); - if( 0 > limit || limit > 40) + if (0 > limit || limit > 40) limit = 40; - if( onlymedia) + if (onlymedia) params.put("only_media", Boolean.toString(true)); - if( any != null && any.size() > 0) { + if (any != null && any.size() > 0) { StringBuilder parameters = new StringBuilder(); for (String a : any) parameters.append("any[]=").append(a).append("&"); parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1).substring(6)); params.put("any[]", parameters.toString()); } - if( all != null && all.size() > 0) { + if (all != null && all.size() > 0) { StringBuilder parameters = new StringBuilder(); for (String a : all) parameters.append("all[]=").append(a).append("&"); parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1).substring(6)); params.put("all[]", parameters.toString()); } - if( none != null && none.size() > 0) { + if (none != null && none.size() > 0) { StringBuilder parameters = new StringBuilder(); for (String a : none) parameters.append("none[]=").append(a).append("&"); parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1).substring(7)); params.put("none[]", parameters.toString()); } - params.put("limit",String.valueOf(limit)); + params.put("limit", String.valueOf(limit)); statuses = new ArrayList<>(); - if( tag == null) + if (tag == null) return null; try { String query = tag.trim(); HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) try { query = URLEncoder.encode(query, "UTF-8"); - } catch (UnsupportedEncodingException ignored) {} - String response = httpsConnection.get(getAbsoluteUrl(String.format("/timelines/tag/%s",query)), 60, params, prefKeyOauthTokenT); + } catch (UnsupportedEncodingException ignored) { + } + String response = httpsConnection.get(getAbsoluteUrl(String.format("/timelines/tag/%s", query)), 60, params, prefKeyOauthTokenT); statuses = parseStatuses(context, new JSONArray(response)); - if( statuses.size() > 0) { + if (statuses.size() > 0) { apiResponse.setSince_id(statuses.get(0).getId()); apiResponse.setMax_id(statuses.get(statuses.size() - 1).getId()); } @@ -1177,63 +1199,68 @@ public class GNUAPI { /** * Retrieves muted users by the authenticated account *synchronously* + * * @param max_id String id max * @return APIResponse */ - public APIResponse getMuted(String max_id){ - return getAccounts("/mutes/users/list.json",null, max_id, null, accountPerPage); + public APIResponse getMuted(String max_id) { + return getAccounts("/mutes/users/list.json", null, max_id, null, accountPerPage); } /** * Retrieves blocked users by the authenticated account *synchronously* + * * @param max_id String id max * @return APIResponse */ - public APIResponse getBlocks(String max_id){ - return getAccounts("/blocks/list.json",null, max_id, null, accountPerPage); + public APIResponse getBlocks(String max_id) { + return getAccounts("/blocks/list.json", null, max_id, null, accountPerPage); } /** * Retrieves following for the account specified by targetedId *synchronously* + * * @param targetedId String targetedId - * @param max_id String id max + * @param max_id String id max * @return APIResponse */ - public APIResponse getFollowing(String targetedId, String max_id){ - return getAccounts("/statuses/friends.json",targetedId, max_id, null, accountPerPage); + public APIResponse getFollowing(String targetedId, String max_id) { + return getAccounts("/statuses/friends.json", targetedId, max_id, null, accountPerPage); } /** * Retrieves followers for the account specified by targetedId *synchronously* + * * @param targetedId String targetedId - * @param max_id String id max + * @param max_id String id max * @return APIResponse */ - public APIResponse getFollowers(String targetedId, String max_id){ - return getAccounts("/statuses/followers.json",targetedId, max_id, null, accountPerPage); + public APIResponse getFollowers(String targetedId, String max_id) { + return getAccounts("/statuses/followers.json", targetedId, max_id, null, accountPerPage); } /** * Retrieves blocked users by the authenticated account *synchronously* - * @param max_id String id max + * + * @param max_id String id max * @param since_id String since the id - * @param limit int limit - max value 40 + * @param limit int limit - max value 40 * @return APIResponse */ @SuppressWarnings("SameParameterValue") - private APIResponse getAccounts(String action, String targetedId, String max_id, String since_id, int limit){ + private APIResponse getAccounts(String action, String targetedId, String max_id, String since_id, int limit) { HashMap params = new HashMap<>(); - if( max_id != null ) + if (max_id != null) params.put("max_id", max_id); - if( since_id != null ) + if (since_id != null) params.put("since_id", since_id); - if( 0 > limit || limit > 40) + if (0 > limit || limit > 40) limit = 40; - params.put("limit",String.valueOf(limit)); - if( targetedId != null) - params.put("user_id",targetedId); + params.put("limit", String.valueOf(limit)); + if (targetedId != null) + params.put("user_id", targetedId); accounts = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); @@ -1241,8 +1268,8 @@ public class GNUAPI { apiResponse.setSince_id(httpsConnection.getSince_id()); apiResponse.setMax_id(httpsConnection.getMax_id()); accounts = parseAccountResponse(new JSONArray(response)); - if( accounts != null && accounts.size() == 1 ){ - if(accounts.get(0).getAcct() == null){ + if (accounts != null && accounts.size() == 1) { + if (accounts.get(0).getAcct() == null) { Throwable error = new Throwable(context.getString(R.string.toast_error)); setError(500, error); } @@ -1263,34 +1290,35 @@ public class GNUAPI { } - - /** * Retrieves follow requests for the authenticated account *synchronously* + * * @param max_id String id max * @return APIResponse */ - public APIResponse getFollowRequest(String max_id){ + public APIResponse getFollowRequest(String max_id) { return getFollowRequest(max_id, null, accountPerPage); } + /** * Retrieves follow requests for the authenticated account *synchronously* - * @param max_id String id max + * + * @param max_id String id max * @param since_id String since the id - * @param limit int limit - max value 40 + * @param limit int limit - max value 40 * @return APIResponse */ @SuppressWarnings("SameParameterValue") - private APIResponse getFollowRequest(String max_id, String since_id, int limit){ + private APIResponse getFollowRequest(String max_id, String since_id, int limit) { HashMap params = new HashMap<>(); - if( max_id != null ) + if (max_id != null) params.put("max_id", max_id); - if( since_id != null ) + if (since_id != null) params.put("since_id", since_id); - if( 0 > limit || limit > 40) + if (0 > limit || limit > 40) limit = 40; - params.put("limit",String.valueOf(limit)); + params.put("limit", String.valueOf(limit)); accounts = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); @@ -1316,36 +1344,39 @@ public class GNUAPI { /** * Retrieves favourited status for the authenticated account *synchronously* + * * @param max_id String id max * @return APIResponse */ - public APIResponse getFavourites(String max_id){ + public APIResponse getFavourites(String max_id) { return getFavourites(max_id, null, tootPerPage); } + /** * Retrieves favourited status for the authenticated account *synchronously* - * @param max_id String id max + * + * @param max_id String id max * @param since_id String since the id - * @param limit int limit - max value 40 + * @param limit int limit - max value 40 * @return APIResponse */ @SuppressWarnings("SameParameterValue") - private APIResponse getFavourites(String max_id, String since_id, int limit){ + private APIResponse getFavourites(String max_id, String since_id, int limit) { HashMap params = new HashMap<>(); - if( max_id != null ) + if (max_id != null) params.put("max_id", max_id); - if( since_id != null ) + if (since_id != null) params.put("since_id", since_id); - if( 0 > limit || limit > 40) + if (0 > limit || limit > 40) limit = 40; - params.put("count",String.valueOf(limit)); + params.put("count", String.valueOf(limit)); statuses = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); String response = httpsConnection.get(getAbsoluteUrl("/favorites.json"), 60, params, prefKeyOauthTokenT); statuses = parseStatuses(context, new JSONArray(response)); - if( statuses.size() > 0) { + if (statuses.size() > 0) { apiResponse.setSince_id(statuses.get(0).getId()); apiResponse.setMax_id(statuses.get(statuses.size() - 1).getId()); } @@ -1367,21 +1398,23 @@ public class GNUAPI { /** * Makes the post action for a status + * * @param statusAction Enum - * @param targetedId String id of the targeted Id *can be this of a status or an account* + * @param targetedId String id of the targeted Id *can be this of a status or an account* * @return in status code - Should be equal to 200 when action is done */ - public int postAction(API.StatusAction statusAction, String targetedId){ + public int postAction(API.StatusAction statusAction, String targetedId) { return postAction(statusAction, targetedId, null, null); } /** * Makes the post action for a status - * @param targetedId String id of the targeted Id *can be this of a status or an account* + * + * @param targetedId String id of the targeted Id *can be this of a status or an account* * @param muteNotifications - boolean - notifications should be also muted * @return in status code - Should be equal to 200 when action is done */ - public int muteNotifications(String targetedId, boolean muteNotifications){ + public int muteNotifications(String targetedId, boolean muteNotifications) { HashMap params = new HashMap<>(); params.put("notifications", Boolean.toString(muteNotifications)); @@ -1404,48 +1437,50 @@ public class GNUAPI { /** * Makes the post action - * @param status Status object related to the status + * + * @param status Status object related to the status * @param comment String comment for the report * @return in status code - Should be equal to 200 when action is done */ - public int reportAction(Status status, String comment){ + public int reportAction(Status status, String comment) { return postAction(API.StatusAction.REPORT, null, status, comment); } - public int statusAction(Status status){ + public int statusAction(Status status) { return postAction(API.StatusAction.CREATESTATUS, null, status, null); } /** * Makes the post action + * * @param statusAction Enum - * @param targetedId String id of the targeted Id *can be this of a status or an account* - * @param status Status object related to the status - * @param comment String comment for the report + * @param targetedId String id of the targeted Id *can be this of a status or an account* + * @param status Status object related to the status + * @param comment String comment for the report * @return in status code - Should be equal to 200 when action is done */ - private int postAction(API.StatusAction statusAction, String targetedId, Status status, String comment ){ + private int postAction(API.StatusAction statusAction, String targetedId, Status status, String comment) { String action; HashMap params = null; - switch (statusAction){ + switch (statusAction) { case FAVOURITE: - if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU) { action = "/favorites/create.json"; params = new HashMap<>(); params.put("id", targetedId); - }else { + } else { action = "/friendica/activity/like.json"; params = new HashMap<>(); params.put("id", targetedId); } break; case UNFAVOURITE: - if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU) { action = "/favorites/destroy.json"; params = new HashMap<>(); params.put("id", targetedId); - }else { + } else { action = "/friendica/activity/unlike.json"; params = new HashMap<>(); params.put("id", targetedId); @@ -1478,7 +1513,7 @@ public class GNUAPI { params.put("user_id", targetedId); break; case UNBLOCK: - action ="/blocks/destroy.json"; + action = "/blocks/destroy.json"; params = new HashMap<>(); params.put("user_id", targetedId); break; @@ -1493,7 +1528,7 @@ public class GNUAPI { params.put("user_id", targetedId); break; case UNSTATUS: - if( !status.getVisibility().equals("direct")) + if (!status.getVisibility().equals("direct")) action = String.format("/statuses/destroy/%s.json", targetedId); else { action = "/direct_messages/destroy.json"; @@ -1503,41 +1538,41 @@ public class GNUAPI { break; case CREATESTATUS: params = new HashMap<>(); - if(! status.getVisibility().equals("direct")) + if (!status.getVisibility().equals("direct")) action = "/statuses/update.json"; else action = "/direct_messages/new.json"; - if( !status.getVisibility().equals("direct")) { + if (!status.getVisibility().equals("direct")) { try { params.put("status", URLEncoder.encode(status.getContent(), "UTF-8")); } catch (UnsupportedEncodingException e) { params.put("status", status.getContent()); } - }else{ + } else { try { params.put("text", URLEncoder.encode(status.getContent(), "UTF-8")); } catch (UnsupportedEncodingException e) { params.put("text", status.getContent()); } } - if( status.getContentType() != null) + if (status.getContentType() != null) params.put("content_type", status.getContentType()); - if( status.getIn_reply_to_id() != null) { - if( !status.getVisibility().equals("direct")) + if (status.getIn_reply_to_id() != null) { + if (!status.getVisibility().equals("direct")) params.put("in_reply_to_status_id", status.getIn_reply_to_id()); else params.put("replyto", status.getConversationId()); } - if( status.getMedia_attachments() != null && status.getMedia_attachments().size() > 0 ) { + if (status.getMedia_attachments() != null && status.getMedia_attachments().size() > 0) { StringBuilder parameters = new StringBuilder(); - for(Attachment attachment: status.getMedia_attachments()) + for (Attachment attachment : status.getMedia_attachments()) parameters.append(attachment.getId()).append(","); parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1)); params.put("media_ids", parameters.toString()); } - if( status.isSensitive()) + if (status.isSensitive()) params.put("possibly_sensitive", Boolean.toString(status.isSensitive())); - break; + break; default: return -1; } @@ -1546,19 +1581,20 @@ public class GNUAPI { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); String resp = httpsConnection.post(getAbsoluteUrl(action), 60, params, prefKeyOauthTokenT); actionCode = httpsConnection.getActionCode(); - if( statusAction == API.StatusAction.REBLOG || statusAction == API.StatusAction.UNREBLOG || statusAction == API.StatusAction.FAVOURITE || statusAction == API.StatusAction.UNFAVOURITE) { + if (statusAction == API.StatusAction.REBLOG || statusAction == API.StatusAction.UNREBLOG || statusAction == API.StatusAction.FAVOURITE || statusAction == API.StatusAction.UNFAVOURITE) { Bundle b = new Bundle(); try { Status status1 = parseStatuses(context, new JSONObject(resp)); b.putParcelable("status", status1); - } catch (JSONException ignored) {} + } catch (JSONException ignored) { + } Intent intentBC = new Intent(Helper.RECEIVE_ACTION); intentBC.putExtras(b); LocalBroadcastManager.getInstance(context).sendBroadcast(intentBC); SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); Account account = new AccountDAO(context, db).getAccountByToken(prefKeyOauthTokenT); new TimelineCacheDAO(context, db).update(targetedId, resp, account.getId(), account.getToken()); - }else if( statusAction == API.StatusAction.UNSTATUS){ + } else if (statusAction == API.StatusAction.UNSTATUS) { SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); new TimelineCacheDAO(context, db).remove(targetedId); } @@ -1576,25 +1612,24 @@ public class GNUAPI { } - - /** * Posts a status + * * @param status Status object related to the status * @return APIResponse */ - public APIResponse postStatusAction(Status status){ + public APIResponse postStatusAction(Status status) { HashMap params = new HashMap<>(); - if( status.getContentType() != null) + if (status.getContentType() != null) params.put("content_type", status.getContentType()); - if( !status.getVisibility().equals("direct")) { + if (!status.getVisibility().equals("direct")) { try { params.put("status", URLEncoder.encode(status.getContent(), "UTF-8")); } catch (UnsupportedEncodingException e) { params.put("status", status.getContent()); } - }else{ + } else { try { params.put("text", URLEncoder.encode(status.getContent(), "UTF-8")); } catch (UnsupportedEncodingException e) { @@ -1609,25 +1644,25 @@ public class GNUAPI { params.put("screen_name", currentAccount.getAcct()); } - if( status.getIn_reply_to_id() != null) - if( !status.getVisibility().equals("direct")) + if (status.getIn_reply_to_id() != null) + if (!status.getVisibility().equals("direct")) params.put("in_reply_to_status_id", status.getIn_reply_to_id()); else params.put("replyto", status.getIn_reply_to_id()); - if( status.getMedia_attachments() != null && status.getMedia_attachments().size() > 0 ) { + if (status.getMedia_attachments() != null && status.getMedia_attachments().size() > 0) { StringBuilder parameters = new StringBuilder(); - for(Attachment attachment: status.getMedia_attachments()) + for (Attachment attachment : status.getMedia_attachments()) parameters.append(attachment.getId()).append(","); parameters = new StringBuilder(parameters.substring(0, parameters.length() - 1)); params.put("media_ids", parameters.toString()); } - if( status.isSensitive()) + if (status.isSensitive()) params.put("possibly_sensitive", Boolean.toString(status.isSensitive())); statuses = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); String response; - if( !status.getVisibility().equals("direct")) + if (!status.getVisibility().equals("direct")) response = httpsConnection.post(getAbsoluteUrl("/statuses/update.json"), 60, params, prefKeyOauthTokenT); else response = httpsConnection.post(getAbsoluteUrl("/direct_messages/new.json"), 60, params, prefKeyOauthTokenT); @@ -1652,54 +1687,57 @@ public class GNUAPI { } - /** * Retrieves notifications for the authenticated account since an id*synchronously* + * * @param since_id String since max * @return APIResponse */ - public APIResponse getNotificationsSince(DisplayNotificationsFragment.Type type, String since_id, boolean display){ + public APIResponse getNotificationsSince(DisplayNotificationsFragment.Type type, String since_id, boolean display) { return getNotifications(type, null, since_id, notificationPerPage, display); } /** * Retrieves notifications for the authenticated account since an id*synchronously* + * * @param since_id String since max * @return APIResponse */ @SuppressWarnings("SameParameterValue") - public APIResponse getNotificationsSince(DisplayNotificationsFragment.Type type, String since_id, int notificationPerPage, boolean display){ + public APIResponse getNotificationsSince(DisplayNotificationsFragment.Type type, String since_id, int notificationPerPage, boolean display) { return getNotifications(type, null, since_id, notificationPerPage, display); } /** * Retrieves notifications for the authenticated account *synchronously* + * * @param max_id String id max * @return APIResponse */ - public APIResponse getNotifications(DisplayNotificationsFragment.Type type, String max_id, boolean display){ + public APIResponse getNotifications(DisplayNotificationsFragment.Type type, String max_id, boolean display) { return getNotifications(type, max_id, null, notificationPerPage, display); } /** * Retrieves notifications for the authenticated account *synchronously* - * @param max_id String id max + * + * @param max_id String id max * @param since_id String since the id - * @param limit int limit - max value 40 + * @param limit int limit - max value 40 * @return APIResponse */ - private APIResponse getNotifications(DisplayNotificationsFragment.Type type, String max_id, String since_id, int limit, boolean display){ + private APIResponse getNotifications(DisplayNotificationsFragment.Type type, String max_id, String since_id, int limit, boolean display) { HashMap params = new HashMap<>(); String stringType = null; - if( max_id != null ) + if (max_id != null) params.put("max_id", max_id); - if( since_id != null ) + if (since_id != null) params.put("since_id", since_id); - if( 0 > limit || limit > 30) + if (0 > limit || limit > 30) limit = 30; - params.put("count",String.valueOf(limit)); + params.put("count", String.valueOf(limit)); List notifications = new ArrayList<>(); String url = null; SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); @@ -1708,18 +1746,18 @@ public class GNUAPI { String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(context)); Account account = new AccountDAO(context, db).getUniqAccount(userId, instance); - if(type == DisplayNotificationsFragment.Type.MENTION){ - params.put("name",account.getAcct()); + if (type == DisplayNotificationsFragment.Type.MENTION) { + params.put("name", account.getAcct()); url = getAbsoluteUrl("/statuses/mentions_timeline.json"); stringType = "mention"; - }else if(type == DisplayNotificationsFragment.Type.BOOST){ + } else if (type == DisplayNotificationsFragment.Type.BOOST) { url = getAbsoluteUrl("/statuses/retweets_of_me.json"); stringType = "reblog"; - }else if(type == DisplayNotificationsFragment.Type.FOLLOW){ + } else if (type == DisplayNotificationsFragment.Type.FOLLOW) { url = getAbsoluteUrl("/statuses/followers.json"); stringType = "follow"; } - if( url == null){ + if (url == null) { Error error = new Error(); error.setStatusCode(500); error.setError(context.getString(R.string.toast_error)); @@ -1731,29 +1769,29 @@ public class GNUAPI { String response = httpsConnection.get(url, 60, params, prefKeyOauthTokenT); apiResponse.setSince_id(httpsConnection.getSince_id()); apiResponse.setMax_id(httpsConnection.getMax_id()); - if(type == DisplayNotificationsFragment.Type.FOLLOW){ - List accounts = parseAccountResponse(new JSONArray(response)); - if( accounts != null) - for(Account st: accounts ){ - Notification notification = new Notification(); - notification.setType(stringType); - notification.setId(st.getId()); - notification.setStatus(null); - notification.setAccount(account); - notifications.add(notification); - } - }else { - List statuses = parseStatuses(context, new JSONArray(response)); - if( statuses != null) - for(Status st: statuses ){ - Notification notification = new Notification(); - notification.setType(stringType); - notification.setId(st.getId()); - notification.setStatus(st); - notification.setAccount(st.getAccount()); - notifications.add(notification); - } - } + if (type == DisplayNotificationsFragment.Type.FOLLOW) { + List accounts = parseAccountResponse(new JSONArray(response)); + if (accounts != null) + for (Account st : accounts) { + Notification notification = new Notification(); + notification.setType(stringType); + notification.setId(st.getId()); + notification.setStatus(null); + notification.setAccount(account); + notifications.add(notification); + } + } else { + List statuses = parseStatuses(context, new JSONArray(response)); + if (statuses != null) + for (Status st : statuses) { + Notification notification = new Notification(); + notification.setType(stringType); + notification.setId(st.getId()); + notification.setStatus(st); + notification.setAccount(st.getAccount()); + notifications.add(notification); + } + } } catch (HttpsConnection.HttpsConnectionException e) { setError(e.getStatusCode(), e); @@ -1772,16 +1810,14 @@ public class GNUAPI { } - - - /** * Changes media description - * @param mediaId String - * @param description String + * + * @param mediaId String + * @param description String * @return Attachment */ - public Attachment updateDescription(String mediaId, String description){ + public Attachment updateDescription(String mediaId, String description) { HashMap params = new HashMap<>(); try { @@ -1811,21 +1847,22 @@ public class GNUAPI { /** * Retrieves Accounts and feeds when searching *synchronously* * - * @param query String search + * @param query String search * @return Results */ public APIResponse searchRemote(String instance, String query, String max_id) { HashMap params = new HashMap<>(); try { query = URLEncoder.encode(query, "UTF-8"); - } catch (UnsupportedEncodingException ignored) {} + } catch (UnsupportedEncodingException ignored) { + } if (max_id != null) params.put("max_id", max_id); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - String response = httpsConnection.get(getAbsoluteRemoteUrl(instance, "/statusnet/tags/timeline/"+query.trim().toLowerCase().replaceAll("\\#","")+".json"), 60, params, null); + String response = httpsConnection.get(getAbsoluteRemoteUrl(instance, "/statusnet/tags/timeline/" + query.trim().toLowerCase().replaceAll("\\#", "") + ".json"), 60, params, null); List statuses = parseStatuses(context, new JSONArray(response)); - if( statuses.size() > 0) { + if (statuses.size() > 0) { apiResponse.setSince_id(statuses.get(0).getId()); apiResponse.setMax_id(statuses.get(statuses.size() - 1).getId()); } @@ -1849,14 +1886,14 @@ public class GNUAPI { /** * Retrieves Accounts and feeds when searching *synchronously* * - * @param query String search + * @param query String search * @return Results */ public APIResponse search(String query) { Results results = new Results(); HashMap params = new HashMap<>(); apiResponse = new APIResponse(); - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) params.put("q", query); else try { @@ -1888,7 +1925,7 @@ public class GNUAPI { /** * Retrieves Accounts and feeds when searching *synchronously* * - * @param query String search + * @param query String search * @return Results */ public APIResponse search(String query, String max_id) { @@ -1896,14 +1933,15 @@ public class GNUAPI { HashMap params = new HashMap<>(); try { query = URLEncoder.encode(query, "UTF-8"); - } catch (UnsupportedEncodingException ignored) {} + } catch (UnsupportedEncodingException ignored) { + } if (max_id != null) params.put("max_id", max_id); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - String response = httpsConnection.get(getAbsoluteUrl("/statusnet/tags/timeline/"+query.trim().toLowerCase().replaceAll("\\#","")+".json"), 60, params, null); + String response = httpsConnection.get(getAbsoluteUrl("/statusnet/tags/timeline/" + query.trim().toLowerCase().replaceAll("\\#", "") + ".json"), 60, params, null); List statuses = parseStatuses(context, new JSONArray(response)); - if( statuses.size() > 0) { + if (statuses.size() > 0) { apiResponse.setSince_id(statuses.get(0).getId()); apiResponse.setMax_id(statuses.get(statuses.size() - 1).getId()); } @@ -1927,7 +1965,8 @@ public class GNUAPI { /** * Retrieves Accounts when searching (ie: via @...) *synchronously* * Not limited to following - * @param query String search + * + * @param query String search * @return APIResponse */ @SuppressWarnings("SameParameterValue") @@ -1937,20 +1976,21 @@ public class GNUAPI { /** * Retrieves Accounts when searching (ie: via @...) *synchronously* - * @param query String search - * @param count int limit - * @param following boolean following only + * + * @param query String search + * @param count int limit + * @param following boolean following only * @return APIResponse */ public APIResponse searchAccounts(String query, int count, boolean following) { HashMap params = new HashMap<>(); params.put("q", query); - if( count < 5) + if (count < 5) count = 5; - if( count > 40 ) + if (count > 40) count = 40; - if( following) + if (following) params.put("following", Boolean.toString(true)); params.put("limit", String.valueOf(count)); @@ -1977,21 +2017,18 @@ public class GNUAPI { } - - - - /** * Parse json response for several conversations + * * @param jsonArray JSONArray * @return List */ - private List parseConversations(JSONArray jsonArray){ + private List parseConversations(JSONArray jsonArray) { List conversations = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ){ + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Conversation conversation = parseConversation(context, resobj); @@ -2007,6 +2044,7 @@ public class GNUAPI { /** * Parse json response for unique conversation + * * @param resobj JSONObject * @return Conversation */ @@ -2018,23 +2056,24 @@ public class GNUAPI { conversation.setUnread(Boolean.parseBoolean(resobj.get("unread").toString())); conversation.setAccounts(parseAccountResponse(resobj.getJSONArray("accounts"))); conversation.setLast_status(parseStatuses(context, resobj.getJSONObject("last_status"))); - }catch (JSONException ignored) {} + } catch (JSONException ignored) { + } return conversation; } - /** * Parse json response for several status + * * @param jsonArray JSONArray * @return List */ - public static List parseStatuses(Context context, JSONArray jsonArray){ + public static List parseStatuses(Context context, JSONArray jsonArray) { List statuses = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ){ + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Status status = parseStatuses(context, resobj); @@ -2050,53 +2089,56 @@ public class GNUAPI { /** * Parse json response for unique status + * * @param resobj JSONObject * @return Status */ @SuppressWarnings("InfiniteRecursion") - private static Status parseStatuses(Context context, JSONObject resobj){ + private static Status parseStatuses(Context context, JSONObject resobj) { Status status = new Status(); try { status.setId(resobj.get("id").toString()); try { status.setUri(resobj.get("uri").toString()); - }catch (Exception ignored){ + } catch (Exception ignored) { status.setUri(resobj.get("id").toString()); } status.setCreated_at(Helper.mstStringToDate(context, resobj.get("created_at").toString())); - if( resobj.has("in_reply_to_status_id")) - status.setIn_reply_to_id(resobj.get("in_reply_to_status_id").toString()); - if( resobj.has("in_reply_to_user_id")) + if (resobj.has("in_reply_to_status_id")) + status.setIn_reply_to_id(resobj.get("in_reply_to_status_id").toString()); + if (resobj.has("in_reply_to_user_id")) status.setIn_reply_to_account_id(resobj.get("in_reply_to_user_id").toString()); status.setSensitive(false); status.setSpoiler_text(null); - if( !resobj.has("sender")) + if (!resobj.has("sender")) status.setVisibility("public"); else status.setVisibility("direct"); - if( resobj.has("geo")) - status.setLanguage(resobj.isNull("geo")?null:resobj.getString("geo")); - if( resobj.has("external_url")) + if (resobj.has("geo")) + status.setLanguage(resobj.isNull("geo") ? null : resobj.getString("geo")); + if (resobj.has("external_url")) status.setUrl(resobj.get("external_url").toString()); //Retrieves attachments try { JSONArray arrayAttachement = resobj.getJSONArray("attachments"); ArrayList attachments = new ArrayList<>(parseAttachmentResponse(arrayAttachement)); status.setMedia_attachments(attachments); - }catch (Exception ignored){ status.setMedia_attachments(new ArrayList<>());} + } catch (Exception ignored) { + status.setMedia_attachments(new ArrayList<>()); + } status.setCard(null); try { status.setConversationId(resobj.get("statusnet_conversation_id").toString()); - }catch (Exception ignored){ - if( resobj.has("friendica_parent_uri")) + } catch (Exception ignored) { + if (resobj.has("friendica_parent_uri")) status.setConversationId(resobj.get("friendica_parent_uri").toString()); else status.setConversationId(resobj.get("id").toString()); } //Retrieves mentions List mentions = new ArrayList<>(); - if( resobj.has("attentions")) { + if (resobj.has("attentions")) { JSONArray arrayMention = resobj.getJSONArray("attentions"); if (arrayMention != null) { for (int j = 0; j < arrayMention.length(); j++) { @@ -2110,7 +2152,7 @@ public class GNUAPI { } } status.setMentions(mentions); - }else{ + } else { status.setMentions(new ArrayList<>()); } @@ -2121,49 +2163,49 @@ public class GNUAPI { //Retrieve Application Application application = new Application(); try { - if(resobj.getJSONObject("source") != null){ + if (resobj.getJSONObject("source") != null) { application.setName(resobj.getJSONObject("source").toString()); application.setWebsite(resobj.getJSONObject("source_link").toString()); } - }catch (Exception e){ + } catch (Exception e) { application = new Application(); } status.setApplication(application); - if( resobj.has("user")) + if (resobj.has("user")) status.setAccount(parseAccountResponse(context, resobj.getJSONObject("user"))); - else if( resobj.has("sender")) + else if (resobj.has("sender")) status.setAccount(parseAccountResponse(context, resobj.getJSONObject("sender"))); - if( resobj.has("statusnet_html")) + if (resobj.has("statusnet_html")) status.setContent(resobj.get("statusnet_html").toString()); - else if( resobj.has("text")) + else if (resobj.has("text")) status.setContent(resobj.get("text").toString()); - if(resobj.has("fave_num")) + if (resobj.has("fave_num")) status.setFavourites_count(Integer.valueOf(resobj.get("fave_num").toString())); else status.setFavourites_count(0); - if(resobj.has("repeat_num")) + if (resobj.has("repeat_num")) status.setReblogs_count(Integer.valueOf(resobj.get("repeat_num").toString())); else status.setReblogs_count(0); status.setReplies_count(0); try { status.setReblogged(Boolean.valueOf(resobj.get("repeated").toString())); - }catch (Exception e){ + } catch (Exception e) { status.setReblogged(false); } try { status.setFavourited(Boolean.valueOf(resobj.get("favorited").toString())); - }catch (Exception e){ + } catch (Exception e) { status.setFavourited(false); } - if( resobj.has("friendica_activities") && resobj.getJSONObject("friendica_activities").has("like")){ + if (resobj.has("friendica_activities") && resobj.getJSONObject("friendica_activities").has("like")) { status.setFavourited(false); JSONArray jsonArray = resobj.getJSONObject("friendica_activities").getJSONArray("like"); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); for (int i = 0; i < jsonArray.length(); i++) { JSONObject like = jsonArray.getJSONObject(i); - if( like.getString("id").equals(userId)) { + if (like.getString("id").equals(userId)) { status.setFavourited(true); break; } @@ -2172,12 +2214,16 @@ public class GNUAPI { } status.setMuted(false); status.setPinned(false); - try{ + try { status.setReblog(parseStatuses(context, resobj.getJSONObject("retweeted_status"))); - }catch (Exception ignored){ status.setReblog(null);} - if( status.getContent().contains(status.getUri())) + } catch (Exception ignored) { + status.setReblog(null); + } + if (status.getContent().contains(status.getUri())) status.setNotice(true); - } catch (JSONException ignored) {ignored.printStackTrace();} catch (ParseException e) { + } catch (JSONException ignored) { + ignored.printStackTrace(); + } catch (ParseException e) { e.printStackTrace(); } @@ -2188,11 +2234,12 @@ public class GNUAPI { /** * Parse json response for unique schedule + * * @param resobj JSONObject * @return Status */ @SuppressWarnings("InfiniteRecursion") - private static Status parseSchedule(Context context, JSONObject resobj){ + private static Status parseSchedule(Context context, JSONObject resobj) { Status status = new Status(); try { status.setIn_reply_to_id(resobj.get("in_reply_to_id").toString()); @@ -2200,26 +2247,28 @@ public class GNUAPI { status.setSpoiler_text(resobj.get("spoiler_text").toString()); try { status.setVisibility(resobj.get("visibility").toString()); - }catch (Exception e){status.setVisibility("public");} + } catch (Exception e) { + status.setVisibility("public"); + } status.setContent(resobj.get("text").toString()); - } catch (JSONException ignored) {} + } catch (JSONException ignored) { + } return status; } - - /** * Parse json response for list of accounts + * * @param jsonArray JSONArray * @return List */ - private List parseAccountResponse(JSONArray jsonArray){ + private List parseAccountResponse(JSONArray jsonArray) { List accounts = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ) { + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Account account = parseAccountResponse(context, resobj); accounts.add(account); @@ -2233,16 +2282,17 @@ public class GNUAPI { /** * Parse json response an unique account + * * @param resobj JSONObject * @return Account */ @SuppressWarnings("InfiniteRecursion") - public static Account parseAccountResponse(Context context, JSONObject resobj){ + public static Account parseAccountResponse(Context context, JSONObject resobj) { Account account = new Account(); try { account.setId(resobj.get("id").toString()); - if( resobj.has("ostatus_uri")) + if (resobj.has("ostatus_uri")) account.setUuid(resobj.get("ostatus_uri").toString()); else account.setUuid(resobj.get("id").toString()); @@ -2260,20 +2310,21 @@ public class GNUAPI { account.setUrl(resobj.get("url").toString()); account.setAvatar(resobj.get("profile_image_url_https").toString()); account.setAvatar_static(resobj.get("profile_image_url_https").toString()); - if( !resobj.isNull("background_image")) { + if (!resobj.isNull("background_image")) { account.setHeader(resobj.get("background_image").toString()); account.setHeader_static(resobj.get("background_image").toString()); - }else{ + } else { account.setHeader("null"); account.setHeader_static("null"); } - if( resobj.has("cid")) + if (resobj.has("cid")) account.setSocial("FRIENDICA"); else account.setSocial("GNU"); account.setEmojis(new ArrayList<>()); - } catch (JSONException ignored) {} catch (ParseException e) { + } catch (JSONException ignored) { + } catch (ParseException e) { e.printStackTrace(); } return account; @@ -2282,10 +2333,11 @@ public class GNUAPI { /** * Parse json response an unique relationship + * * @param resobjIni JSONObject * @return Relationship */ - private Relationship parseRelationshipResponse(JSONObject resobjIni){ + private Relationship parseRelationshipResponse(JSONObject resobjIni) { Relationship relationship = new Relationship(); @@ -2297,12 +2349,12 @@ public class GNUAPI { relationship.setBlocking(Boolean.valueOf(resobj.get("blocking").toString())); try { relationship.setMuting(Boolean.valueOf(resobj.get("muting").toString())); - }catch (Exception ignored){ - relationship.setMuting(false); - } + } catch (Exception ignored) { + relationship.setMuting(false); + } try { relationship.setMuting_notifications(!Boolean.valueOf(resobj.get("notifications_enabled").toString())); - }catch (Exception ignored){ + } catch (Exception ignored) { relationship.setMuting_notifications(false); } relationship.setEndorsed(false); @@ -2317,15 +2369,16 @@ public class GNUAPI { /** * Parse json response for list of relationship + * * @param jsonArray JSONArray * @return List */ - private List parseRelationshipResponse(JSONArray jsonArray){ + private List parseRelationshipResponse(JSONArray jsonArray) { List relationships = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ) { + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Relationship relationship = parseRelationshipResponse(resobj); relationships.add(relationship); @@ -2339,10 +2392,11 @@ public class GNUAPI { /** * Parse json response for the context + * * @param jsonObject JSONObject * @return Context */ - private app.fedilab.android.client.Entities.Context parseContext(JSONObject jsonObject){ + private app.fedilab.android.client.Entities.Context parseContext(JSONObject jsonObject) { app.fedilab.android.client.Entities.Context context = new app.fedilab.android.client.Entities.Context(); try { @@ -2355,126 +2409,144 @@ public class GNUAPI { } - /** * Parse json response for list of relationship + * * @param jsonArray JSONArray * @return List */ - private static List parseAttachmentResponse(JSONArray jsonArray){ + private static List parseAttachmentResponse(JSONArray jsonArray) { List attachments = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ) { + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Attachment attachment = parseAttachmentResponse(resobj); attachments.add(attachment); i++; } - } catch (JSONException ignored) { } + } catch (JSONException ignored) { + } return attachments; } + /** * Parse json response an unique attachment + * * @param resobj JSONObject * @return Relationship */ - static Attachment parseAttachmentResponse(JSONObject resobj){ + static Attachment parseAttachmentResponse(JSONObject resobj) { Attachment attachment = new Attachment(); try { - if(resobj.has("id") ) + if (resobj.has("id")) attachment.setId(resobj.get("id").toString()); - if( resobj.has("url") ){ + if (resobj.has("url")) { attachment.setUrl(resobj.getString("url")); attachment.setPreview_url(resobj.getString("url")); attachment.setRemote_url(resobj.getString("url")); } - if( attachment.getUrl().endsWith("png") || attachment.getUrl().endsWith("jpg") || attachment.getUrl().endsWith("jpeg")){ + if (attachment.getUrl().endsWith("png") || attachment.getUrl().endsWith("jpg") || attachment.getUrl().endsWith("jpeg")) { attachment.setType("image"); - }else if( attachment.getUrl().endsWith("gif") || attachment.getUrl().endsWith("apng") ){ + } else if (attachment.getUrl().endsWith("gif") || attachment.getUrl().endsWith("apng")) { attachment.setType("gifv"); - }else if( attachment.getUrl().endsWith("mp4") ){ + } else if (attachment.getUrl().endsWith("mp4")) { attachment.setType("video"); - }else{ + } else { attachment.setType("web"); } try { attachment.setDescription(resobj.get("description").toString()); - }catch (JSONException ignore){} - try{ + } catch (JSONException ignore) { + } + try { attachment.setRemote_url(resobj.get("url").toString()); - }catch (JSONException ignore){} - try{ + } catch (JSONException ignore) { + } + try { attachment.setPreview_url(resobj.get("thumb_url").toString()); - }catch (JSONException ignore){} - try{ + } catch (JSONException ignore) { + } + try { attachment.setMeta(resobj.get("meta").toString()); - }catch (JSONException ignore){} - try{ + } catch (JSONException ignore) { + } + try { attachment.setText_url(resobj.get("text_url").toString()); - }catch (JSONException ignore){} + } catch (JSONException ignore) { + } - } catch (JSONException ignored) {} + } catch (JSONException ignored) { + } return attachment; } /** * Parse json response an unique attachment + * * @param resobj JSONObject * @return Relationship */ - public static Attachment parseUploadedAttachmentResponse(JSONObject resobj){ + public static Attachment parseUploadedAttachmentResponse(JSONObject resobj) { Attachment attachment = new Attachment(); try { - if(resobj.has("media_id") ) + if (resobj.has("media_id")) attachment.setId(resobj.get("media_id").toString()); - if( resobj.has("image") && resobj.getJSONObject("image").has("image_type")) + if (resobj.has("image") && resobj.getJSONObject("image").has("image_type")) attachment.setType("Image"); - else if(resobj.has("image") && resobj.getJSONObject("gif").has("image_type")) + else if (resobj.has("image") && resobj.getJSONObject("gif").has("image_type")) attachment.setType("GifV"); else attachment.setType("video"); - try{ + try { attachment.setRemote_url(resobj.get("url").toString()); - }catch (JSONException ignore){} - try{ + } catch (JSONException ignore) { + } + try { attachment.setPreview_url(resobj.get("thumb_url").toString()); - }catch (JSONException ignore){} + } catch (JSONException ignore) { + } - if( resobj.has("image") && resobj.getJSONObject("image").has("friendica_preview_url")){ + if (resobj.has("image") && resobj.getJSONObject("image").has("friendica_preview_url")) { attachment.setUrl(resobj.getJSONObject("image").getString("friendica_preview_url")); attachment.setPreview_url(resobj.getJSONObject("image").getString("friendica_preview_url")); attachment.setRemote_url(resobj.getJSONObject("image").getString("friendica_preview_url")); } - if( resobj.has("media_url")) + if (resobj.has("media_url")) attachment.setUrl(resobj.get("media_url").toString()); try { attachment.setDescription(resobj.get("description").toString()); - }catch (JSONException ignore){} + } catch (JSONException ignore) { + } - try{ + try { attachment.setMeta(resobj.get("meta").toString()); - }catch (JSONException ignore){} - try{ + } catch (JSONException ignore) { + } + try { attachment.setText_url(resobj.get("text_url").toString()); - }catch (JSONException ignore){} + } catch (JSONException ignore) { + } - } catch (JSONException ignored) {ignored.printStackTrace();} + } catch (JSONException ignored) { + ignored.printStackTrace(); + } return attachment; } /** * Parse json response an unique notification + * * @param resobj JSONObject * @return Account */ - private Notification parseNotificationResponse(Context context, JSONObject resobj){ + private Notification parseNotificationResponse(Context context, JSONObject resobj) { Notification notification = new Notification(); try { @@ -2482,11 +2554,13 @@ public class GNUAPI { notification.setType(resobj.get("ntype").toString()); notification.setCreated_at(Helper.mstStringToDate(context, resobj.get("created_at").toString())); notification.setAccount(parseAccountResponse(context, resobj.getJSONObject("from_profile"))); - try{ + try { notification.setStatus(parseStatuses(context, resobj.getJSONObject("notice"))); - }catch (Exception ignored){} + } catch (Exception ignored) { + } notification.setCreated_at(Helper.mstStringToDate(context, resobj.get("created_at").toString())); - } catch (JSONException ignored) {} catch (ParseException e) { + } catch (JSONException ignored) { + } catch (ParseException e) { e.printStackTrace(); } return notification; @@ -2494,15 +2568,16 @@ public class GNUAPI { /** * Parse json response for list of notifications + * * @param jsonArray JSONArray * @return List */ - private List parseNotificationResponse(JSONArray jsonArray){ + private List parseNotificationResponse(JSONArray jsonArray) { List notifications = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ) { + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Notification notification = parseNotificationResponse(context, resobj); @@ -2516,13 +2591,13 @@ public class GNUAPI { } - /** * Set the error message + * * @param statusCode int code - * @param error Throwable error + * @param error Throwable error */ - private void setError(int statusCode, Throwable error){ + private void setError(int statusCode, Throwable error) { APIError = new Error(); APIError.setStatusCode(statusCode); String message = statusCode + " - " + error.getMessage(); @@ -2531,7 +2606,7 @@ public class GNUAPI { String errorM = jsonObject.get("error").toString(); message = "Error " + statusCode + " : " + errorM; } catch (JSONException e) { - if(error.getMessage().split(".").length > 0) { + if (error.getMessage().split(".").length > 0) { String errorM = error.getMessage().split(".")[0]; message = "Error " + statusCode + " : " + errorM; } @@ -2540,11 +2615,11 @@ public class GNUAPI { apiResponse.setError(APIError); } - private void setDefaultError(Exception e){ + private void setDefaultError(Exception e) { APIError = new Error(); - if( e.getLocalizedMessage() != null && e.getLocalizedMessage().trim().length() > 0) + if (e.getLocalizedMessage() != null && e.getLocalizedMessage().trim().length() > 0) APIError.setError(e.getLocalizedMessage()); - else if( e.getMessage() != null && e.getMessage().trim().length() > 0) + else if (e.getMessage() != null && e.getMessage().trim().length() > 0) APIError.setError(e.getMessage()); else APIError.setError(context.getString(R.string.toast_error)); @@ -2552,7 +2627,7 @@ public class GNUAPI { } - public Error getError(){ + public Error getError() { return APIError; } @@ -2560,8 +2635,9 @@ public class GNUAPI { private String getAbsoluteUrl(String action) { return Helper.instanceWithProtocol(this.context, this.instance) + "/api" + action; } + private String getAbsoluteRemoteUrl(String instance, String action) { - return Helper.instanceWithProtocol(this.context,instance) + "/api" + action; + return Helper.instanceWithProtocol(this.context, instance) + "/api" + action; } } diff --git a/app/src/main/java/app/fedilab/android/client/Glide/CustomStreamFetcher.java b/app/src/main/java/app/fedilab/android/client/Glide/CustomStreamFetcher.java index 33a6ed4de..31dd98896 100644 --- a/app/src/main/java/app/fedilab/android/client/Glide/CustomStreamFetcher.java +++ b/app/src/main/java/app/fedilab/android/client/Glide/CustomStreamFetcher.java @@ -1,6 +1,7 @@ package app.fedilab.android.client.Glide; import android.content.Context; + import androidx.annotation.NonNull; import com.bumptech.glide.Priority; diff --git a/app/src/main/java/app/fedilab/android/client/Glide/HttpsUrlLoader.java b/app/src/main/java/app/fedilab/android/client/Glide/HttpsUrlLoader.java index c1a6908e6..f4b2f7252 100644 --- a/app/src/main/java/app/fedilab/android/client/Glide/HttpsUrlLoader.java +++ b/app/src/main/java/app/fedilab/android/client/Glide/HttpsUrlLoader.java @@ -1,6 +1,7 @@ package app.fedilab.android.client.Glide; import android.content.Context; + import androidx.annotation.NonNull; import androidx.annotation.Nullable; @@ -14,7 +15,6 @@ import java.io.InputStream; import java.lang.ref.WeakReference; - /** * Created by Thomas on 13/12/2017. * Custom UrlLoader @@ -25,7 +25,8 @@ public class HttpsUrlLoader implements ModelLoader { private static WeakReference contextWeakReference; HttpsUrlLoader(Context context) { - contextWeakReference = new WeakReference<>(context);} + contextWeakReference = new WeakReference<>(context); + } @Nullable @Override @@ -41,14 +42,16 @@ public class HttpsUrlLoader implements ModelLoader { public static class Factory implements ModelLoaderFactory { - Factory(Context context){ + Factory(Context context) { contextWeakReference = new WeakReference<>(context); } + @NonNull @Override public ModelLoader build(@NonNull MultiModelLoaderFactory multiFactory) { return new HttpsUrlLoader(contextWeakReference.get()); } + @Override public void teardown() { diff --git a/app/src/main/java/app/fedilab/android/client/Glide/TLSLibraryGlideModule.java b/app/src/main/java/app/fedilab/android/client/Glide/TLSLibraryGlideModule.java index a0d3a0035..42fa91051 100644 --- a/app/src/main/java/app/fedilab/android/client/Glide/TLSLibraryGlideModule.java +++ b/app/src/main/java/app/fedilab/android/client/Glide/TLSLibraryGlideModule.java @@ -1,6 +1,7 @@ package app.fedilab.android.client.Glide; import android.content.Context; + import androidx.annotation.NonNull; import com.bumptech.glide.Glide; diff --git a/app/src/main/java/app/fedilab/android/client/HttpsConnection.java b/app/src/main/java/app/fedilab/android/client/HttpsConnection.java index 7c6af2a4c..f43cc3625 100644 --- a/app/src/main/java/app/fedilab/android/client/HttpsConnection.java +++ b/app/src/main/java/app/fedilab/android/client/HttpsConnection.java @@ -94,7 +94,6 @@ import app.fedilab.android.sqlite.Sqlite; public class HttpsConnection { - private HttpsURLConnection httpsURLConnection; private HttpURLConnection httpURLConnection; private String since_id, max_id; @@ -104,24 +103,24 @@ public class HttpsConnection { private Proxy proxy; private String instance; - public HttpsConnection(Context context, String instance){ - this.instance = instance; + public HttpsConnection(Context context, String instance) { + this.instance = instance; this.context = context; sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); boolean proxyEnabled = sharedpreferences.getBoolean(Helper.SET_PROXY_ENABLED, false); int type = sharedpreferences.getInt(Helper.SET_PROXY_TYPE, 0); proxy = null; - if( proxyEnabled ){ + if (proxyEnabled) { try { String host = sharedpreferences.getString(Helper.SET_PROXY_HOST, "127.0.0.1"); int port = sharedpreferences.getInt(Helper.SET_PROXY_PORT, 8118); - if( type == 0 ) + if (type == 0) proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); else proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(host, port)); final String login = sharedpreferences.getString(Helper.SET_PROXY_LOGIN, null); final String pwd = sharedpreferences.getString(Helper.SET_PROXY_PASSWORD, null); - if( login != null) { + if (login != null) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { assert pwd != null; @@ -131,13 +130,13 @@ public class HttpsConnection { }; Authenticator.setDefault(authenticator); } - }catch (Exception e){ + } catch (Exception e) { proxy = null; } } - if( instance != null && instance.endsWith(".onion")) { + if (instance != null && instance.endsWith(".onion")) { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @SuppressLint("BadHostnameVerifier") @Override @@ -153,7 +152,7 @@ public class HttpsConnection { public String get(String urlConnection, int timeout, HashMap paramaters, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException { - if( urlConnection.startsWith("https://")) { + if (urlConnection.startsWith("https://")) { Map params = new LinkedHashMap<>(); if (paramaters != null) { Iterator it = paramaters.entrySet().iterator(); @@ -183,7 +182,7 @@ public class HttpsConnection { httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory(this.instance)); if (token != null && !token.startsWith("Basic ")) httpsURLConnection.setRequestProperty("Authorization", "Bearer " + token); - else if( token != null && token.startsWith("Basic ")) + else if (token != null && token.startsWith("Basic ")) httpsURLConnection.setRequestProperty("Authorization", token); httpsURLConnection.setRequestMethod("GET"); String response; @@ -191,30 +190,33 @@ public class HttpsConnection { response = converToString(httpsURLConnection.getInputStream()); } else { String error = null; - if( httpsURLConnection.getErrorStream() != null) { + if (httpsURLConnection.getErrorStream() != null) { InputStream stream = httpsURLConnection.getErrorStream(); if (stream == null) { stream = httpsURLConnection.getInputStream(); } try (Scanner scanner = new Scanner(stream)) { scanner.useDelimiter("\\Z"); - if( scanner.hasNext()) { + if (scanner.hasNext()) { error = scanner.next(); } - }catch (Exception e){e.printStackTrace();} + } catch (Exception e) { + e.printStackTrace(); + } } int responseCode = httpsURLConnection.getResponseCode(); try { httpsURLConnection.getInputStream().close(); - }catch (Exception ignored){} + } catch (Exception ignored) { + } throw new HttpsConnectionException(responseCode, error); } getSinceMaxId(); httpsURLConnection.getInputStream().close(); return response; - }else { - Map params = new LinkedHashMap<>(); - if( paramaters != null) { + } else { + Map params = new LinkedHashMap<>(); + if (paramaters != null) { Iterator it = paramaters.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); @@ -223,46 +225,49 @@ public class HttpsConnection { } } StringBuilder postData = new StringBuilder(); - for (Map.Entry param : params.entrySet()) { + for (Map.Entry param : params.entrySet()) { if (postData.length() != 0) postData.append('&'); postData.append(param.getKey()); postData.append('='); postData.append(String.valueOf(param.getValue())); } URL url = new URL(urlConnection + "?" + postData); - if( proxy !=null ) - httpURLConnection = (HttpURLConnection)url.openConnection(proxy); + if (proxy != null) + httpURLConnection = (HttpURLConnection) url.openConnection(proxy); else - httpURLConnection = (HttpURLConnection)url.openConnection(); + httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setConnectTimeout(timeout * 1000); httpURLConnection.setRequestProperty("http.keepAlive", "false"); httpURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT); if (token != null && !token.startsWith("Basic ")) httpsURLConnection.setRequestProperty("Authorization", "Bearer " + token); - else if( token != null && token.startsWith("Basic ")) + else if (token != null && token.startsWith("Basic ")) httpsURLConnection.setRequestProperty("Authorization", token); httpURLConnection.setRequestMethod("GET"); String response; if (httpURLConnection.getResponseCode() >= 200 && httpURLConnection.getResponseCode() < 400) { response = converToString(httpURLConnection.getInputStream()); - }else { + } else { String error = null; - if( httpURLConnection.getErrorStream() != null) { + if (httpURLConnection.getErrorStream() != null) { InputStream stream = httpURLConnection.getErrorStream(); if (stream == null) { stream = httpURLConnection.getInputStream(); } try (Scanner scanner = new Scanner(stream)) { scanner.useDelimiter("\\Z"); - if( scanner.hasNext()) { + if (scanner.hasNext()) { error = scanner.next(); } - }catch (Exception e){e.printStackTrace();} + } catch (Exception e) { + e.printStackTrace(); + } } int responseCode = httpURLConnection.getResponseCode(); try { httpURLConnection.getInputStream().close(); - }catch (Exception ignored){} + } catch (Exception ignored) { + } throw new HttpsConnectionException(responseCode, error); } getSinceMaxId(); @@ -272,14 +277,13 @@ public class HttpsConnection { } - public String get(String urlConnection) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException { - if( urlConnection.startsWith("https://")) { + if (urlConnection.startsWith("https://")) { URL url = new URL(urlConnection); - if( proxy !=null ) - httpsURLConnection = (HttpsURLConnection)url.openConnection(proxy); + if (proxy != null) + httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy); else - httpsURLConnection = (HttpsURLConnection)url.openConnection(); + httpsURLConnection = (HttpsURLConnection) url.openConnection(); httpsURLConnection.setConnectTimeout(30 * 1000); httpsURLConnection.setRequestProperty("http.keepAlive", "false"); httpsURLConnection.setRequestProperty("Content-Type", "application/json"); @@ -291,35 +295,38 @@ public class HttpsConnection { if (httpsURLConnection.getResponseCode() >= 200 && httpsURLConnection.getResponseCode() < 400) { getSinceMaxId(); response = converToString(httpsURLConnection.getInputStream()); - }else { + } else { String error = null; - if( httpsURLConnection.getErrorStream() != null) { + if (httpsURLConnection.getErrorStream() != null) { InputStream stream = httpsURLConnection.getErrorStream(); if (stream == null) { stream = httpsURLConnection.getInputStream(); } try (Scanner scanner = new Scanner(stream)) { scanner.useDelimiter("\\Z"); - if( scanner.hasNext()) { + if (scanner.hasNext()) { error = scanner.next(); } - }catch (Exception e){e.printStackTrace();} + } catch (Exception e) { + e.printStackTrace(); + } } int responseCode = httpsURLConnection.getResponseCode(); try { httpsURLConnection.getInputStream().close(); - }catch (Exception ignored){} + } catch (Exception ignored) { + } throw new HttpsConnectionException(responseCode, error); } getSinceMaxId(); httpsURLConnection.getInputStream().close(); return response; - }else{ + } else { URL url = new URL(urlConnection); - if( proxy !=null ) - httpURLConnection = (HttpURLConnection)url.openConnection(proxy); + if (proxy != null) + httpURLConnection = (HttpURLConnection) url.openConnection(proxy); else - httpURLConnection = (HttpURLConnection)url.openConnection(); + httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setConnectTimeout(30 * 1000); httpURLConnection.setRequestProperty("http.keepAlive", "false"); httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36"); @@ -328,24 +335,27 @@ public class HttpsConnection { if (httpURLConnection.getResponseCode() >= 200 && httpURLConnection.getResponseCode() < 400) { getSinceMaxId(); response = converToString(httpURLConnection.getInputStream()); - }else { + } else { String error = null; - if( httpURLConnection.getErrorStream() != null) { + if (httpURLConnection.getErrorStream() != null) { InputStream stream = httpURLConnection.getErrorStream(); if (stream == null) { stream = httpURLConnection.getInputStream(); } try (Scanner scanner = new Scanner(stream)) { scanner.useDelimiter("\\Z"); - if( scanner.hasNext()) { + if (scanner.hasNext()) { error = scanner.next(); } - }catch (Exception e){e.printStackTrace();} + } catch (Exception e) { + e.printStackTrace(); + } } int responseCode = httpURLConnection.getResponseCode(); try { httpURLConnection.getInputStream().close(); - }catch (Exception ignored){} + } catch (Exception ignored) { + } throw new HttpsConnectionException(responseCode, error); } getSinceMaxId(); @@ -355,9 +365,8 @@ public class HttpsConnection { } - public String post(String urlConnection, int timeout, HashMap paramaters, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException { - if( urlConnection.startsWith("https://")) { + if (urlConnection.startsWith("https://")) { URL url = new URL(urlConnection); Map params = new LinkedHashMap<>(); if (paramaters != null) { @@ -387,7 +396,7 @@ public class HttpsConnection { httpsURLConnection.setRequestMethod("POST"); if (token != null && !token.startsWith("Basic ")) httpsURLConnection.setRequestProperty("Authorization", "Bearer " + token); - else if( token != null && token.startsWith("Basic ")) + else if (token != null && token.startsWith("Basic ")) httpsURLConnection.setRequestProperty("Authorization", token); httpsURLConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); @@ -399,28 +408,31 @@ public class HttpsConnection { response = converToString(httpsURLConnection.getInputStream()); } else { String error = null; - if( httpsURLConnection.getErrorStream() != null) { + if (httpsURLConnection.getErrorStream() != null) { InputStream stream = httpsURLConnection.getErrorStream(); if (stream == null) { stream = httpsURLConnection.getInputStream(); } try (Scanner scanner = new Scanner(stream)) { scanner.useDelimiter("\\Z"); - if( scanner.hasNext()) { + if (scanner.hasNext()) { error = scanner.next(); } - }catch (Exception e){e.printStackTrace();} + } catch (Exception e) { + e.printStackTrace(); + } } int responseCode = httpsURLConnection.getResponseCode(); try { httpsURLConnection.getInputStream().close(); - }catch (Exception ignored){} + } catch (Exception ignored) { + } throw new HttpsConnectionException(responseCode, error); } getSinceMaxId(); httpsURLConnection.getInputStream().close(); return response; - }else { + } else { URL url = new URL(urlConnection); Map params = new LinkedHashMap<>(); if (paramaters != null) { @@ -450,7 +462,7 @@ public class HttpsConnection { httpURLConnection.setRequestMethod("POST"); if (token != null && !token.startsWith("Basic ")) httpURLConnection.setRequestProperty("Authorization", "Bearer " + token); - else if( token != null && token.startsWith("Basic ")) + else if (token != null && token.startsWith("Basic ")) httpURLConnection.setRequestProperty("Authorization", token); httpURLConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); @@ -461,22 +473,25 @@ public class HttpsConnection { response = converToString(httpURLConnection.getInputStream()); } else { String error = null; - if( httpURLConnection.getErrorStream() != null) { + if (httpURLConnection.getErrorStream() != null) { InputStream stream = httpURLConnection.getErrorStream(); if (stream == null) { stream = httpURLConnection.getInputStream(); } try (Scanner scanner = new Scanner(stream)) { scanner.useDelimiter("\\Z"); - if( scanner.hasNext()) { + if (scanner.hasNext()) { error = scanner.next(); } - }catch (Exception e){e.printStackTrace();} + } catch (Exception e) { + e.printStackTrace(); + } } int responseCode = httpURLConnection.getResponseCode(); try { httpURLConnection.getInputStream().close(); - }catch (Exception ignored){} + } catch (Exception ignored) { + } throw new HttpsConnectionException(responseCode, error); } getSinceMaxId(); @@ -488,7 +503,7 @@ public class HttpsConnection { public String postJson(String urlConnection, int timeout, JsonObject jsonObject, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException { - if( urlConnection.startsWith("https://")) { + if (urlConnection.startsWith("https://")) { URL url = new URL(urlConnection); byte[] postDataBytes = new byte[0]; postDataBytes = jsonObject.toString().getBytes("UTF-8"); @@ -505,7 +520,7 @@ public class HttpsConnection { httpsURLConnection.setRequestMethod("POST"); if (token != null && !token.startsWith("Basic ")) httpsURLConnection.setRequestProperty("Authorization", "Bearer " + token); - else if( token != null && token.startsWith("Basic ")) + else if (token != null && token.startsWith("Basic ")) httpsURLConnection.setRequestProperty("Authorization", token); httpsURLConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); @@ -517,28 +532,31 @@ public class HttpsConnection { response = converToString(httpsURLConnection.getInputStream()); } else { String error = null; - if( httpsURLConnection.getErrorStream() != null) { + if (httpsURLConnection.getErrorStream() != null) { InputStream stream = httpsURLConnection.getErrorStream(); if (stream == null) { stream = httpsURLConnection.getInputStream(); } try (Scanner scanner = new Scanner(stream)) { scanner.useDelimiter("\\Z"); - if( scanner.hasNext()) { + if (scanner.hasNext()) { error = scanner.next(); } - }catch (Exception e){e.printStackTrace();} + } catch (Exception e) { + e.printStackTrace(); + } } int responseCode = httpsURLConnection.getResponseCode(); try { httpsURLConnection.getInputStream().close(); - }catch (Exception ignored){} + } catch (Exception ignored) { + } throw new HttpsConnectionException(responseCode, error); } getSinceMaxId(); httpsURLConnection.getInputStream().close(); return response; - }else { + } else { URL url = new URL(urlConnection); byte[] postDataBytes = jsonObject.toString().getBytes("UTF-8"); @@ -552,7 +570,7 @@ public class HttpsConnection { httpURLConnection.setRequestMethod("POST"); if (token != null && !token.startsWith("Basic ")) httpURLConnection.setRequestProperty("Authorization", "Bearer " + token); - else if( token != null && token.startsWith("Basic ")) + else if (token != null && token.startsWith("Basic ")) httpURLConnection.setRequestProperty("Authorization", token); httpURLConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); @@ -563,22 +581,25 @@ public class HttpsConnection { response = converToString(httpURLConnection.getInputStream()); } else { String error = null; - if( httpURLConnection.getErrorStream() != null) { + if (httpURLConnection.getErrorStream() != null) { InputStream stream = httpURLConnection.getErrorStream(); if (stream == null) { stream = httpURLConnection.getInputStream(); } try (Scanner scanner = new Scanner(stream)) { scanner.useDelimiter("\\Z"); - if( scanner.hasNext()) { + if (scanner.hasNext()) { error = scanner.next(); } - }catch (Exception e){e.printStackTrace();} + } catch (Exception e) { + e.printStackTrace(); + } } int responseCode = httpURLConnection.getResponseCode(); try { httpURLConnection.getInputStream().close(); - }catch (Exception ignored){} + } catch (Exception ignored) { + } throw new HttpsConnectionException(responseCode, error); } getSinceMaxId(); @@ -603,7 +624,7 @@ public class HttpsConnection { httpsURLConnection.setRequestMethod("POST"); if (token != null && !token.startsWith("Basic ")) httpsURLConnection.setRequestProperty("Authorization", "Bearer " + token); - else if( token != null && token.startsWith("Basic ")) + else if (token != null && token.startsWith("Basic ")) httpsURLConnection.setRequestProperty("Authorization", token); httpsURLConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); @@ -615,22 +636,25 @@ public class HttpsConnection { response = converToString(httpsURLConnection.getInputStream()); } else { String error = null; - if( httpsURLConnection.getErrorStream() != null) { + if (httpsURLConnection.getErrorStream() != null) { InputStream stream = httpsURLConnection.getErrorStream(); if (stream == null) { stream = httpsURLConnection.getInputStream(); } try (Scanner scanner = new Scanner(stream)) { scanner.useDelimiter("\\Z"); - if( scanner.hasNext()) { + if (scanner.hasNext()) { error = scanner.next(); } - }catch (Exception e){e.printStackTrace();} + } catch (Exception e) { + e.printStackTrace(); + } } int responseCode = httpsURLConnection.getResponseCode(); try { httpsURLConnection.getInputStream().close(); - }catch (Exception ignored){} + } catch (Exception ignored) { + } throw new HttpsConnectionException(responseCode, error); } getSinceMaxId(); @@ -654,10 +678,10 @@ public class HttpsConnection { if (downloadUrl.startsWith("https://")) { try { url = new URL(downloadUrl); - if( proxy !=null ) - httpsURLConnection = (HttpsURLConnection)url.openConnection(proxy); + if (proxy != null) + httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy); else - httpsURLConnection = (HttpsURLConnection)url.openConnection(); + httpsURLConnection = (HttpsURLConnection) url.openConnection(); httpsURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT); int responseCode = httpsURLConnection.getResponseCode(); @@ -698,7 +722,7 @@ public class HttpsConnection { final int currentProgress = (downloadedFileSize * 100) / contentSize; ((MediaActivity) context).runOnUiThread(new Runnable() { public void run() { - listener.onUpdateProgress(currentProgress>0?currentProgress:101); + listener.onUpdateProgress(currentProgress > 0 ? currentProgress : 101); } }); } @@ -742,10 +766,10 @@ public class HttpsConnection { } else { try { url = new URL(downloadUrl); - if( proxy !=null ) - httpURLConnection = (HttpURLConnection)url.openConnection(proxy); + if (proxy != null) + httpURLConnection = (HttpURLConnection) url.openConnection(proxy); else - httpURLConnection = (HttpURLConnection)url.openConnection(); + httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT); int responseCode = httpURLConnection.getResponseCode(); @@ -786,7 +810,7 @@ public class HttpsConnection { final int currentProgress = (downloadedFileSize * 100) / contentSize; ((MediaActivity) context).runOnUiThread(new Runnable() { public void run() { - listener.onUpdateProgress(currentProgress>0?currentProgress:101); + listener.onUpdateProgress(currentProgress > 0 ? currentProgress : 101); } }); } @@ -833,9 +857,8 @@ public class HttpsConnection { } - public InputStream getPicture(final String downloadUrl) { - if( downloadUrl.startsWith("https://")) { + if (downloadUrl.startsWith("https://")) { try { URL url = new URL(downloadUrl); if (proxy != null) @@ -856,9 +879,10 @@ public class HttpsConnection { if (httpsURLConnection != null) try { httpsURLConnection.getInputStream().close(); - } catch (Exception ignored) { } + } catch (Exception ignored) { + } return null; - }else { + } else { try { URL url = new URL(downloadUrl); if (proxy != null) @@ -878,26 +902,27 @@ public class HttpsConnection { if (httpURLConnection != null) try { httpURLConnection.getInputStream().close(); - } catch (Exception ignored) { } + } catch (Exception ignored) { + } return null; } } - enum imageType{ + enum imageType { AVATAR, BANNER } - private void uploadMedia(String urlConnection, InputStream avatar, InputStream header, String filename){ + private void uploadMedia(String urlConnection, InputStream avatar, InputStream header, String filename) { UploadNotificationConfig uploadConfig = new UploadNotificationConfig(); uploadConfig.getCompleted().autoClear = true; File file = new File(context.getCacheDir() + "/" + filename); OutputStream outputStream; try { outputStream = new FileOutputStream(file); - if( avatar != null) { + if (avatar != null) { IOUtils.copy(avatar, outputStream); - }else{ + } else { IOUtils.copy(header, outputStream); } } catch (FileNotFoundException e) { @@ -910,12 +935,12 @@ public class HttpsConnection { String token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); MultipartUploadRequest m = new MultipartUploadRequest(context, urlConnection) .setMethod("PATCH"); - if( avatar != null) { - m.addFileToUpload(file.getPath(), "avatar"); - }else{ - m.addFileToUpload(file.getPath(), "header"); - } - m.addParameter("name", filename) + if (avatar != null) { + m.addFileToUpload(file.getPath(), "avatar"); + } else { + m.addFileToUpload(file.getPath(), "header"); + } + m.addParameter("name", filename) .addHeader("Authorization", "Bearer " + token) .setNotificationConfig(uploadConfig) .setDelegate(new UploadStatusDelegate() { @@ -950,10 +975,9 @@ public class HttpsConnection { } - - @SuppressWarnings("SameParameterValue") - public String patch(String urlConnection, int timeout, HashMap paramaters, InputStream avatar, String avatarName, InputStream header, String headerName, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException { - if( urlConnection.startsWith("https://")) { + @SuppressWarnings("SameParameterValue") + public String patch(String urlConnection, int timeout, HashMap paramaters, InputStream avatar, String avatarName, InputStream header, String headerName, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException { + if (urlConnection.startsWith("https://")) { URL url = new URL(urlConnection); Map params = new LinkedHashMap<>(); if (paramaters != null) { @@ -974,7 +998,6 @@ public class HttpsConnection { byte[] postDataBytes = (postData.toString()).getBytes("UTF-8"); - if (proxy != null) httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy); else @@ -982,15 +1005,15 @@ public class HttpsConnection { httpsURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT); httpsURLConnection.setConnectTimeout(timeout * 1000); httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory(this.instance)); - if( Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT ){ + if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { httpsURLConnection.setRequestMethod("PATCH"); - }else { + } else { httpsURLConnection.setRequestProperty("X-HTTP-Method-Override", "PATCH"); httpsURLConnection.setRequestMethod("POST"); } if (token != null && !token.startsWith("Basic ")) httpsURLConnection.setRequestProperty("Authorization", "Bearer " + token); - else if( token != null && token.startsWith("Basic ")) + else if (token != null && token.startsWith("Basic ")) httpsURLConnection.setRequestProperty("Authorization", token); httpsURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpsURLConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); @@ -999,40 +1022,44 @@ public class HttpsConnection { String response; OutputStream outputStream = httpsURLConnection.getOutputStream(); outputStream.write(postDataBytes); - if( avatar != null){ - uploadMedia(urlConnection,avatar, null, avatarName); + if (avatar != null) { + uploadMedia(urlConnection, avatar, null, avatarName); } - if( header != null){ - uploadMedia(urlConnection,null,header,headerName); + if (header != null) { + uploadMedia(urlConnection, null, header, headerName); } if (httpsURLConnection.getResponseCode() >= 200 && httpsURLConnection.getResponseCode() < 400) { response = converToString(httpsURLConnection.getInputStream()); } else { String error = null; - if( httpsURLConnection.getErrorStream() != null) { + if (httpsURLConnection.getErrorStream() != null) { InputStream stream = httpsURLConnection.getErrorStream(); if (stream == null) { stream = httpsURLConnection.getInputStream(); } try (Scanner scanner = new Scanner(stream)) { scanner.useDelimiter("\\Z"); - if( scanner.hasNext()) { + if (scanner.hasNext()) { error = scanner.next(); } - }catch (Exception e){e.printStackTrace();} + } catch (Exception e) { + e.printStackTrace(); + } } int responseCode = httpsURLConnection.getResponseCode(); try { httpsURLConnection.getInputStream().close(); - }catch (Exception ignored){} + } catch (Exception ignored) { + } try { httpsURLConnection.getInputStream().close(); - }catch (Exception ignored){} + } catch (Exception ignored) { + } throw new HttpsConnectionException(responseCode, error); } httpsURLConnection.getInputStream().close(); return response; - }else { + } else { URL url = new URL(urlConnection); Map params = new LinkedHashMap<>(); if (paramaters != null) { @@ -1058,15 +1085,15 @@ public class HttpsConnection { httpURLConnection = (HttpsURLConnection) url.openConnection(); httpURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT); httpURLConnection.setConnectTimeout(timeout * 1000); - if( Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT ){ + if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { httpURLConnection.setRequestMethod("PATCH"); - }else { + } else { httpURLConnection.setRequestProperty("X-HTTP-Method-Override", "PATCH"); httpURLConnection.setRequestMethod("POST"); } if (token != null && !token.startsWith("Basic ")) httpURLConnection.setRequestProperty("Authorization", "Bearer " + token); - else if( token != null && token.startsWith("Basic ")) + else if (token != null && token.startsWith("Basic ")) httpURLConnection.setRequestProperty("Authorization", token); httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpURLConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); @@ -1075,33 +1102,36 @@ public class HttpsConnection { OutputStream outputStream = httpURLConnection.getOutputStream(); outputStream.write(postDataBytes); - if( avatar != null){ - uploadMedia(urlConnection,avatar, null, avatarName); + if (avatar != null) { + uploadMedia(urlConnection, avatar, null, avatarName); } - if( header != null){ - uploadMedia(urlConnection,null,header,headerName); + if (header != null) { + uploadMedia(urlConnection, null, header, headerName); } String response; if (httpURLConnection.getResponseCode() >= 200 && httpURLConnection.getResponseCode() < 400) { response = converToString(httpsURLConnection.getInputStream()); } else { String error = null; - if( httpURLConnection.getErrorStream() != null) { + if (httpURLConnection.getErrorStream() != null) { InputStream stream = httpURLConnection.getErrorStream(); if (stream == null) { stream = httpURLConnection.getInputStream(); } try (Scanner scanner = new Scanner(stream)) { scanner.useDelimiter("\\Z"); - if( scanner.hasNext()) { + if (scanner.hasNext()) { error = scanner.next(); } - }catch (Exception e){e.printStackTrace();} + } catch (Exception e) { + e.printStackTrace(); + } } int responseCode = httpURLConnection.getResponseCode(); try { httpURLConnection.getInputStream().close(); - }catch (Exception ignored){} + } catch (Exception ignored) { + } throw new HttpsConnectionException(responseCode, error); } @@ -1112,9 +1142,8 @@ public class HttpsConnection { } - public String put(String urlConnection, int timeout, HashMap paramaters, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException { - if( urlConnection.startsWith("https://")) { + if (urlConnection.startsWith("https://")) { URL url = new URL(urlConnection); Map params = new LinkedHashMap<>(); if (paramaters != null) { @@ -1143,7 +1172,7 @@ public class HttpsConnection { httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory(this.instance)); if (token != null && !token.startsWith("Basic ")) httpsURLConnection.setRequestProperty("Authorization", "Bearer " + token); - else if( token != null && token.startsWith("Basic ")) + else if (token != null && token.startsWith("Basic ")) httpsURLConnection.setRequestProperty("Authorization", token); httpsURLConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); @@ -1158,28 +1187,31 @@ public class HttpsConnection { response = converToString(httpsURLConnection.getInputStream()); } else { String error = null; - if( httpsURLConnection.getErrorStream() != null) { + if (httpsURLConnection.getErrorStream() != null) { InputStream stream = httpsURLConnection.getErrorStream(); if (stream == null) { stream = httpsURLConnection.getInputStream(); } try (Scanner scanner = new Scanner(stream)) { scanner.useDelimiter("\\Z"); - if( scanner.hasNext()) { + if (scanner.hasNext()) { error = scanner.next(); } - }catch (Exception e){e.printStackTrace();} + } catch (Exception e) { + e.printStackTrace(); + } } int responseCode = httpsURLConnection.getResponseCode(); try { httpsURLConnection.getInputStream().close(); - }catch (Exception ignored){} + } catch (Exception ignored) { + } throw new HttpsConnectionException(responseCode, error); } getSinceMaxId(); httpsURLConnection.getInputStream().close(); return response; - }else{ + } else { URL url = new URL(urlConnection); Map params = new LinkedHashMap<>(); if (paramaters != null) { @@ -1207,7 +1239,7 @@ public class HttpsConnection { httpURLConnection.setConnectTimeout(timeout * 1000); if (token != null && !token.startsWith("Basic ")) httpURLConnection.setRequestProperty("Authorization", "Bearer " + token); - else if( token != null && token.startsWith("Basic ")) + else if (token != null && token.startsWith("Basic ")) httpURLConnection.setRequestProperty("Authorization", token); httpURLConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); @@ -1222,22 +1254,25 @@ public class HttpsConnection { response = converToString(httpURLConnection.getInputStream()); } else { String error = null; - if( httpURLConnection.getErrorStream() != null) { + if (httpURLConnection.getErrorStream() != null) { InputStream stream = httpURLConnection.getErrorStream(); if (stream == null) { stream = httpURLConnection.getInputStream(); } try (Scanner scanner = new Scanner(stream)) { scanner.useDelimiter("\\Z"); - if( scanner.hasNext()) { + if (scanner.hasNext()) { error = scanner.next(); } - }catch (Exception e){e.printStackTrace();} + } catch (Exception e) { + e.printStackTrace(); + } } int responseCode = httpURLConnection.getResponseCode(); try { httpURLConnection.getInputStream().close(); - }catch (Exception ignored){} + } catch (Exception ignored) { + } throw new HttpsConnectionException(responseCode, error); } getSinceMaxId(); @@ -1249,7 +1284,7 @@ public class HttpsConnection { public int delete(String urlConnection, int timeout, HashMap paramaters, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException { - if( urlConnection.startsWith("https://")) { + if (urlConnection.startsWith("https://")) { URL url = new URL(urlConnection); Map params = new LinkedHashMap<>(); if (paramaters != null) { @@ -1277,7 +1312,7 @@ public class HttpsConnection { httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory(this.instance)); if (token != null && !token.startsWith("Basic ")) httpsURLConnection.setRequestProperty("Authorization", "Bearer " + token); - else if( token != null && token.startsWith("Basic ")) + else if (token != null && token.startsWith("Basic ")) httpsURLConnection.setRequestProperty("Authorization", token); httpsURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpsURLConnection.setRequestMethod("DELETE"); @@ -1291,28 +1326,31 @@ public class HttpsConnection { return httpsURLConnection.getResponseCode(); } else { String error = null; - if( httpsURLConnection.getErrorStream() != null) { + if (httpsURLConnection.getErrorStream() != null) { InputStream stream = httpsURLConnection.getErrorStream(); if (stream == null) { stream = httpsURLConnection.getInputStream(); } try (Scanner scanner = new Scanner(stream)) { scanner.useDelimiter("\\Z"); - if( scanner.hasNext()) { + if (scanner.hasNext()) { error = scanner.next(); } - }catch (Exception e){e.printStackTrace();} + } catch (Exception e) { + e.printStackTrace(); + } } int responseCode = httpsURLConnection.getResponseCode(); try { httpsURLConnection.getInputStream().close(); - }catch (Exception ignored){} + } catch (Exception ignored) { + } throw new HttpsConnectionException(responseCode, error); } - }else { + } else { URL url = new URL(urlConnection); - Map params = new LinkedHashMap<>(); - if( paramaters != null) { + Map params = new LinkedHashMap<>(); + if (paramaters != null) { Iterator it = paramaters.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); @@ -1321,7 +1359,7 @@ public class HttpsConnection { } } StringBuilder postData = new StringBuilder(); - for (Map.Entry param : params.entrySet()) { + for (Map.Entry param : params.entrySet()) { if (postData.length() != 0) postData.append('&'); postData.append(param.getKey()); postData.append('='); @@ -1329,14 +1367,14 @@ public class HttpsConnection { } byte[] postDataBytes = postData.toString().getBytes("UTF-8"); - if( proxy !=null ) - httpURLConnection = (HttpURLConnection)url.openConnection(proxy); + if (proxy != null) + httpURLConnection = (HttpURLConnection) url.openConnection(proxy); else - httpURLConnection = (HttpURLConnection)url.openConnection(); + httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT); if (token != null && !token.startsWith("Basic ")) httpsURLConnection.setRequestProperty("Authorization", "Bearer " + token); - else if( token != null && token.startsWith("Basic ")) + else if (token != null && token.startsWith("Basic ")) httpsURLConnection.setRequestProperty("Authorization", token); httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpURLConnection.setRequestMethod("DELETE"); @@ -1350,24 +1388,27 @@ public class HttpsConnection { getSinceMaxId(); httpURLConnection.getInputStream().close(); return httpURLConnection.getResponseCode(); - }else { + } else { String error = null; - if( httpURLConnection.getErrorStream() != null) { + if (httpURLConnection.getErrorStream() != null) { InputStream stream = httpURLConnection.getErrorStream(); if (stream == null) { stream = httpURLConnection.getInputStream(); } try (Scanner scanner = new Scanner(stream)) { scanner.useDelimiter("\\Z"); - if( scanner.hasNext()) { + if (scanner.hasNext()) { error = scanner.next(); } - }catch (Exception e){e.printStackTrace();} + } catch (Exception e) { + e.printStackTrace(); + } } int responseCode = httpURLConnection.getResponseCode(); try { httpURLConnection.getInputStream().close(); - }catch (Exception ignored){} + } catch (Exception ignored) { + } throw new HttpsConnectionException(responseCode, error); } } @@ -1382,15 +1423,15 @@ public class HttpsConnection { } - private void getSinceMaxId(){ - if( Helper.getLiveInstanceWithProtocol(context) == null) + private void getSinceMaxId() { + if (Helper.getLiveInstanceWithProtocol(context) == null) return; - if( Helper.getLiveInstanceWithProtocol(context).startsWith("https://")) { + if (Helper.getLiveInstanceWithProtocol(context).startsWith("https://")) { if (httpsURLConnection == null) return; Map> map = httpsURLConnection.getHeaderFields(); for (Map.Entry> entry : map.entrySet()) { - if (entry.toString().startsWith("Link") || entry.toString().startsWith("link") ) { + if (entry.toString().startsWith("Link") || entry.toString().startsWith("link")) { Pattern patternMaxId = Pattern.compile("max_id=([0-9a-zA-Z]{1,}).*"); Matcher matcherMaxId = patternMaxId.matcher(entry.toString()); if (matcherMaxId.find()) { @@ -1406,7 +1447,7 @@ public class HttpsConnection { } } } - }else { + } else { if (httpURLConnection == null) return; Map> map = httpURLConnection.getHeaderFields(); @@ -1437,13 +1478,13 @@ public class HttpsConnection { int getActionCode() { - if( Helper.getLiveInstanceWithProtocol(context).startsWith("https://")) { + if (Helper.getLiveInstanceWithProtocol(context).startsWith("https://")) { try { return httpsURLConnection.getResponseCode(); } catch (IOException e) { return -1; } - }else { + } else { try { return httpURLConnection.getResponseCode(); } catch (IOException e) { @@ -1456,16 +1497,17 @@ public class HttpsConnection { private int statusCode; private String message; + HttpsConnectionException(int statusCode, String message) { this.statusCode = statusCode; SpannableString spannableString; - if( message != null) { + if (message != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) spannableString = new SpannableString(Html.fromHtml(message, Html.FROM_HTML_MODE_LEGACY)); else //noinspection deprecation spannableString = new SpannableString(Html.fromHtml(message)); - }else { + } else { spannableString = new SpannableString(context.getString(R.string.toast_error)); } this.message = spannableString.toString(); diff --git a/app/src/main/java/app/fedilab/android/client/PeertubeAPI.java b/app/src/main/java/app/fedilab/android/client/PeertubeAPI.java index 64873ac8f..16e989143 100644 --- a/app/src/main/java/app/fedilab/android/client/PeertubeAPI.java +++ b/app/src/main/java/app/fedilab/android/client/PeertubeAPI.java @@ -21,6 +21,7 @@ import android.database.sqlite.SQLiteDatabase; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; + import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; @@ -69,7 +70,6 @@ import app.fedilab.android.sqlite.Sqlite; public class PeertubeAPI { - private Account account; private Context context; private Results results; @@ -92,14 +92,14 @@ public class PeertubeAPI { tootPerPage = Helper.TOOTS_PER_PAGE; accountPerPage = Helper.ACCOUNTS_PER_PAGE; notificationPerPage = Helper.NOTIFICATIONS_PER_PAGE; - if( Helper.getLiveInstance(context) != null) + if (Helper.getLiveInstance(context) != null) this.instance = Helper.getLiveInstance(context); else { SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(context)); Account account = new AccountDAO(context, db).getUniqAccount(userId, instance); - if( account == null) { + if (account == null) { apiResponse = new APIResponse(); APIError = new Error(); return; @@ -113,7 +113,7 @@ public class PeertubeAPI { public PeertubeAPI(Context context, String instance, String token) { this.context = context; - if( context == null) { + if (context == null) { apiResponse = new APIResponse(); APIError = new Error(); return; @@ -122,12 +122,12 @@ public class PeertubeAPI { tootPerPage = Helper.TOOTS_PER_PAGE; accountPerPage = Helper.ACCOUNTS_PER_PAGE; notificationPerPage = Helper.NOTIFICATIONS_PER_PAGE; - if( instance != null) + if (instance != null) this.instance = instance; else this.instance = Helper.getLiveInstance(context); - if( token != null) + if (token != null) this.prefKeyOauthTokenT = token; else this.prefKeyOauthTokenT = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); @@ -160,11 +160,10 @@ public class PeertubeAPI { } - /** * Update video meta data *synchronously* * - * @param peertube Peertube + * @param peertube Peertube * @return APIResponse */ @SuppressWarnings("SameParameterValue") @@ -174,42 +173,42 @@ public class PeertubeAPI { params.put("name", peertube.getName()); //Category - Map.Entry categoryM = peertube.getCategory().entrySet().iterator().next(); + Map.Entry categoryM = peertube.getCategory().entrySet().iterator().next(); Integer idCategory = categoryM.getKey(); params.put("category", String.valueOf(idCategory)); //License - Map.Entry licenseM = peertube.getLicense().entrySet().iterator().next(); - Integer idLicense= licenseM.getKey(); + Map.Entry licenseM = peertube.getLicense().entrySet().iterator().next(); + Integer idLicense = licenseM.getKey(); params.put("licence", String.valueOf(idLicense)); //language - Map.Entry languagesM = peertube.getLanguage().entrySet().iterator().next(); + Map.Entry languagesM = peertube.getLanguage().entrySet().iterator().next(); String iDlanguage = languagesM.getKey(); params.put("language", iDlanguage); params.put("support", "null"); params.put("description", peertube.getDescription()); //Channel - Map.Entry channelsM = peertube.getChannelForUpdate().entrySet().iterator().next(); + Map.Entry channelsM = peertube.getChannelForUpdate().entrySet().iterator().next(); String iDChannel = channelsM.getValue(); params.put("channelId", iDChannel); //Privacy - Map.Entry privacyM = peertube.getPrivacy().entrySet().iterator().next(); + Map.Entry privacyM = peertube.getPrivacy().entrySet().iterator().next(); Integer idPrivacy = privacyM.getKey(); params.put("privacy", String.valueOf(idPrivacy)); - if( peertube.getTags() != null && peertube.getTags().size() > 0){ + if (peertube.getTags() != null && peertube.getTags().size() > 0) { StringBuilder parameters = new StringBuilder(); parameters.append("[]&"); - for(String tag: peertube.getTags()) + for (String tag : peertube.getTags()) parameters.append("tags=").append(tag).append("&"); String strParam = parameters.toString(); strParam = strParam.substring(0, strParam.length() - 1); params.put("tags[]", strParam); - }else { + } else { params.put("tags", "null"); } params.put("nsfw", String.valueOf(peertube.isSensitive())); params.put("waitTranscoding", "true"); params.put("commentsEnabled", String.valueOf(peertube.isCommentsEnabled())); - params.put("scheduleUpdate","null"); + params.put("scheduleUpdate", "null"); List peertubes = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); @@ -241,7 +240,7 @@ public class PeertubeAPI { String response = new HttpsConnection(context, this.instance).get(getAbsoluteUrl("/videos/categories"), 60, null, null); JSONObject categories = new JSONObject(response); LinkedHashMap _pcategories = new LinkedHashMap<>(); - for( int i = 1 ; i <= categories.length() ; i++){ + for (int i = 1; i <= categories.length(); i++) { _pcategories.put(i, categories.getString(String.valueOf(i))); } @@ -255,14 +254,15 @@ public class PeertubeAPI { String key = iter.next(); try { _languages.put(key, (String) languages.get(key)); - } catch (JSONException ignored) {} + } catch (JSONException ignored) { + } } peertubeInformation.setLanguages(_languages); response = new HttpsConnection(context, this.instance).get(getAbsoluteUrl("/videos/privacies"), 60, null, null); JSONObject privacies = new JSONObject(response); LinkedHashMap _pprivacies = new LinkedHashMap<>(); - for( int i = 1 ; i <= privacies.length() ; i++){ + for (int i = 1; i <= privacies.length(); i++) { _pprivacies.put(i, privacies.getString(String.valueOf(i))); } @@ -272,7 +272,7 @@ public class PeertubeAPI { response = new HttpsConnection(context, this.instance).get(getAbsoluteUrl("/video-playlists/privacies"), 60, null, null); JSONObject plprivacies = new JSONObject(response); LinkedHashMap _plprivacies = new LinkedHashMap<>(); - for( int i = 1 ; i <= plprivacies.length() ; i++){ + for (int i = 1; i <= plprivacies.length(); i++) { _plprivacies.put(i, plprivacies.getString(String.valueOf(i))); } @@ -281,7 +281,7 @@ public class PeertubeAPI { response = new HttpsConnection(context, this.instance).get(getAbsoluteUrl("/videos/licences"), 60, null, null); JSONObject licences = new JSONObject(response); LinkedHashMap _plicences = new LinkedHashMap<>(); - for( int i = 1 ; i <= licences.length() ; i++){ + for (int i = 1; i <= licences.length(); i++) { _plicences.put(i, licences.getString(String.valueOf(i))); } @@ -290,10 +290,10 @@ public class PeertubeAPI { String instance = Helper.getLiveInstance(context); String lang = null; - if(PeertubeInformation.langueMapped.containsKey( Locale.getDefault().getLanguage())) + if (PeertubeInformation.langueMapped.containsKey(Locale.getDefault().getLanguage())) lang = PeertubeInformation.langueMapped.get(Locale.getDefault().getLanguage()); - if( lang != null && !lang.startsWith("en")) { + if (lang != null && !lang.startsWith("en")) { response = new HttpsConnection(context, this.instance).get(String.format("https://" + instance + "/client/locales/%s/server.json", lang), 60, null, null); JSONObject translations = new JSONObject(response); LinkedHashMap _translations = new LinkedHashMap<>(); @@ -324,7 +324,7 @@ public class PeertubeAPI { * Verifiy credential of the authenticated user *synchronously* * @return Account */ - public Account verifyCredentials() { + public Account verifyCredentials() { account = new Account(); try { String response = new HttpsConnection(context, this.instance).get(getAbsoluteUrl("/users/me"), 60, null, prefKeyOauthTokenT); @@ -338,22 +338,23 @@ public class PeertubeAPI { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); - }catch (HttpsConnection.HttpsConnectionException e) { - if( e.getStatusCode() == 401 || e.getStatusCode() == 403){ + } catch (HttpsConnection.HttpsConnectionException e) { + if (e.getStatusCode() == 401 || e.getStatusCode() == 403) { SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); Account targetedAccount = new AccountDAO(context, db).getAccountByToken(prefKeyOauthTokenT); HashMap values = refreshToken(targetedAccount.getClient_id(), targetedAccount.getClient_secret(), targetedAccount.getRefresh_token()); - if( values.containsKey("access_token") && values.get("access_token") != null) { + if (values.containsKey("access_token") && values.get("access_token") != null) { targetedAccount.setToken(values.get("access_token")); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); //This account is currently logged in, the token is updated - if( prefKeyOauthTokenT.equals(token)){ + if (prefKeyOauthTokenT.equals(token)) { SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, targetedAccount.getToken()); editor.apply(); } - }if( values.containsKey("refresh_token") && values.get("refresh_token") != null) + } + if (values.containsKey("refresh_token") && values.get("refresh_token") != null) targetedAccount.setRefresh_token(values.get("refresh_token")); new AccountDAO(context, db).updateAccount(targetedAccount); @@ -384,7 +385,7 @@ public class PeertubeAPI { * Verifiy credential of the authenticated user *synchronously* * @return Account */ - private HashMap refreshToken(String client_id, String client_secret, String refresh_token) { + private HashMap refreshToken(String client_id, String client_secret, String refresh_token) { account = new Account(); HashMap params = new HashMap<>(); HashMap newValues = new HashMap<>(); @@ -396,10 +397,10 @@ public class PeertubeAPI { String response = new HttpsConnection(context, this.instance).post(getAbsoluteUrl("/users/token"), 60, params, null); JSONObject resobj = new JSONObject(response); String token = resobj.get("access_token").toString(); - if( resobj.has("refresh_token")) + if (resobj.has("refresh_token")) refresh_token = resobj.get("refresh_token").toString(); - newValues.put("access_token",token); - newValues.put("refresh_token",refresh_token); + newValues.put("access_token", token); + newValues.put("refresh_token", refresh_token); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { @@ -417,6 +418,7 @@ public class PeertubeAPI { /** * Returns an account + * * @param accountId String account fetched * @return Account entity */ @@ -424,7 +426,7 @@ public class PeertubeAPI { account = new Account(); try { - String response = new HttpsConnection(context, this.instance).get(getAbsoluteUrl(String.format("/accounts/%s",accountId)), 60, null, prefKeyOauthTokenT); + String response = new HttpsConnection(context, this.instance).get(getAbsoluteUrl(String.format("/accounts/%s", accountId)), 60, null, prefKeyOauthTokenT); account = parseAccountResponsePeertube(context, new JSONObject(response)); } catch (HttpsConnection.HttpsConnectionException e) { e.printStackTrace(); @@ -442,9 +444,9 @@ public class PeertubeAPI { } - /** * Returns a relationship between the authenticated account and an account + * * @param uri String accounts fetched * @return Relationship entity */ @@ -475,8 +477,8 @@ public class PeertubeAPI { /** * Retrieves videos for the account *synchronously* * - * @param acct String Id of the account - * @param max_id String id max + * @param acct String Id of the account + * @param max_id String id max * @return APIResponse */ public APIResponse getVideos(String acct, String max_id) { @@ -486,7 +488,7 @@ public class PeertubeAPI { /** * Retrieves history for videos for the account *synchronously* * - * @param max_id String id max + * @param max_id String id max * @return APIResponse */ public APIResponse getMyHistory(String max_id) { @@ -494,12 +496,11 @@ public class PeertubeAPI { } - /** - * Retrieves history for videos for the account *synchronously* + * Retrieves history for videos for the account *synchronously* * - * @param max_id String id max - * @param since_id String since the id + * @param max_id String id max + * @param since_id String since the id * @return APIResponse */ @SuppressWarnings("SameParameterValue") @@ -539,7 +540,7 @@ public class PeertubeAPI { /** * Retrieves videos for the account *synchronously* * - * @param max_id String id max + * @param max_id String id max * @return APIResponse */ public APIResponse getMyVideos(String max_id) { @@ -547,12 +548,11 @@ public class PeertubeAPI { } - /** * Retrieves status for the account *synchronously* * - * @param max_id String id max - * @param since_id String since the id + * @param max_id String id max + * @param since_id String since the id * @return APIResponse */ @SuppressWarnings("SameParameterValue") @@ -593,9 +593,9 @@ public class PeertubeAPI { /** * Retrieves status for the account *synchronously* * - * @param acct String Id of the account - * @param max_id String id max - * @param since_id String since the id + * @param acct String Id of the account + * @param max_id String id max + * @param since_id String since the id * @return APIResponse */ @SuppressWarnings("SameParameterValue") @@ -633,28 +633,28 @@ public class PeertubeAPI { /** * Retrieves Peertube notifications for the account *synchronously* * - * @param max_id String id max + * @param max_id String id max * @return APIResponse */ - public APIResponse getNotifications(String max_id){ + public APIResponse getNotifications(String max_id) { return getNotifications(max_id, null); } /** * Retrieves Peertube notifications since id for the account *synchronously* * - * @param since_id String id since + * @param since_id String id since * @return APIResponse */ - public APIResponse getNotificationsSince(String since_id){ + public APIResponse getNotificationsSince(String since_id) { return getNotifications(null, since_id); } /** * Retrieves Peertube notifications for the account *synchronously* * - * @param max_id String id max - * @param since_id String since the id + * @param max_id String id max + * @param since_id String since the id * @return APIResponse */ @SuppressWarnings("SameParameterValue") @@ -692,8 +692,8 @@ public class PeertubeAPI { /** * Retrieves videos channel for the account *synchronously* * - * @param acct String Id of the account - * @param max_id String id max + * @param acct String Id of the account + * @param max_id String id max * @return APIResponse */ public APIResponse getVideosChannel(String acct, String max_id) { @@ -703,9 +703,9 @@ public class PeertubeAPI { /** * Retrieves status for the account *synchronously* * - * @param acct String Id of the account - * @param max_id String id max - * @param since_id String since the id + * @param acct String Id of the account + * @param max_id String id max + * @param since_id String since the id * @return APIResponse */ @SuppressWarnings("SameParameterValue") @@ -743,18 +743,17 @@ public class PeertubeAPI { } - - /** * Retrieves subscription videos *synchronously* - * @param max_id String id max + * + * @param max_id String id max * @return APIResponse */ - public APIResponse getSubscriptionsTL( String max_id) { + public APIResponse getSubscriptionsTL(String max_id) { try { - return getTL("/users/me/subscriptions/videos","-publishedAt",null, max_id, null, null); + return getTL("/users/me/subscriptions/videos", "-publishedAt", null, max_id, null, null); } catch (HttpsConnection.HttpsConnectionException e) { - if( e.getStatusCode() == 401 || e.getStatusCode() == 403) { + if (e.getStatusCode() == 401 || e.getStatusCode() == 403) { SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); Account targetedAccount = new AccountDAO(context, db).getAccountByToken(prefKeyOauthTokenT); HashMap values = refreshToken(targetedAccount.getClient_id(), targetedAccount.getClient_secret(), targetedAccount.getRefresh_token()); @@ -772,7 +771,7 @@ public class PeertubeAPI { targetedAccount.setRefresh_token(values.get("refresh_token")); new AccountDAO(context, db).updateAccount(targetedAccount); try { - return getTL("/users/me/subscriptions/videos","-publishedAt",null, max_id, null, null); + return getTL("/users/me/subscriptions/videos", "-publishedAt", null, max_id, null, null); } catch (HttpsConnection.HttpsConnectionException e1) { setError(e.getStatusCode(), e); return apiResponse; @@ -785,12 +784,13 @@ public class PeertubeAPI { /** * Retrieves overview videos *synchronously* - * @param max_id String id max + * + * @param max_id String id max * @return APIResponse */ - public APIResponse getOverviewTL( String max_id) { + public APIResponse getOverviewTL(String max_id) { try { - return getTL("/overviews/videos",null,null, max_id, null, null); + return getTL("/overviews/videos", null, null, max_id, null, null); } catch (HttpsConnection.HttpsConnectionException e) { setError(e.getStatusCode(), e); return apiResponse; @@ -799,12 +799,13 @@ public class PeertubeAPI { /** * Retrieves trending videos *synchronously* - * @param max_id String id max + * + * @param max_id String id max * @return APIResponse */ - public APIResponse getTrendingTL( String max_id) { + public APIResponse getTrendingTL(String max_id) { try { - return getTL("/videos/","-trending", null,max_id, null, null); + return getTL("/videos/", "-trending", null, max_id, null, null); } catch (HttpsConnection.HttpsConnectionException e) { setError(e.getStatusCode(), e); return apiResponse; @@ -813,12 +814,13 @@ public class PeertubeAPI { /** * Retrieves trending videos *synchronously* - * @param max_id String id max + * + * @param max_id String id max * @return APIResponse */ - public APIResponse getRecentlyAddedTL( String max_id) { + public APIResponse getRecentlyAddedTL(String max_id) { try { - return getTL("/videos/","-publishedAt",null,max_id, null, null); + return getTL("/videos/", "-publishedAt", null, max_id, null, null); } catch (HttpsConnection.HttpsConnectionException e) { setError(e.getStatusCode(), e); return apiResponse; @@ -827,12 +829,13 @@ public class PeertubeAPI { /** * Retrieves trending videos *synchronously* - * @param max_id String id max + * + * @param max_id String id max * @return APIResponse */ - public APIResponse getLocalTL( String max_id) { + public APIResponse getLocalTL(String max_id) { try { - return getTL("/videos/","-publishedAt", "local",max_id, null, null); + return getTL("/videos/", "-publishedAt", "local", max_id, null, null); } catch (HttpsConnection.HttpsConnectionException e) { setError(e.getStatusCode(), e); return apiResponse; @@ -841,11 +844,12 @@ public class PeertubeAPI { /** * Retrieves home timeline for the account since an Id value *synchronously* + * * @return APIResponse */ public APIResponse getSubscriptionsTLSinceId(String since_id) { try { - return getTL("/users/me/subscriptions/videos",null,null,null, since_id, null); + return getTL("/users/me/subscriptions/videos", null, null, null, since_id, null); } catch (HttpsConnection.HttpsConnectionException e) { setError(e.getStatusCode(), e); return apiResponse; @@ -854,11 +858,12 @@ public class PeertubeAPI { /** * Retrieves home timeline for the account from a min Id value *synchronously* + * * @return APIResponse */ public APIResponse getSubscriptionsTLMinId(String min_id) { try { - return getTL("/users/me/subscriptions/videos",null, null,null, null, min_id); + return getTL("/users/me/subscriptions/videos", null, null, null, null, min_id); } catch (HttpsConnection.HttpsConnectionException e) { setError(e.getStatusCode(), e); return apiResponse; @@ -868,6 +873,7 @@ public class PeertubeAPI { /** * Retrieves home timeline for the account *synchronously* + * * @param max_id String id max * @param since_id String since the id * @return APIResponse @@ -881,13 +887,13 @@ public class PeertubeAPI { params.put("since_id", since_id); if (min_id != null) params.put("min_id", min_id); - params.put("count",String.valueOf(tootPerPage)); - if( sort != null) - params.put("sort",sort); + params.put("count", String.valueOf(tootPerPage)); + if (sort != null) + params.put("sort", sort); else - params.put("sort","publishedAt"); - if( filter != null) - params.put("filter",filter); + params.put("sort", "publishedAt"); + if (filter != null) + params.put("filter", filter); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); boolean nsfw = sharedpreferences.getBoolean(Helper.SET_VIDEO_NSFW, false); params.put("nsfw", String.valueOf(nsfw)); @@ -895,21 +901,21 @@ public class PeertubeAPI { try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); String response = httpsConnection.get(getAbsoluteUrl(action), 60, params, prefKeyOauthTokenT); - if( !action.equals("/overviews/videos")) { + if (!action.equals("/overviews/videos")) { JSONArray values = new JSONObject(response).getJSONArray("data"); peertubes = parsePeertube(values); - }else { + } else { JSONArray videoA = new JSONObject(response).getJSONArray("categories"); JSONArray values = videoA.getJSONObject(0).getJSONArray("videos"); List peertubes1 = parsePeertube(values); - if( peertubes1 != null && peertubes1.size() > 0) { + if (peertubes1 != null && peertubes1.size() > 0) { peertubes1.get(0).setHeaderType("categories"); peertubes1.get(0).setHeaderTypeValue(videoA.getJSONObject(0).getJSONObject("category").getString("label")); peertubes.addAll(peertubes1); } values = videoA.getJSONObject(1).getJSONArray("videos"); List peertubes2 = parsePeertube(values); - if( peertubes2 != null && peertubes2.size() > 0) { + if (peertubes2 != null && peertubes2.size() > 0) { peertubes2.get(0).setHeaderType("categories"); peertubes2.get(0).setHeaderTypeValue(videoA.getJSONObject(1).getJSONObject("category").getString("label")); peertubes.addAll(peertubes2); @@ -918,14 +924,14 @@ public class PeertubeAPI { videoA = new JSONObject(response).getJSONArray("tags"); values = videoA.getJSONObject(0).getJSONArray("videos"); List peertubes5 = parsePeertube(values); - if( peertubes5 != null && peertubes5.size() > 0) { + if (peertubes5 != null && peertubes5.size() > 0) { peertubes5.get(0).setHeaderType("tags"); peertubes5.get(0).setHeaderTypeValue(videoA.getJSONObject(0).getString("tag")); peertubes.addAll(peertubes5); } values = videoA.getJSONObject(1).getJSONArray("videos"); List peertubes6 = parsePeertube(values); - if( peertubes6 != null && peertubes6.size() > 0) { + if (peertubes6 != null && peertubes6.size() > 0) { peertubes6.get(0).setHeaderType("tags"); peertubes6.get(0).setHeaderTypeValue(videoA.getJSONObject(1).getString("tag")); peertubes.addAll(peertubes6); @@ -934,14 +940,14 @@ public class PeertubeAPI { videoA = new JSONObject(response).getJSONArray("channels"); values = videoA.getJSONObject(0).getJSONArray("videos"); List peertubes3 = parsePeertube(values); - if( peertubes3 != null && peertubes3.size() > 0) { + if (peertubes3 != null && peertubes3.size() > 0) { peertubes3.get(0).setHeaderType("channels"); peertubes3.get(0).setHeaderTypeValue(videoA.getJSONObject(0).getJSONObject("channel").getString("displayName")); peertubes.addAll(peertubes3); } values = videoA.getJSONObject(1).getJSONArray("videos"); List peertubes4 = parsePeertube(values); - if( peertubes4 != null && peertubes4.size() > 0) { + if (peertubes4 != null && peertubes4.size() > 0) { peertubes4.get(0).setHeaderType("channels"); peertubes4.get(0).setHeaderTypeValue(videoA.getJSONObject(1).getJSONObject("channel").getString("displayName")); peertubes.addAll(peertubes4); @@ -961,11 +967,10 @@ public class PeertubeAPI { } - - /** * Retrieves Peertube channel from an account *synchronously* * Peertube channels are dealt like accounts + * * @return APIResponse */ public APIResponse getPeertubeChannel(String name) { @@ -994,6 +999,7 @@ public class PeertubeAPI { /** * Retrieves Peertube videos from an instance *synchronously* + * * @return APIResponse */ public APIResponse getPeertubeChannelVideos(String instance, String name) { @@ -1001,7 +1007,7 @@ public class PeertubeAPI { List peertubes = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - String response = httpsConnection.get(String.format("https://"+instance+"/api/v1/video-channels/%s/videos", name), 60, null, null); + String response = httpsConnection.get(String.format("https://" + instance + "/api/v1/video-channels/%s/videos", name), 60, null, null); JSONArray jsonArray = new JSONObject(response).getJSONArray("data"); peertubes = parsePeertube(jsonArray); } catch (HttpsConnection.HttpsConnectionException e) { @@ -1021,18 +1027,19 @@ public class PeertubeAPI { /** * Retrieves Peertube videos from an instance *synchronously* + * * @return APIResponse */ public APIResponse getPeertube(String instance, String max_id) { List peertubes = new ArrayList<>(); HashMap params = new HashMap<>(); - if( max_id == null) + if (max_id == null) max_id = "0"; params.put("start", String.valueOf(tootPerPage)); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - String response = httpsConnection.get("https://"+instance+"/api/v1/videos", 60, params, null); + String response = httpsConnection.get("https://" + instance + "/api/v1/videos", 60, params, null); JSONArray jsonArray = new JSONObject(response).getJSONArray("data"); peertubes = parsePeertube(jsonArray); } catch (HttpsConnection.HttpsConnectionException e) { @@ -1052,6 +1059,7 @@ public class PeertubeAPI { /** * Retrieves Peertube videos from an instance *synchronously* + * * @return APIResponse */ public APIResponse getSinglePeertube(String instance, String videoId, String token) { @@ -1059,7 +1067,7 @@ public class PeertubeAPI { Peertube peertube = null; try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - String response = httpsConnection.get(String.format("https://"+instance+"/api/v1/videos/%s", videoId), 60, null, token); + String response = httpsConnection.get(String.format("https://" + instance + "/api/v1/videos/%s", videoId), 60, null, token); JSONObject jsonObject = new JSONObject(response); peertube = parseSinglePeertube(context, instance, jsonObject); } catch (HttpsConnection.HttpsConnectionException e) { @@ -1082,7 +1090,7 @@ public class PeertubeAPI { /** * Retrieves peertube search *synchronously* * - * @param query String search + * @param query String search * @return APIResponse */ public APIResponse searchPeertube(String instance, String query) { @@ -1096,7 +1104,7 @@ public class PeertubeAPI { List peertubes = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - String response = httpsConnection.get("https://"+instance+"/api/v1/search/videos", 60, params, null); + String response = httpsConnection.get("https://" + instance + "/api/v1/search/videos", 60, params, null); JSONArray jsonArray = new JSONObject(response).getJSONArray("data"); peertubes = parsePeertube(jsonArray); } catch (HttpsConnection.HttpsConnectionException e) { @@ -1114,15 +1122,17 @@ public class PeertubeAPI { apiResponse.setPeertubes(peertubes); return apiResponse; } + /** * Retrieves Peertube videos from an instance *synchronously* + * * @return APIResponse */ public APIResponse getSinglePeertubeComments(String instance, String videoId) { statuses = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - String response = httpsConnection.get(String.format("https://"+instance+"/api/v1/videos/%s/comment-threads", videoId), 60, null, null); + String response = httpsConnection.get(String.format("https://" + instance + "/api/v1/videos/%s/comment-threads", videoId), 60, null, null); JSONObject jsonObject = new JSONObject(response); statuses = parseSinglePeertubeComments(context, instance, jsonObject); } catch (HttpsConnection.HttpsConnectionException e) { @@ -1141,19 +1151,17 @@ public class PeertubeAPI { } - - - /** * Retrieves rating of user on a video *synchronously* + * * @param id String id * @return APIResponse */ @SuppressWarnings("SameParameterValue") - public String getRating(String id){ + public String getRating(String id) { try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - String response = httpsConnection.get(getAbsoluteUrl(String.format("/users/me/videos/%s/rating",id)), 60, null, prefKeyOauthTokenT); + String response = httpsConnection.get(getAbsoluteUrl(String.format("/users/me/videos/%s/rating", id)), 60, null, prefKeyOauthTokenT); return new JSONObject(response).get("rating").toString(); } catch (HttpsConnection.HttpsConnectionException e) { setError(e.getStatusCode(), e); @@ -1172,48 +1180,51 @@ public class PeertubeAPI { /** * Makes the post action for a status + * * @param statusAction Enum - * @param targetedId String id of the targeted Id *can be this of a status or an account* + * @param targetedId String id of the targeted Id *can be this of a status or an account* * @return in status code - Should be equal to 200 when action is done */ - public int postAction(API.StatusAction statusAction, String targetedId){ + public int postAction(API.StatusAction statusAction, String targetedId) { return postAction(statusAction, targetedId, null, null); } - public int postRating(String targetedId, String actionMore){ + public int postRating(String targetedId, String actionMore) { return postAction(API.StatusAction.RATEVIDEO, targetedId, actionMore, null); } - public int postComment(String targetedId, String actionMore){ + public int postComment(String targetedId, String actionMore) { return postAction(API.StatusAction.PEERTUBECOMMENT, targetedId, actionMore, null); } - public int postReply(String targetedId, String actionMore, String targetedComment){ + public int postReply(String targetedId, String actionMore, String targetedComment) { return postAction(API.StatusAction.PEERTUBEREPLY, targetedId, actionMore, targetedComment); } - public int deleteComment(String targetedId, String targetedComment){ + public int deleteComment(String targetedId, String targetedComment) { return postAction(API.StatusAction.PEERTUBEDELETECOMMENT, targetedId, null, targetedComment); } - public int deleteVideo(String targetedId){ + public int deleteVideo(String targetedId) { return postAction(API.StatusAction.PEERTUBEDELETEVIDEO, targetedId, null, null); } + /** * Makes the post action - * @param statusAction Enum - * @param targetedId String id of the targeted Id *can be this of a status or an account* - * @param actionMore String another action + * + * @param statusAction Enum + * @param targetedId String id of the targeted Id *can be this of a status or an account* + * @param actionMore String another action * @param targetedComment String another action * @return in status code - Should be equal to 200 when action is done */ - private int postAction(API.StatusAction statusAction, String targetedId, String actionMore, String targetedComment){ + private int postAction(API.StatusAction statusAction, String targetedId, String actionMore, String targetedComment) { String action; String actionCall = "POST"; HashMap params = null; - switch (statusAction){ + switch (statusAction) { case FOLLOW: action = "/users/me/subscriptions"; params = new HashMap<>(); @@ -1252,11 +1263,11 @@ public class PeertubeAPI { } try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - if( actionCall.equals("POST")) + if (actionCall.equals("POST")) httpsConnection.post(getAbsoluteUrl(action), 60, params, prefKeyOauthTokenT); - else if( actionCall.equals("DELETE")) + else if (actionCall.equals("DELETE")) httpsConnection.delete(getAbsoluteUrl(action), 60, params, prefKeyOauthTokenT); - else if( actionCall.equals("PUT")) + else if (actionCall.equals("PUT")) httpsConnection.put(getAbsoluteUrl(action), 60, params, prefKeyOauthTokenT); actionCode = httpsConnection.getActionCode(); } catch (HttpsConnection.HttpsConnectionException e) { @@ -1272,15 +1283,14 @@ public class PeertubeAPI { } - - /** * Changes media description - * @param mediaId String - * @param description String + * + * @param mediaId String + * @param description String * @return Attachment */ - public Attachment updateDescription(String mediaId, String description){ + public Attachment updateDescription(String mediaId, String description) { HashMap params = new HashMap<>(); try { @@ -1309,12 +1319,13 @@ public class PeertubeAPI { /** * Video is in play lists + * * @return APIResponse */ - public APIResponse getPlaylistForVideo(String videoId){ + public APIResponse getPlaylistForVideo(String videoId) { HashMap params = new HashMap<>(); - params.put("videoIds",videoId); + params.put("videoIds", videoId); List ids = new ArrayList<>(); try { String response = new HttpsConnection(context, this.instance).get(getAbsoluteUrl("/users/me/video-playlists/videos-exist"), 60, params, prefKeyOauthTokenT); @@ -1322,7 +1333,7 @@ public class PeertubeAPI { JSONArray jsonArray = new JSONObject(response).getJSONArray(videoId); try { int i = 0; - while (i < jsonArray.length() ) { + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); String playlistId = resobj.getString("playlistId"); ids.add(playlistId); @@ -1351,14 +1362,15 @@ public class PeertubeAPI { /** * Get lists for the user + * * @return APIResponse */ - public APIResponse getPlayists(String username){ + public APIResponse getPlayists(String username) { List playlists = new ArrayList<>(); try { String response = new HttpsConnection(context, this.instance).get(getAbsoluteUrl(String.format("/accounts/%s/video-playlists", username)), 60, null, prefKeyOauthTokenT); - playlists = parsePlaylists(context, new JSONObject(response).getJSONArray("data")); + playlists = parsePlaylists(context, new JSONObject(response).getJSONArray("data")); } catch (HttpsConnection.HttpsConnectionException e) { setError(e.getStatusCode(), e); } catch (NoSuchAlgorithmException e) { @@ -1375,14 +1387,13 @@ public class PeertubeAPI { } - - /** * Delete a Playlist + * * @param playlistId String, the playlist id * @return int */ - public int deletePlaylist(String playlistId){ + public int deletePlaylist(String playlistId) { try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); httpsConnection.delete(getAbsoluteUrl(String.format("/video-playlists/%s", playlistId)), 60, null, prefKeyOauthTokenT); @@ -1402,11 +1413,12 @@ public class PeertubeAPI { /** * Delete video in a Playlist + * * @param playlistId String, the playlist id - * @param videoId String, the video id + * @param videoId String, the video id * @return int */ - public int deleteVideoPlaylist(String playlistId, String videoId){ + public int deleteVideoPlaylist(String playlistId, String videoId) { try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); httpsConnection.delete(getAbsoluteUrl(String.format("/video-playlists/%s/videos/%s", playlistId, videoId)), 60, null, prefKeyOauthTokenT); @@ -1425,11 +1437,12 @@ public class PeertubeAPI { /** * Add video in a Playlist + * * @param playlistId String, the playlist id - * @param videoId String, the video id + * @param videoId String, the video id * @return int */ - public int addVideoPlaylist(String playlistId, String videoId){ + public int addVideoPlaylist(String playlistId, String videoId) { try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); HashMap params = new HashMap<>(); @@ -1450,13 +1463,12 @@ public class PeertubeAPI { } - /** * Retrieves status for the account *synchronously* * - * @param playlistid String Id of the playlist - * @param max_id String id max - * @param since_id String since the id + * @param playlistid String Id of the playlist + * @param max_id String id max + * @param since_id String since the id * @return APIResponse */ @SuppressWarnings("SameParameterValue") @@ -1468,7 +1480,7 @@ public class PeertubeAPI { if (since_id != null) params.put("since_id", since_id); params.put("count", String.valueOf(tootPerPage)); - params.put("sort","-updatedAt"); + params.put("sort", "-updatedAt"); List peertubes = new ArrayList<>(); try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); @@ -1495,15 +1507,16 @@ public class PeertubeAPI { /** * Parse json response for several howto + * * @param jsonArray JSONArray * @return List */ - private List parseHowTos(JSONArray jsonArray){ + private List parseHowTos(JSONArray jsonArray) { List howToVideos = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ){ + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); HowToVideo howToVideo = parseHowTo(context, resobj); @@ -1519,14 +1532,15 @@ public class PeertubeAPI { /** * Parse json response for peertube notifications + * * @param jsonArray JSONArray * @return List */ - private List parsePeertubeNotifications(JSONArray jsonArray){ + private List parsePeertubeNotifications(JSONArray jsonArray) { List peertubeNotifications = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ){ + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); PeertubeNotification peertubeNotification = parsePeertubeNotifications(context, resobj); i++; @@ -1540,10 +1554,11 @@ public class PeertubeAPI { /** * Parse json response for unique how to + * * @param resobj JSONObject * @return Peertube */ - private static PeertubeNotification parsePeertubeNotifications(Context context,JSONObject resobj){ + private static PeertubeNotification parsePeertubeNotifications(Context context, JSONObject resobj) { PeertubeNotification peertubeNotification = new PeertubeNotification(); try { peertubeNotification.setId(resobj.get("id").toString()); @@ -1552,22 +1567,22 @@ public class PeertubeAPI { peertubeNotification.setCreatedAt(Helper.mstStringToDate(context, resobj.get("createdAt").toString())); peertubeNotification.setRead(resobj.getBoolean("read")); - if( resobj.has("comment")){ + if (resobj.has("comment")) { PeertubeComment peertubeComment = new PeertubeComment(); JSONObject comment = resobj.getJSONObject("comment"); - if( comment.has("account")){ + if (comment.has("account")) { JSONObject account = comment.getJSONObject("account"); PeertubeAccountNotification peertubeAccountNotification = new PeertubeAccountNotification(); peertubeAccountNotification.setDisplayName(account.get("displayName").toString()); peertubeAccountNotification.setName(account.get("name").toString()); peertubeAccountNotification.setId(account.get("id").toString()); - if( account.has("host")) { + if (account.has("host")) { peertubeAccountNotification.setHost(account.get("host").toString()); } peertubeAccountNotification.setAvatar(account.getJSONObject("avatar").get("path").toString()); peertubeComment.setPeertubeAccountNotification(peertubeAccountNotification); } - if( comment.has("video")){ + if (comment.has("video")) { JSONObject video = comment.getJSONObject("video"); PeertubeVideoNotification peertubeVideoNotification = new PeertubeVideoNotification(); peertubeVideoNotification.setUuid(video.get("uuid").toString()); @@ -1580,19 +1595,19 @@ public class PeertubeAPI { peertubeNotification.setPeertubeComment(peertubeComment); } - if( resobj.has("video")){ + if (resobj.has("video")) { PeertubeVideoNotification peertubeVideoNotification = new PeertubeVideoNotification(); JSONObject video = resobj.getJSONObject("video"); peertubeVideoNotification.setUuid(video.get("uuid").toString()); peertubeVideoNotification.setName(video.get("name").toString()); peertubeVideoNotification.setId(video.get("id").toString()); - if( video.has("channel")){ + if (video.has("channel")) { PeertubeAccountNotification peertubeAccountNotification = new PeertubeAccountNotification(); JSONObject channel = video.getJSONObject("channel"); peertubeAccountNotification.setDisplayName(channel.get("displayName").toString()); peertubeAccountNotification.setName(channel.get("name").toString()); peertubeAccountNotification.setId(channel.get("id").toString()); - if( channel.has("avatar")){ + if (channel.has("avatar")) { peertubeAccountNotification.setAvatar(channel.getJSONObject("avatar").get("path").toString()); } peertubeVideoNotification.setPeertubeAccountNotification(peertubeAccountNotification); @@ -1600,7 +1615,7 @@ public class PeertubeAPI { peertubeNotification.setPeertubeVideoNotification(peertubeVideoNotification); } - if( resobj.has("actorFollow")){ + if (resobj.has("actorFollow")) { PeertubeActorFollow peertubeActorFollow = new PeertubeActorFollow(); JSONObject actorFollow = resobj.getJSONObject("actorFollow"); @@ -1611,10 +1626,10 @@ public class PeertubeAPI { peertubeAccountNotification.setDisplayName(follower.get("displayName").toString()); peertubeAccountNotification.setName(follower.get("name").toString()); peertubeAccountNotification.setId(follower.get("id").toString()); - if( follower.has("host")) { + if (follower.has("host")) { peertubeAccountNotification.setHost(follower.get("host").toString()); } - if( follower.has("avatar")){ + if (follower.has("avatar")) { peertubeAccountNotification.setAvatar(follower.getJSONObject("avatar").get("path").toString()); } peertubeActorFollow.setFollower(peertubeAccountNotification); @@ -1624,8 +1639,9 @@ public class PeertubeAPI { peertubeAccounFollowingNotification.setName(following.get("name").toString()); try { peertubeAccounFollowingNotification.setId(following.get("id").toString()); - }catch (Exception ignored){} - if( following.has("avatar")){ + } catch (Exception ignored) { + } + if (following.has("avatar")) { peertubeAccounFollowingNotification.setAvatar(following.getJSONObject("avatar").get("path").toString()); } peertubeActorFollow.setFollowing(peertubeAccounFollowingNotification); @@ -1644,18 +1660,18 @@ public class PeertubeAPI { } - /** * Parse json response for several howto + * * @param jsonArray JSONArray * @return List */ - private List parsePeertube(JSONArray jsonArray){ + private List parsePeertube(JSONArray jsonArray) { List peertubes = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ){ + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Peertube peertube = parsePeertube(context, resobj); i++; @@ -1669,13 +1685,13 @@ public class PeertubeAPI { } - /** * Parse json response for unique how to + * * @param resobj JSONObject * @return Peertube */ - public static Peertube parsePeertube(Context context,JSONObject resobj){ + public static Peertube parsePeertube(Context context, JSONObject resobj) { Peertube peertube = new Peertube(); try { peertube.setId(resobj.get("id").toString()); @@ -1689,7 +1705,8 @@ public class PeertubeAPI { peertube.setAccount(parseAccountResponsePeertube(context, resobj.getJSONObject("account"))); try { peertube.setChannel(parseAccountResponsePeertube(context, resobj.getJSONObject("channel"))); - }catch (Exception ignored){} + } catch (Exception ignored) { + } peertube.setView(Integer.parseInt(resobj.get("views").toString())); peertube.setLike(Integer.parseInt(resobj.get("likes").toString())); peertube.setDislike(Integer.parseInt(resobj.get("dislikes").toString())); @@ -1697,7 +1714,8 @@ public class PeertubeAPI { peertube.setSensitive(Boolean.parseBoolean(resobj.get("nsfw").toString())); try { peertube.setCommentsEnabled(Boolean.parseBoolean(resobj.get("commentsEnabled").toString())); - }catch (Exception ignored){} + } catch (Exception ignored) { + } try { peertube.setCreated_at(Helper.mstStringToDate(context, resobj.get("createdAt").toString())); @@ -1719,7 +1737,8 @@ public class PeertubeAPI { peertube.setLicense(license); peertube.setLanguage(langue); peertube.setPrivacy(privacy); - }catch (Exception ignored){} + } catch (Exception ignored) { + } } catch (JSONException e) { e.printStackTrace(); } @@ -1729,10 +1748,11 @@ public class PeertubeAPI { /** * Parse json response for unique how to + * * @param resobj JSONObject * @return Peertube */ - private static Peertube parseSinglePeertube(Context context, String instance, JSONObject resobj){ + private static Peertube parseSinglePeertube(Context context, String instance, JSONObject resobj) { Peertube peertube = new Peertube(); try { peertube.setId(resobj.get("id").toString()); @@ -1754,15 +1774,17 @@ public class PeertubeAPI { List tags = new ArrayList<>(); try { JSONArray tagsA = resobj.getJSONArray("tags"); - for(int i = 0 ; i < tagsA.length() ; i++){ + for (int i = 0; i < tagsA.length(); i++) { String value = tagsA.getString(i); tags.add(value); } peertube.setTags(tags); - }catch (Exception ignored){} + } catch (Exception ignored) { + } try { peertube.setChannel(parseAccountResponsePeertube(context, resobj.getJSONObject("channel"))); - }catch (Exception ignored){} + } catch (Exception ignored) { + } peertube.setSensitive(Boolean.parseBoolean(resobj.get("nsfw").toString())); try { peertube.setCreated_at(Helper.mstStringToDate(context, resobj.get("createdAt").toString())); @@ -1777,7 +1799,7 @@ public class PeertubeAPI { } JSONArray files = resobj.getJSONArray("files"); ArrayList resolutions = new ArrayList<>(); - for(int j = 0 ; j < files.length() ; j++){ + for (int j = 0; j < files.length(); j++) { JSONObject attObj = files.getJSONObject(j); resolutions.add(attObj.getJSONObject("resolution").get("id").toString()); } @@ -1795,7 +1817,8 @@ public class PeertubeAPI { peertube.setLicense(license); peertube.setLanguage(langue); peertube.setPrivacy(privacy); - }catch (Exception ignored){} + } catch (Exception ignored) { + } peertube.setResolution(resolutions); } catch (JSONException e) { e.printStackTrace(); @@ -1806,33 +1829,34 @@ public class PeertubeAPI { /** * Parse json response for peertube comments + * * @param resobj JSONObject * @return Peertube */ - private static List parseSinglePeertubeComments(Context context, String instance, JSONObject resobj){ + private static List parseSinglePeertubeComments(Context context, String instance, JSONObject resobj) { List statuses = new ArrayList<>(); try { JSONArray jsonArray = resobj.getJSONArray("data"); - int i = 0; - while (i < jsonArray.length() ){ - Status status = new Status(); - JSONObject comment = jsonArray.getJSONObject(i); - status.setId(comment.get("id").toString()); - status.setUri(comment.get("url").toString()); - status.setUrl(comment.get("url").toString()); - status.setSensitive(false); - status.setSpoiler_text(""); - status.setContent(comment.get("text").toString()); - status.setIn_reply_to_id(comment.get("inReplyToCommentId").toString()); - status.setAccount(parseAccountResponsePeertube(context, comment.getJSONObject("account"))); - status.setCreated_at(Helper.mstStringToDate(context, comment.get("createdAt").toString())); - status.setMentions(new ArrayList<>()); - status.setEmojis(new ArrayList<>()); - status.setMedia_attachments(new ArrayList<>()); - status.setVisibility("public"); - i++; - statuses.add(status); - } + int i = 0; + while (i < jsonArray.length()) { + Status status = new Status(); + JSONObject comment = jsonArray.getJSONObject(i); + status.setId(comment.get("id").toString()); + status.setUri(comment.get("url").toString()); + status.setUrl(comment.get("url").toString()); + status.setSensitive(false); + status.setSpoiler_text(""); + status.setContent(comment.get("text").toString()); + status.setIn_reply_to_id(comment.get("inReplyToCommentId").toString()); + status.setAccount(parseAccountResponsePeertube(context, comment.getJSONObject("account"))); + status.setCreated_at(Helper.mstStringToDate(context, comment.get("createdAt").toString())); + status.setMentions(new ArrayList<>()); + status.setEmojis(new ArrayList<>()); + status.setMedia_attachments(new ArrayList<>()); + status.setVisibility("public"); + i++; + statuses.add(status); + } } catch (JSONException e) { e.printStackTrace(); } catch (ParseException e) { @@ -1843,10 +1867,11 @@ public class PeertubeAPI { /** * Parse json response for unique how to + * * @param resobj JSONObject * @return HowToVideo */ - private static HowToVideo parseHowTo(Context context, JSONObject resobj){ + private static HowToVideo parseHowTo(Context context, JSONObject resobj) { HowToVideo howToVideo = new HowToVideo(); try { howToVideo.setId(resobj.get("id").toString()); @@ -1864,14 +1889,13 @@ public class PeertubeAPI { } - - /** * Parse json response an unique instance + * * @param resobj JSONObject * @return Instance */ - private Instance parseInstance(JSONObject resobj){ + private Instance parseInstance(JSONObject resobj) { Instance instance = new Instance(); try { @@ -1887,17 +1911,17 @@ public class PeertubeAPI { } - /** * Parse emojis + * * @param jsonArray JSONArray * @return List of emojis */ - private List parseEmojis(JSONArray jsonArray){ + private List parseEmojis(JSONArray jsonArray) { List emojis = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ) { + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Emojis emojis1 = parseEmojis(resobj); emojis.add(emojis1); @@ -1912,30 +1936,33 @@ public class PeertubeAPI { /** * Parse json response for emoji + * * @param resobj JSONObject * @return Emojis */ - private static Emojis parseEmojis(JSONObject resobj){ + private static Emojis parseEmojis(JSONObject resobj) { Emojis emojis = new Emojis(); try { emojis.setShortcode(resobj.get("shortcode").toString()); emojis.setStatic_url(resobj.get("static_url").toString()); emojis.setUrl(resobj.get("url").toString()); - }catch (Exception ignored){} + } catch (Exception ignored) { + } return emojis; } /** * Parse emojis + * * @param jsonArray JSONArray * @return List of emojis */ - private List parseMisskeyEmojis(JSONArray jsonArray){ + private List parseMisskeyEmojis(JSONArray jsonArray) { List emojis = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ) { + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Emojis emojis1 = parseMisskeyEmojis(resobj); emojis.add(emojis1); @@ -1950,33 +1977,36 @@ public class PeertubeAPI { /** * Parse json response for emoji + * * @param resobj JSONObject * @return Emojis */ - private static Emojis parseMisskeyEmojis(JSONObject resobj){ + private static Emojis parseMisskeyEmojis(JSONObject resobj) { Emojis emojis = new Emojis(); try { emojis.setShortcode(resobj.get("name").toString()); emojis.setStatic_url(resobj.get("url").toString()); emojis.setUrl(resobj.get("url").toString()); - }catch (Exception ignored){} + } catch (Exception ignored) { + } return emojis; } /** * Parse Filters + * * @param jsonArray JSONArray * @return List of filters */ - private List parseFilters(JSONArray jsonArray){ + private List parseFilters(JSONArray jsonArray) { List filters = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ) { + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Filters filter = parseFilter(resobj); - if( filter != null) + if (filter != null) filters.add(filter); i++; } @@ -1988,50 +2018,54 @@ public class PeertubeAPI { /** * Parse json response for filter + * * @param resobj JSONObject * @return Filter */ - private Filters parseFilter(JSONObject resobj){ + private Filters parseFilter(JSONObject resobj) { Filters filter = new Filters(); try { filter.setId(resobj.get("id").toString()); - if( resobj.get("phrase").toString() == null) + if (resobj.get("phrase").toString() == null) return null; filter.setPhrase(resobj.get("phrase").toString()); - if( resobj.get("expires_at") != null && !resobj.get("expires_at").toString().equals("null")) + if (resobj.get("expires_at") != null && !resobj.get("expires_at").toString().equals("null")) filter.setSetExpires_at(Helper.mstStringToDate(context, resobj.get("expires_at").toString())); filter.setWhole_word(Boolean.parseBoolean(resobj.get("whole_word").toString())); filter.setIrreversible(Boolean.parseBoolean(resobj.get("irreversible").toString())); String contextString = resobj.get("context").toString(); - contextString = contextString.replaceAll("\\[",""); - contextString = contextString.replaceAll("]",""); - contextString = contextString.replaceAll("\"",""); - if( contextString != null) { + contextString = contextString.replaceAll("\\[", ""); + contextString = contextString.replaceAll("]", ""); + contextString = contextString.replaceAll("\"", ""); + if (contextString != null) { String[] context = contextString.split(","); - if( contextString.length() > 0 ){ + if (contextString.length() > 0) { ArrayList finalContext = new ArrayList<>(); - for(String c: context) + for (String c : context) finalContext.add(c.trim()); filter.setContext(finalContext); } } return filter; - }catch (Exception ignored){ return null;} + } catch (Exception ignored) { + return null; + } } /** * Parse Playlists + * * @param jsonArray JSONArray * @return List of lists */ - private List parsePlaylists(Context context, JSONArray jsonArray){ + private List parsePlaylists(Context context, JSONArray jsonArray) { List playlists = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ) { + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Playlist playlist = parsePlaylist(context, resobj); playlists.add(playlist); @@ -2046,10 +2080,11 @@ public class PeertubeAPI { /** * Parse json response for emoji + * * @param resobj JSONObject * @return Emojis */ - private static Playlist parsePlaylist(Context context, JSONObject resobj){ + private static Playlist parsePlaylist(Context context, JSONObject resobj) { Playlist playlist = new Playlist(); try { playlist.setId(resobj.getString("id")); @@ -2069,21 +2104,27 @@ public class PeertubeAPI { type.put(resobj.getJSONObject("type").getInt("id"), resobj.getJSONObject("type").get("label").toString()); playlist.setType(type); playlist.setPrivacy(privacy); - }catch (Exception ignored){ignored.printStackTrace();} + } catch (Exception ignored) { + ignored.printStackTrace(); + } - try{ + try { playlist.setUpdatedAt(Helper.stringToDate(context, resobj.getString("updatedAt"))); - }catch (Exception ignored){ignored.printStackTrace();} - }catch (Exception ignored){ignored.printStackTrace();} + } catch (Exception ignored) { + ignored.printStackTrace(); + } + } catch (Exception ignored) { + ignored.printStackTrace(); + } return playlist; } - private List parseAccountResponsePeertube(Context context, String instance, JSONArray jsonArray){ + private List parseAccountResponsePeertube(Context context, String instance, JSONArray jsonArray) { List accounts = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ) { + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Account account = parseAccountResponsePeertube(context, resobj); accounts.add(account); @@ -2097,62 +2138,63 @@ public class PeertubeAPI { /** * Parse json response an unique peertube account + * * @param accountObject JSONObject * @return Account */ - private static Account parseAccountResponsePeertube(Context context, JSONObject accountObject){ + private static Account parseAccountResponsePeertube(Context context, JSONObject accountObject) { Account account = new Account(); try { account.setId(accountObject.get("id").toString()); account.setUuid(accountObject.get("uuid").toString()); account.setUsername(accountObject.get("name").toString()); - account.setAcct(accountObject.get("name").toString()+"@" + accountObject.get("host")); + account.setAcct(accountObject.get("name").toString() + "@" + accountObject.get("host")); account.setDisplay_name(accountObject.get("name").toString()); account.setHost(accountObject.get("host").toString()); account.setSocial("PEERTUBE"); - if( accountObject.has("createdAt") ) + if (accountObject.has("createdAt")) account.setCreated_at(Helper.mstStringToDate(context, accountObject.get("createdAt").toString())); else account.setCreated_at(new Date()); - if( accountObject.has("followersCount") ) + if (accountObject.has("followersCount")) account.setFollowers_count(Integer.valueOf(accountObject.get("followersCount").toString())); else account.setFollowers_count(0); - if( accountObject.has("followingCount")) + if (accountObject.has("followingCount")) account.setFollowing_count(Integer.valueOf(accountObject.get("followingCount").toString())); else account.setFollowing_count(0); account.setStatuses_count(0); - if( accountObject.has("description") ) + if (accountObject.has("description")) account.setNote(accountObject.get("description").toString()); else account.setNote(""); account.setUrl(accountObject.get("url").toString()); - if( accountObject.has("avatar") && !accountObject.isNull("avatar")){ + if (accountObject.has("avatar") && !accountObject.isNull("avatar")) { account.setAvatar(accountObject.getJSONObject("avatar").get("path").toString()); - }else + } else account.setAvatar("null"); account.setHeader("null"); account.setHeader_static("null"); account.setAvatar_static(accountObject.get("avatar").toString()); - } catch (JSONException ignored) {ignored.printStackTrace();} catch (ParseException e) { + } catch (JSONException ignored) { + ignored.printStackTrace(); + } catch (ParseException e) { e.printStackTrace(); } return account; } - - - /** * Parse json response an unique relationship + * * @param resobj JSONObject * @return Relationship */ - private Relationship parseRelationshipResponse(JSONObject resobj){ + private Relationship parseRelationshipResponse(JSONObject resobj) { Relationship relationship = new Relationship(); try { @@ -2163,17 +2205,17 @@ public class PeertubeAPI { relationship.setMuting(Boolean.valueOf(resobj.get("muting").toString())); try { relationship.setMuting_notifications(Boolean.valueOf(resobj.get("muting_notifications").toString())); - }catch (Exception ignored){ + } catch (Exception ignored) { relationship.setMuting_notifications(true); } try { relationship.setEndorsed(Boolean.valueOf(resobj.get("endorsed").toString())); - }catch (Exception ignored){ + } catch (Exception ignored) { relationship.setMuting_notifications(false); } try { relationship.setShowing_reblogs(Boolean.valueOf(resobj.get("showing_reblogs").toString())); - }catch (Exception ignored){ + } catch (Exception ignored) { relationship.setMuting_notifications(false); } relationship.setRequested(Boolean.valueOf(resobj.get("requested").toString())); @@ -2186,15 +2228,16 @@ public class PeertubeAPI { /** * Parse json response for list of relationship + * * @param jsonArray JSONArray * @return List */ - private List parseRelationshipResponse(JSONArray jsonArray){ + private List parseRelationshipResponse(JSONArray jsonArray) { List relationships = new ArrayList<>(); try { int i = 0; - while (i < jsonArray.length() ) { + while (i < jsonArray.length()) { JSONObject resobj = jsonArray.getJSONObject(i); Relationship relationship = parseRelationshipResponse(resobj); relationships.add(relationship); @@ -2207,13 +2250,13 @@ public class PeertubeAPI { } - /** * Parse json response an unique attachment + * * @param resobj JSONObject * @return Relationship */ - static Attachment parseAttachmentResponse(JSONObject resobj){ + static Attachment parseAttachmentResponse(JSONObject resobj) { Attachment attachment = new Attachment(); try { @@ -2222,35 +2265,38 @@ public class PeertubeAPI { attachment.setUrl(resobj.get("url").toString()); try { attachment.setDescription(resobj.get("description").toString()); - }catch (JSONException ignore){} - try{ + } catch (JSONException ignore) { + } + try { attachment.setRemote_url(resobj.get("remote_url").toString()); - }catch (JSONException ignore){} - try{ + } catch (JSONException ignore) { + } + try { attachment.setPreview_url(resobj.get("preview_url").toString()); - }catch (JSONException ignore){} - try{ + } catch (JSONException ignore) { + } + try { attachment.setMeta(resobj.get("meta").toString()); - }catch (JSONException ignore){} - try{ + } catch (JSONException ignore) { + } + try { attachment.setText_url(resobj.get("text_url").toString()); - }catch (JSONException ignore){} + } catch (JSONException ignore) { + } - } catch (JSONException ignored) {} + } catch (JSONException ignored) { + } return attachment; } - - - - /** * Set the error message + * * @param statusCode int code - * @param error Throwable error + * @param error Throwable error */ - private void setError(int statusCode, Throwable error){ + private void setError(int statusCode, Throwable error) { APIError = new Error(); APIError.setStatusCode(statusCode); String message = statusCode + " - " + error.getMessage(); @@ -2259,7 +2305,7 @@ public class PeertubeAPI { String errorM = jsonObject.get("error").toString(); message = "Error " + statusCode + " : " + errorM; } catch (JSONException e) { - if(error.getMessage().split(".").length > 0) { + if (error.getMessage().split(".").length > 0) { String errorM = error.getMessage().split(".")[0]; message = "Error " + statusCode + " : " + errorM; } @@ -2268,11 +2314,11 @@ public class PeertubeAPI { apiResponse.setError(APIError); } - private void setDefaultError(Exception e){ + private void setDefaultError(Exception e) { APIError = new Error(); - if( e.getLocalizedMessage() != null && e.getLocalizedMessage().trim().length() > 0) + if (e.getLocalizedMessage() != null && e.getLocalizedMessage().trim().length() > 0) APIError.setError(e.getLocalizedMessage()); - else if( e.getMessage() != null && e.getMessage().trim().length() > 0) + else if (e.getMessage() != null && e.getMessage().trim().length() > 0) APIError.setError(e.getMessage()); else APIError.setError(context.getString(R.string.toast_error)); @@ -2280,7 +2326,7 @@ public class PeertubeAPI { } - public Error getError(){ + public Error getError() { return APIError; } @@ -2288,6 +2334,7 @@ public class PeertubeAPI { private String getAbsoluteUrl(String action) { return Helper.instanceWithProtocol(this.context, this.instance) + "/api/v1" + action; } + private String getAbsoluteUrlRemote(String remote, String action) { return "https://" + remote + "/api/v1" + action; } @@ -2297,7 +2344,7 @@ public class PeertubeAPI { } private String getAbsoluteUrlCommunitywiki(String action) { - return "https://communitywiki.org/trunk/api/v1" + action; + return "https://communitywiki.org/trunk/api/v1" + action; } } diff --git a/app/src/main/java/app/fedilab/android/client/TLSSocketFactory.java b/app/src/main/java/app/fedilab/android/client/TLSSocketFactory.java index 2e49d19ad..a5d98c185 100644 --- a/app/src/main/java/app/fedilab/android/client/TLSSocketFactory.java +++ b/app/src/main/java/app/fedilab/android/client/TLSSocketFactory.java @@ -2,6 +2,7 @@ package app.fedilab.android.client; import android.content.SharedPreferences; + import java.io.IOException; import java.net.InetAddress; import java.net.Socket; @@ -22,7 +23,6 @@ import app.fedilab.android.helper.Helper; /** * Created by Thomas on 29/08/2017. - * */ public class TLSSocketFactory extends SSLSocketFactory { @@ -34,11 +34,11 @@ public class TLSSocketFactory extends SSLSocketFactory { public TLSSocketFactory(String instance) throws KeyManagementException, NoSuchAlgorithmException { - if( instance == null || !instance.endsWith(".onion")) { + if (instance == null || !instance.endsWith(".onion")) { sslContext = SSLContext.getInstance("TLS"); isOnion = false; sslContext.init(null, null, null); - }else{ + } else { sslContext = SSLContext.getInstance("SSL"); isOnion = true; TrustManager[] trustAllCerts = new TrustManager[]{ @@ -46,9 +46,11 @@ public class TLSSocketFactory extends SSLSocketFactory { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } + public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) { } + public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) { } @@ -61,11 +63,11 @@ public class TLSSocketFactory extends SSLSocketFactory { } - public SSLContext getSSLContext(){ + public SSLContext getSSLContext() { return this.sslContext; } - public SSLEngine getSSLEngine(){ + public SSLEngine getSSLEngine() { return this.sslContext.createSSLEngine(); } @@ -110,19 +112,20 @@ public class TLSSocketFactory extends SSLSocketFactory { } private Socket enableTLSOnSocket(Socket socket) { - if((socket instanceof SSLSocket)) { - if( !isOnion){ + if ((socket instanceof SSLSocket)) { + if (!isOnion) { boolean security_provider = false; try { SharedPreferences sharedpreferences = MainApplication.getApp().getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); security_provider = sharedpreferences.getBoolean(Helper.SET_SECURITY_PROVIDER, true); - }catch (Exception ignored){} - if( security_provider) - ((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2", "TLSv1.3"}); + } catch (Exception ignored) { + } + if (security_provider) + ((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1.1", "TLSv1.2", "TLSv1.3"}); else - ((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"}); - }else{ - ((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2",}); + ((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1.1", "TLSv1.2"}); + } else { + ((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1.1", "TLSv1.2",}); } } return socket; diff --git a/app/src/main/java/app/fedilab/android/client/Tls12SocketFactory.java b/app/src/main/java/app/fedilab/android/client/Tls12SocketFactory.java index 79aa20022..0b1161690 100644 --- a/app/src/main/java/app/fedilab/android/client/Tls12SocketFactory.java +++ b/app/src/main/java/app/fedilab/android/client/Tls12SocketFactory.java @@ -13,6 +13,7 @@ import javax.net.ssl.SSLSocketFactory; *

* For some reason, android supports TLS v1.2 from API 16, but enables it by * default only from API 20. + * * @link https://developer.android.com/reference/javax/net/ssl/SSLSocket.html * @see SSLSocketFactory */ diff --git a/app/src/main/java/app/fedilab/android/drawers/AccountSearchDevAdapter.java b/app/src/main/java/app/fedilab/android/drawers/AccountSearchDevAdapter.java index 35631da5a..b6192a6ac 100644 --- a/app/src/main/java/app/fedilab/android/drawers/AccountSearchDevAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/AccountSearchDevAdapter.java @@ -20,8 +20,11 @@ import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; + import com.google.android.material.floatingactionbutton.FloatingActionButton; + import androidx.core.content.ContextCompat; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -46,7 +49,6 @@ import app.fedilab.android.asynctasks.PostActionAsyncTask; import app.fedilab.android.interfaces.OnPostActionInterface; - /** * Created by Thomas on 03/09/2017. * Adapter for accounts from web @@ -58,12 +60,11 @@ public class AccountSearchDevAdapter extends BaseAdapter implements OnPostAction private Context context; private ViewHolder holder; - public AccountSearchDevAdapter(List accounts){ + public AccountSearchDevAdapter(List accounts) { this.accounts = accounts; } - @Override public int getCount() { return accounts.size(); @@ -101,17 +102,17 @@ public class AccountSearchDevAdapter extends BaseAdapter implements OnPostAction } //Redraws icon for locked accounts final float scale = context.getResources().getDisplayMetrics().density; - if( account.isLocked()){ + if (account.isLocked()) { Drawable img = ContextCompat.getDrawable(context, R.drawable.ic_lock_outline); assert img != null; - img.setBounds(0,0,(int) (20 * scale + 0.5f),(int) (20 * scale + 0.5f)); - holder.account_dn.setCompoundDrawables( null, null, img, null); - }else{ - holder.account_dn.setCompoundDrawables( null, null, null, null); + img.setBounds(0, 0, (int) (20 * scale + 0.5f), (int) (20 * scale + 0.5f)); + holder.account_dn.setCompoundDrawables(null, null, img, null); + } else { + holder.account_dn.setCompoundDrawables(null, null, null, null); } - if( !account.getSocial().contains("OPENCOLLECTIVE")) { + if (!account.getSocial().contains("OPENCOLLECTIVE")) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { holder.account_dn.setText(Helper.shortnameToUnicode(account.getDisplay_name(), true)); holder.account_un.setText(String.format("@%s", account.getAcct())); @@ -119,31 +120,31 @@ public class AccountSearchDevAdapter extends BaseAdapter implements OnPostAction holder.account_dn.setText(Helper.shortnameToUnicode(account.getDisplay_name(), true)); holder.account_un.setText(String.format("@%s", account.getAcct())); } - if( account.isFollowing()){ + if (account.isFollowing()) { holder.account_follow.hide(); - }else{ + } else { holder.account_follow.show(); } - }else{ + } else { holder.account_dn.setText(Helper.shortnameToUnicode(account.getDisplay_name(), true)); holder.account_un.setText(account.getAcct()); holder.account_follow.hide(); } - Helper.changeDrawableColor(context, R.drawable.ic_lock_outline,R.color.mastodonC4); + Helper.changeDrawableColor(context, R.drawable.ic_lock_outline, R.color.mastodonC4); //Profile picture - if( account.getAvatar().startsWith("http")) { + if (account.getAvatar().startsWith("http")) { Glide.with(holder.account_pp.getContext()) .load(account.getAvatar()) .into(holder.account_pp); - }else if(account.getSocial().contains("OPENCOLLECTIVE")){ + } else if (account.getSocial().contains("OPENCOLLECTIVE")) { Glide.with(holder.account_pp.getContext()) .load(R.drawable.missing) .into(holder.account_pp); } - if( !account.getSocial().contains("OPENCOLLECTIVE")) { + if (!account.getSocial().contains("OPENCOLLECTIVE")) { holder.account_follow.setOnClickListener(new View.OnClickListener() { @Override @@ -162,11 +163,11 @@ public class AccountSearchDevAdapter extends BaseAdapter implements OnPostAction context.startActivity(intent); } }); - }else{ + } else { holder.acccount_container.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - Helper.openBrowser(context, account.getUrl()); + Helper.openBrowser(context, account.getUrl()); } }); } @@ -176,13 +177,13 @@ public class AccountSearchDevAdapter extends BaseAdapter implements OnPostAction @Override public void onPostAction(int statusCode, API.StatusAction statusAction, String userId, Error error) { - if( error != null){ - Toasty.error(context, error.getError(),Toast.LENGTH_LONG).show(); + if (error != null) { + Toasty.error(context, error.getError(), Toast.LENGTH_LONG).show(); holder.account_follow.setEnabled(true); return; } - for( Account account: accounts){ - if(account.getId().equals(userId)) { + for (Account account : accounts) { + if (account.getId().equals(userId)) { account.setFollowing(true); notifyDataSetChanged(); break; diff --git a/app/src/main/java/app/fedilab/android/drawers/AccountsAdminListAdapter.java b/app/src/main/java/app/fedilab/android/drawers/AccountsAdminListAdapter.java index ec9b8f597..461e4a6f1 100644 --- a/app/src/main/java/app/fedilab/android/drawers/AccountsAdminListAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/AccountsAdminListAdapter.java @@ -47,14 +47,12 @@ public class AccountsAdminListAdapter extends RecyclerView.Adapter implements On private Context context; private AccountsAdminListAdapter accountsAdminListAdapter; - public AccountsAdminListAdapter(List accountAdmins){ + public AccountsAdminListAdapter(List accountAdmins) { this.accountAdmins = accountAdmins; this.accountsAdminListAdapter = this; } - - @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { @@ -71,26 +69,26 @@ public class AccountsAdminListAdapter extends RecyclerView.Adapter implements On Account.makeAccountNameEmoji(context, AccountsAdminListAdapter.this, account); - if( account.getdisplayNameSpan() == null || account.getdisplayNameSpan().toString().trim().equals("")) { - if( account.getDisplay_name() != null && !account.getDisplay_name().trim().equals("")) + if (account.getdisplayNameSpan() == null || account.getdisplayNameSpan().toString().trim().equals("")) { + if (account.getDisplay_name() != null && !account.getDisplay_name().trim().equals("")) holder.account_dn.setText(Helper.shortnameToUnicode(account.getDisplay_name(), true)); else if (account.getDisplay_name() != null) { - holder.account_dn.setText(account.getDisplay_name().replace("@","")); + holder.account_dn.setText(account.getDisplay_name().replace("@", "")); } - }else - holder.account_dn.setText( account.getdisplayNameSpan(), TextView.BufferType.SPANNABLE); + } else + holder.account_dn.setText(account.getdisplayNameSpan(), TextView.BufferType.SPANNABLE); - if( account.getdisplayNameSpan() == null || account.getdisplayNameSpan().toString().trim().equals("")) { - if( account.getDisplay_name() != null && !account.getDisplay_name().trim().equals("")) + if (account.getdisplayNameSpan() == null || account.getdisplayNameSpan().toString().trim().equals("")) { + if (account.getDisplay_name() != null && !account.getDisplay_name().trim().equals("")) holder.account_dn.setText(Helper.shortnameToUnicode(account.getDisplay_name(), true)); else if (account.getDisplay_name() != null) { - holder.account_dn.setText(account.getDisplay_name().replace("@","")); + holder.account_dn.setText(account.getDisplay_name().replace("@", "")); } - }else - holder.account_dn.setText( account.getdisplayNameSpan(), TextView.BufferType.SPANNABLE); - holder.account_un.setText(String.format("@%s",account.getUsername())); + } else + holder.account_dn.setText(account.getdisplayNameSpan(), TextView.BufferType.SPANNABLE); + holder.account_un.setText(String.format("@%s", account.getUsername())); holder.account_ac.setText(account.getAcct()); - if( account.getDisplay_name().equals(account.getAcct())) + if (account.getDisplay_name().equals(account.getAcct())) holder.account_ac.setVisibility(View.GONE); else holder.account_ac.setVisibility(View.VISIBLE); @@ -99,7 +97,7 @@ public class AccountsAdminListAdapter extends RecyclerView.Adapter implements On Helper.loadGiF(context, account.getAvatar(), holder.account_pp); - holder.main_container.setOnClickListener(view ->{ + holder.main_container.setOnClickListener(view -> { Intent intent = new Intent(context, AccountReportActivity.class); Bundle b = new Bundle(); b.putParcelable("targeted_account", accountAdmin); @@ -118,8 +116,8 @@ public class AccountsAdminListAdapter extends RecyclerView.Adapter implements On return accountAdmins.size(); } - private AccountAdmin getItemAt(int position){ - if( accountAdmins.size() > position) + private AccountAdmin getItemAt(int position) { + if (accountAdmins.size() > position) return accountAdmins.get(position); else return null; @@ -130,7 +128,7 @@ public class AccountsAdminListAdapter extends RecyclerView.Adapter implements On notifyAccountChanged(account); } - private void notifyAccountChanged(Account account){ + private void notifyAccountChanged(Account account) { for (int i = 0; i < accountsAdminListAdapter.getItemCount(); i++) { //noinspection ConstantConditions if (accountsAdminListAdapter.getItemAt(i) != null && accountsAdminListAdapter.getItemAt(i).getAccount().getId().equals(account.getId())) { @@ -143,7 +141,7 @@ public class AccountsAdminListAdapter extends RecyclerView.Adapter implements On } - private class ViewHolder extends RecyclerView.ViewHolder{ + private class ViewHolder extends RecyclerView.ViewHolder { ImageView account_pp; TextView account_ac; TextView account_dn; diff --git a/app/src/main/java/app/fedilab/android/drawers/AccountsFollowRequestAdapter.java b/app/src/main/java/app/fedilab/android/drawers/AccountsFollowRequestAdapter.java index 225b60203..f72020120 100644 --- a/app/src/main/java/app/fedilab/android/drawers/AccountsFollowRequestAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/AccountsFollowRequestAdapter.java @@ -21,8 +21,10 @@ import android.content.SharedPreferences; import android.graphics.PorterDuff; import android.os.AsyncTask; import android.os.Bundle; + import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.RecyclerView; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -30,10 +32,14 @@ import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; + import com.bumptech.glide.Glide; + import org.jetbrains.annotations.NotNull; + import java.util.ArrayList; import java.util.List; + import app.fedilab.android.client.API; import app.fedilab.android.client.Entities.Account; import app.fedilab.android.client.Entities.Error; @@ -55,7 +61,7 @@ public class AccountsFollowRequestAdapter extends RecyclerView.Adapter implement private Context context; private AccountsFollowRequestAdapter accountsFollowRequestAdapter; - public AccountsFollowRequestAdapter(List accounts){ + public AccountsFollowRequestAdapter(List accounts) { this.accounts = accounts; accountsFollowRequestAdapter = this; } @@ -76,7 +82,7 @@ public class AccountsFollowRequestAdapter extends RecyclerView.Adapter implement final Account account = accounts.get(position); holder.btn_authorize.getBackground().setColorFilter(ContextCompat.getColor(context, R.color.green_1), PorterDuff.Mode.MULTIPLY); holder.btn_reject.getBackground().setColorFilter(ContextCompat.getColor(context, R.color.red_1), PorterDuff.Mode.MULTIPLY); - holder.account_dn.setText(Helper.shortnameToUnicode(account.getDisplay_name(),true)); + holder.account_dn.setText(Helper.shortnameToUnicode(account.getDisplay_name(), true)); holder.account_un.setText(account.getAcct()); //Profile picture Glide.with(holder.account_pp.getContext()) @@ -114,7 +120,7 @@ public class AccountsFollowRequestAdapter extends RecyclerView.Adapter implement }); final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); final int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if( theme == Helper.THEME_LIGHT) { + if (theme == Helper.THEME_LIGHT) { holder.btn_reject.setTextColor(ContextCompat.getColor(context, R.color.white)); holder.btn_authorize.setTextColor(ContextCompat.getColor(context, R.color.white)); } @@ -130,7 +136,7 @@ public class AccountsFollowRequestAdapter extends RecyclerView.Adapter implement return accounts.size(); } - private void openAccountDetails(Account account){ + private void openAccountDetails(Account account) { Intent intent = new Intent(context, ShowAccountActivity.class); Bundle b = new Bundle(); b.putParcelable("account", account); @@ -140,16 +146,16 @@ public class AccountsFollowRequestAdapter extends RecyclerView.Adapter implement @Override public void onPostAction(int statusCode, API.StatusAction statusAction, String userId, Error error) { - if( error != null){ - Toasty.error(context, error.getError(),Toast.LENGTH_LONG).show(); + if (error != null) { + Toasty.error(context, error.getError(), Toast.LENGTH_LONG).show(); return; } Helper.manageMessageStatusCode(context, statusCode, statusAction); //When authorizing or rejecting an account, this account is removed from the list List accountToRemove = new ArrayList<>(); - if( statusAction == API.StatusAction.AUTHORIZE || statusAction == API.StatusAction.REJECT){ - for(Account account: accounts){ - if( account.getId().equals(userId)) + if (statusAction == API.StatusAction.AUTHORIZE || statusAction == API.StatusAction.REJECT) { + for (Account account : accounts) { + if (account.getId().equals(userId)) accountToRemove.add(account); } accounts.removeAll(accountToRemove); diff --git a/app/src/main/java/app/fedilab/android/drawers/AccountsInAListAdapter.java b/app/src/main/java/app/fedilab/android/drawers/AccountsInAListAdapter.java index b16eaa9e5..134561586 100644 --- a/app/src/main/java/app/fedilab/android/drawers/AccountsInAListAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/AccountsInAListAdapter.java @@ -18,7 +18,9 @@ import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; + import com.google.android.material.floatingactionbutton.FloatingActionButton; + import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; @@ -58,19 +60,19 @@ public class AccountsInAListAdapter extends RecyclerView.Adapter implements OnLi private String listId; private List allAccount = new ArrayList<>(); - public enum type{ + public enum type { CURRENT, SEARCH } - public AccountsInAListAdapter(type actionType, String listId, List accounts){ + public AccountsInAListAdapter(type actionType, String listId, List accounts) { this.accounts = accounts; this.accountsInAListAdapter = this; this.actionType = actionType; this.listId = listId; } - public AccountsInAListAdapter(type actionType, String listId, List allAccount, List accountSearch){ + public AccountsInAListAdapter(type actionType, String listId, List allAccount, List accountSearch) { this.accounts = accountSearch; this.accountsInAListAdapter = this; this.actionType = actionType; @@ -93,38 +95,37 @@ public class AccountsInAListAdapter extends RecyclerView.Adapter implements OnLi final Account account = accounts.get(position); - holder.account_un.setText(Helper.shortnameToUnicode(account.getDisplay_name(), true)); holder.account_ac.setText(account.getAcct()); - if( account.getDisplay_name().equals(account.getAcct())) + if (account.getDisplay_name().equals(account.getAcct())) holder.account_ac.setVisibility(View.GONE); else holder.account_ac.setVisibility(View.VISIBLE); //Profile picture Helper.loadGiF(context, account.getAvatar(), holder.account_pp); - if( actionType == type.CURRENT){ + if (actionType == type.CURRENT) { holder.account_action.setImageResource(R.drawable.ic_close); holder.account_action.setContentDescription(context.getString(R.string.remove_account)); - }else if(actionType == type.SEARCH && !isInList(account)){ + } else if (actionType == type.SEARCH && !isInList(account)) { holder.account_action.setImageResource(R.drawable.ic_add); holder.account_action.setContentDescription(context.getString(R.string.add_account)); - }else if (actionType == type.SEARCH){ + } else if (actionType == type.SEARCH) { holder.account_action.setImageResource(R.drawable.ic_close); holder.account_action.setContentDescription(context.getString(R.string.remove_account)); } holder.account_action.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { - if( actionType == type.CURRENT){ + if (actionType == type.CURRENT) { new ManageListsAsyncTask(context, ManageListsAsyncTask.action.DELETE_USERS, new String[]{account.getId()}, null, listId, null, AccountsInAListAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); remove(account); accountsInAListAdapter.notifyDataSetChanged(); - }else if(actionType == type.SEARCH && !isInList(account)){ + } else if (actionType == type.SEARCH && !isInList(account)) { new ManageListsAsyncTask(context, ManageListsAsyncTask.action.ADD_USERS, new String[]{account.getId()}, null, listId, null, AccountsInAListAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - ((ManageAccountsInListActivity)context).addAccount(account); + ((ManageAccountsInListActivity) context).addAccount(account); - }else if( actionType == type.SEARCH){ + } else if (actionType == type.SEARCH) { new ManageListsAsyncTask(context, ManageListsAsyncTask.action.DELETE_USERS, new String[]{account.getId()}, null, listId, null, AccountsInAListAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); remove(account); accountsInAListAdapter.notifyDataSetChanged(); @@ -144,10 +145,10 @@ public class AccountsInAListAdapter extends RecyclerView.Adapter implements OnLi }); } - private void remove(Account account){ + private void remove(Account account) { int position = 0; - for(Account act: allAccount){ - if( account.getId().equals(act.getId()) ){ + for (Account act : allAccount) { + if (account.getId().equals(act.getId())) { allAccount.remove(position); return; } @@ -155,8 +156,8 @@ public class AccountsInAListAdapter extends RecyclerView.Adapter implements OnLi } } - private boolean isInList(Account account){ - if( allAccount != null && allAccount.size() > 0) { + private boolean isInList(Account account) { + if (allAccount != null && allAccount.size() > 0) { for (Account act : allAccount) { if (act.getId().equals(account.getId())) { return true; @@ -169,9 +170,9 @@ public class AccountsInAListAdapter extends RecyclerView.Adapter implements OnLi @Override public void onActionDone(ManageListsAsyncTask.action actionType, APIResponse apiResponse, int statusCode) { - if( actionType == ManageListsAsyncTask.action.DELETE_USERS && statusCode != 200){ - Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_SHORT).show(); - } + if (actionType == ManageListsAsyncTask.action.DELETE_USERS && statusCode != 200) { + Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_SHORT).show(); + } } @Override @@ -185,14 +186,13 @@ public class AccountsInAListAdapter extends RecyclerView.Adapter implements OnLi } - - - private class ViewHolder extends RecyclerView.ViewHolder{ + private class ViewHolder extends RecyclerView.ViewHolder { ImageView account_pp; TextView account_ac; TextView account_un; - FloatingActionButton account_action; + FloatingActionButton account_action; LinearLayout account_container; + ViewHolder(View itemView) { super(itemView); account_container = itemView.findViewById(R.id.account_container); diff --git a/app/src/main/java/app/fedilab/android/drawers/AccountsListAdapter.java b/app/src/main/java/app/fedilab/android/drawers/AccountsListAdapter.java index 7c54a7f11..254f6c5b8 100644 --- a/app/src/main/java/app/fedilab/android/drawers/AccountsListAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/AccountsListAdapter.java @@ -23,12 +23,15 @@ import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; + import androidx.annotation.NonNull; + import com.google.android.material.floatingactionbutton.FloatingActionButton; import androidx.appcompat.app.AlertDialog; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.RecyclerView; + import android.text.Html; import android.text.util.Linkify; import android.view.LayoutInflater; @@ -73,7 +76,7 @@ public class AccountsListAdapter extends RecyclerView.Adapter implements OnPostA private AccountsListAdapter accountsListAdapter; private String targetedId; - public AccountsListAdapter(RetrieveAccountsAsyncTask.Type action, String targetedId, List accounts){ + public AccountsListAdapter(RetrieveAccountsAsyncTask.Type action, String targetedId, List accounts) { this.accounts = accounts; this.action = action; this.accountsListAdapter = this; @@ -81,8 +84,6 @@ public class AccountsListAdapter extends RecyclerView.Adapter implements OnPostA } - - @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { @@ -98,7 +99,7 @@ public class AccountsListAdapter extends RecyclerView.Adapter implements OnPostA API.StatusAction doAction = null; - if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { holder.account_mute_notification.hide(); if (action == RetrieveAccountsAsyncTask.Type.BLOCKED) account.setFollowType(Account.followAction.BLOCK); @@ -107,7 +108,7 @@ public class AccountsListAdapter extends RecyclerView.Adapter implements OnPostA if (action == RetrieveAccountsAsyncTask.Type.CHANNELS) account.setFollowType(Account.followAction.NOT_FOLLOW); - holder.account_follow.setBackgroundTintList(ColorStateList.valueOf( ContextCompat.getColor(context, R.color.mastodonC4))); + holder.account_follow.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(context, R.color.mastodonC4))); if (account.getFollowType() == Account.followAction.NOTHING) { holder.account_follow.hide(); holder.account_follow_request.setVisibility(View.GONE); @@ -117,7 +118,7 @@ public class AccountsListAdapter extends RecyclerView.Adapter implements OnPostA holder.account_follow_request.setVisibility(View.VISIBLE); doAction = null; } else if (account.getFollowType() == Account.followAction.FOLLOW) { - holder.account_follow.setBackgroundTintList(ColorStateList.valueOf( ContextCompat.getColor(context, R.color.unfollow))); + holder.account_follow.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(context, R.color.unfollow))); holder.account_follow.setImageResource(R.drawable.ic_user_times); doAction = API.StatusAction.UNFOLLOW; holder.account_follow.show(); @@ -174,22 +175,22 @@ public class AccountsListAdapter extends RecyclerView.Adapter implements OnPostA } }); } - }else { + } else { holder.account_follow.hide(); } - if( !account.isEmojiFound()) { + if (!account.isEmojiFound()) { Account.makeAccountNameEmoji(context, AccountsListAdapter.this, account); } - if( account.getdisplayNameSpan() == null || account.getdisplayNameSpan().toString().trim().equals("")) { - if( account.getDisplay_name() != null && !account.getDisplay_name().trim().equals("")) + if (account.getdisplayNameSpan() == null || account.getdisplayNameSpan().toString().trim().equals("")) { + if (account.getDisplay_name() != null && !account.getDisplay_name().trim().equals("")) holder.account_dn.setText(Helper.shortnameToUnicode(account.getDisplay_name(), true)); else - holder.account_dn.setText(account.getUsername().replace("@","")); - }else - holder.account_dn.setText( account.getdisplayNameSpan(), TextView.BufferType.SPANNABLE); - holder.account_un.setText(String.format("@%s",account.getUsername())); + holder.account_dn.setText(account.getUsername().replace("@", "")); + } else + holder.account_dn.setText(account.getdisplayNameSpan(), TextView.BufferType.SPANNABLE); + holder.account_un.setText(String.format("@%s", account.getUsername())); holder.account_ac.setText(account.getAcct()); - if( account.getUsername().equals(account.getAcct())) + if (account.getUsername().equals(account.getAcct())) holder.account_ac.setVisibility(View.GONE); else holder.account_ac.setVisibility(View.VISIBLE); @@ -204,9 +205,9 @@ public class AccountsListAdapter extends RecyclerView.Adapter implements OnPostA holder.account_frc.setText(Helper.withSuffix(account.getFollowers_count())); //Profile picture Helper.loadGiF(context, account.getAvatar(), holder.account_pp); - if( account.isMakingAction()){ + if (account.isMakingAction()) { holder.account_follow.setEnabled(false); - }else { + } else { holder.account_follow.setEnabled(true); } //Follow button @@ -214,12 +215,12 @@ public class AccountsListAdapter extends RecyclerView.Adapter implements OnPostA holder.account_follow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - if( action != RetrieveAccountsAsyncTask.Type.CHANNELS) { + if (action != RetrieveAccountsAsyncTask.Type.CHANNELS) { if (finalDoAction != null) { - if( finalDoAction != API.StatusAction.UNFOLLOW) { + if (finalDoAction != API.StatusAction.UNFOLLOW) { account.setMakingAction(true); new PostActionAsyncTask(context, finalDoAction, account.getId(), AccountsListAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else{ + } else { final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); boolean confirm_unfollow = sharedpreferences.getBoolean(Helper.SET_UNFOLLOW_VALIDATION, true); if (confirm_unfollow) { @@ -227,9 +228,9 @@ public class AccountsListAdapter extends RecyclerView.Adapter implements OnPostA int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } AlertDialog.Builder unfollowConfirm = new AlertDialog.Builder(context, style); @@ -237,13 +238,13 @@ public class AccountsListAdapter extends RecyclerView.Adapter implements OnPostA unfollowConfirm.setMessage(account.getAcct()); unfollowConfirm.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog,int which) { + public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); unfollowConfirm.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog,int which) { + public void onClick(DialogInterface dialog, int which) { account.setMakingAction(true); new PostActionAsyncTask(context, finalDoAction, account.getId(), AccountsListAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); dialog.dismiss(); @@ -257,12 +258,12 @@ public class AccountsListAdapter extends RecyclerView.Adapter implements OnPostA } } - }else { + } else { CrossActions.followPeertubeChannel(context, account, AccountsListAdapter.this); } } }); - if( action != RetrieveAccountsAsyncTask.Type.GROUPS ) { + if (action != RetrieveAccountsAsyncTask.Type.GROUPS) { holder.account_pp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -286,7 +287,7 @@ public class AccountsListAdapter extends RecyclerView.Adapter implements OnPostA } }); - }else{ + } else { holder.account_container.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -310,8 +311,8 @@ public class AccountsListAdapter extends RecyclerView.Adapter implements OnPostA return accounts.size(); } - private Account getItemAt(int position){ - if( accounts.size() > position) + private Account getItemAt(int position) { + if (accounts.size() > position) return accounts.get(position); else return null; @@ -319,28 +320,28 @@ public class AccountsListAdapter extends RecyclerView.Adapter implements OnPostA @Override public void onPostAction(int statusCode, API.StatusAction statusAction, String targetedId, Error error) { - if( error != null){ - Toasty.error(context, error.getError(),Toast.LENGTH_LONG).show(); + if (error != null) { + Toasty.error(context, error.getError(), Toast.LENGTH_LONG).show(); return; } Helper.manageMessageStatusCode(context, statusCode, statusAction); //When unmuting or unblocking an account, it is removed from the list List accountsToRemove = new ArrayList<>(); - if( statusAction == API.StatusAction.UNMUTE || statusAction == API.StatusAction.UNBLOCK){ - for(Account account: accounts){ - if( account.getId().equals(targetedId)) + if (statusAction == API.StatusAction.UNMUTE || statusAction == API.StatusAction.UNBLOCK) { + for (Account account : accounts) { + if (account.getId().equals(targetedId)) accountsToRemove.add(account); } accounts.removeAll(accountsToRemove); accountsListAdapter.notifyDataSetChanged(); } - if( statusAction == API.StatusAction.FOLLOW){ - if( action == RetrieveAccountsAsyncTask.Type.CHANNELS){ + if (statusAction == API.StatusAction.FOLLOW) { + if (action == RetrieveAccountsAsyncTask.Type.CHANNELS) { SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); new InstancesDAO(context, db).insertInstance(accounts.get(0).getAcct().split("@")[1], accounts.get(0).getAcct().split("@")[0], "PEERTUBE_CHANNEL"); - }else{ - for(Account account: accounts){ - if( account.getId().equals(targetedId)) { + } else { + for (Account account : accounts) { + if (account.getId().equals(targetedId)) { account.setFollowType(Account.followAction.FOLLOW); account.setMakingAction(false); } @@ -348,9 +349,9 @@ public class AccountsListAdapter extends RecyclerView.Adapter implements OnPostA accountsListAdapter.notifyDataSetChanged(); } } - if( statusAction == API.StatusAction.UNFOLLOW){ - for(Account account: accounts){ - if( account.getId().equals(targetedId)) { + if (statusAction == API.StatusAction.UNFOLLOW) { + for (Account account : accounts) { + if (account.getId().equals(targetedId)) { account.setFollowType(Account.followAction.NOT_FOLLOW); account.setMakingAction(false); } @@ -359,7 +360,7 @@ public class AccountsListAdapter extends RecyclerView.Adapter implements OnPostA } } - public void notifyAccountChanged(Account account){ + public void notifyAccountChanged(Account account) { for (int i = 0; i < accountsListAdapter.getItemCount(); i++) { //noinspection ConstantConditions if (accountsListAdapter.getItemAt(i) != null && accountsListAdapter.getItemAt(i).getId().equals(account.getId())) { @@ -378,7 +379,7 @@ public class AccountsListAdapter extends RecyclerView.Adapter implements OnPostA } - private class ViewHolder extends RecyclerView.ViewHolder{ + private class ViewHolder extends RecyclerView.ViewHolder { ImageView account_pp; TextView account_ac; TextView account_dn; diff --git a/app/src/main/java/app/fedilab/android/drawers/AccountsReplyAdapter.java b/app/src/main/java/app/fedilab/android/drawers/AccountsReplyAdapter.java index ff6aded53..27f92ae17 100644 --- a/app/src/main/java/app/fedilab/android/drawers/AccountsReplyAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/AccountsReplyAdapter.java @@ -16,7 +16,9 @@ package app.fedilab.android.drawers; import android.content.Context; + import androidx.annotation.NonNull; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -40,19 +42,19 @@ import app.fedilab.android.activities.TootActivity; * Created by Thomas on 25/10/2017. * Adapter for accounts when replying */ -public class AccountsReplyAdapter extends BaseAdapter{ +public class AccountsReplyAdapter extends BaseAdapter { private List accounts; private LayoutInflater layoutInflater; private boolean[] checked; private Context context; - public AccountsReplyAdapter(List accounts, boolean[] checked){ + public AccountsReplyAdapter(List accounts, boolean[] checked) { this.accounts = accounts; this.checked = checked; } - public AccountsReplyAdapter(List accounts, List checked){ + public AccountsReplyAdapter(List accounts, List checked) { this.accounts = accounts; this.checked = new boolean[checked.size()]; int index = 0; @@ -77,7 +79,6 @@ public class AccountsReplyAdapter extends BaseAdapter{ } - @NonNull @Override public View getView(final int position, View convertView, @NonNull ViewGroup parent) { @@ -101,9 +102,10 @@ public class AccountsReplyAdapter extends BaseAdapter{ @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { try { - ((TootActivity) context).changeAccountReply(isChecked, "@"+account.getAcct()); + ((TootActivity) context).changeAccountReply(isChecked, "@" + account.getAcct()); checked[position] = isChecked; - }catch (Exception ignored){} + } catch (Exception ignored) { + } } }); holder.checkbox.setChecked(checked[position]); @@ -122,8 +124,6 @@ public class AccountsReplyAdapter extends BaseAdapter{ } - - private class ViewHolder { ImageView account_pp; TextView account_dn; diff --git a/app/src/main/java/app/fedilab/android/drawers/AccountsSearchAdapter.java b/app/src/main/java/app/fedilab/android/drawers/AccountsSearchAdapter.java index d2c2d68a1..7252663e1 100644 --- a/app/src/main/java/app/fedilab/android/drawers/AccountsSearchAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/AccountsSearchAdapter.java @@ -18,7 +18,9 @@ package app.fedilab.android.drawers; import android.content.Context; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; + import androidx.annotation.NonNull; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -48,12 +50,12 @@ import app.fedilab.android.R; */ public class AccountsSearchAdapter extends ArrayAdapter implements Filterable { - private List accounts, tempAccounts, suggestions ; + private List accounts, tempAccounts, suggestions; private LayoutInflater layoutInflater; private boolean owner; private Context context; - public AccountsSearchAdapter(Context context, List accounts){ + public AccountsSearchAdapter(Context context, List accounts) { super(context, android.R.layout.simple_list_item_1, accounts); this.accounts = accounts; this.context = context; @@ -62,7 +64,8 @@ public class AccountsSearchAdapter extends ArrayAdapter implements Filt layoutInflater = LayoutInflater.from(context); this.owner = false; } - public AccountsSearchAdapter(Context context, List accounts, boolean owner){ + + public AccountsSearchAdapter(Context context, List accounts, boolean owner) { super(context, android.R.layout.simple_list_item_1, accounts); this.accounts = accounts; this.context = context; @@ -108,16 +111,16 @@ public class AccountsSearchAdapter extends ArrayAdapter implements Filt holder = (ViewHolder) convertView.getTag(); } - if( owner) { + if (owner) { final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, null); Account currentAccount = new AccountDAO(context, db).getUniqAccount(userId, instance); - instance = (account.getInstance() !=null)?account.getInstance():currentAccount.getInstance(); + instance = (account.getInstance() != null) ? account.getInstance() : currentAccount.getInstance(); holder.account_un.setText(String.format("@%s", account.getUsername() + "@" + instance)); holder.account_dn.setVisibility(View.GONE); - }else { + } else { holder.account_un.setText(String.format("@%s", account.getAcct())); holder.account_dn.setText(Helper.shortnameToUnicode(account.getDisplay_name(), true)); holder.account_dn.setVisibility(View.VISIBLE); @@ -164,7 +167,7 @@ public class AccountsSearchAdapter extends ArrayAdapter implements Filt clear(); addAll(c); notifyDataSetChanged(); - } else{ + } else { clear(); notifyDataSetChanged(); } diff --git a/app/src/main/java/app/fedilab/android/drawers/ArtListAdapter.java b/app/src/main/java/app/fedilab/android/drawers/ArtListAdapter.java index 72e06f539..6ddd5d45a 100644 --- a/app/src/main/java/app/fedilab/android/drawers/ArtListAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/ArtListAdapter.java @@ -20,8 +20,10 @@ import android.content.Intent; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; + import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -69,7 +71,7 @@ public class ArtListAdapter extends RecyclerView.Adapter implements OnPostAction private static final int DISPLAYED_STATUS = 1; - public ArtListAdapter(List statuses){ + public ArtListAdapter(List statuses) { this.statuses = statuses; statusListAdapter = this; @@ -85,8 +87,8 @@ public class ArtListAdapter extends RecyclerView.Adapter implements OnPostAction return statuses.size(); } - private Status getItemAt(int position){ - if( statuses.size() > position) + private Status getItemAt(int position) { + if (statuses.size() > position) return statuses.get(position); else return null; @@ -94,7 +96,7 @@ public class ArtListAdapter extends RecyclerView.Adapter implements OnPostAction @Override public void onRetrieveReplies(APIResponse apiResponse) { - if( apiResponse.getError() != null || apiResponse.getStatuses() == null || apiResponse.getStatuses().size() == 0){ + if (apiResponse.getError() != null || apiResponse.getStatuses() == null || apiResponse.getStatuses().size() == 0) { return; } List modifiedStatus = apiResponse.getStatuses(); @@ -102,7 +104,7 @@ public class ArtListAdapter extends RecyclerView.Adapter implements OnPostAction } - private class ViewHolderEmpty extends RecyclerView.ViewHolder{ + private class ViewHolderEmpty extends RecyclerView.ViewHolder { ViewHolderEmpty(View itemView) { super(itemView); } @@ -114,12 +116,13 @@ public class ArtListAdapter extends RecyclerView.Adapter implements OnPostAction } - private class ViewHolderArt extends RecyclerView.ViewHolder{ + private class ViewHolderArt extends RecyclerView.ViewHolder { ImageView art_media, art_pp; TextView art_username, art_acct; LinearLayout art_author; RelativeLayout status_show_more; ImageView show_more_button_art; + ViewHolderArt(View itemView) { super(itemView); art_media = itemView.findViewById(R.id.art_media); @@ -133,10 +136,8 @@ public class ArtListAdapter extends RecyclerView.Adapter implements OnPostAction } - - - public Status getItem(int position){ - if( statuses.size() > position && position >= 0) + public Status getItem(int position) { + if (statuses.size() > position && position >= 0) return statuses.get(position); else return null; } @@ -145,11 +146,11 @@ public class ArtListAdapter extends RecyclerView.Adapter implements OnPostAction public int getItemViewType(int position) { boolean show_boosts = false; boolean show_replies = false; - if( context instanceof ShowAccountActivity){ + if (context instanceof ShowAccountActivity) { show_boosts = ((ShowAccountActivity) context).showBoosts(); show_replies = ((ShowAccountActivity) context).showReplies(); } - if( !Helper.filterToots(statuses.get(position), null,context instanceof ShowAccountActivity,show_boosts, show_replies)) + if (!Helper.filterToots(statuses.get(position), null, context instanceof ShowAccountActivity, show_boosts, show_replies)) return HIDDEN_STATUS; else return DISPLAYED_STATUS; @@ -161,20 +162,19 @@ public class ArtListAdapter extends RecyclerView.Adapter implements OnPostAction this.context = parent.getContext(); LayoutInflater layoutInflater = LayoutInflater.from(this.context); - if( viewType != HIDDEN_STATUS) + if (viewType != HIDDEN_STATUS) return new ViewHolderArt(layoutInflater.inflate(R.layout.drawer_art, parent, false)); else return new ViewHolderEmpty(layoutInflater.inflate(R.layout.drawer_empty, parent, false)); } - @SuppressLint("SetJavaScriptEnabled") @Override public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder viewHolder, int i) { final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); final String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - if( viewHolder.getItemViewType() != HIDDEN_STATUS ) { + if (viewHolder.getItemViewType() != HIDDEN_STATUS) { final ViewHolderArt holder = (ViewHolderArt) viewHolder; final Status status = statuses.get(viewHolder.getAdapterPosition()); if (!status.isClickable()) @@ -238,48 +238,43 @@ public class ArtListAdapter extends RecyclerView.Adapter implements OnPostAction } - - - - - @Override public void onPostAction(int statusCode, API.StatusAction statusAction, String targetedId, Error error) { final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - if( error != null){ - Toasty.error(context, error.getError(),Toast.LENGTH_LONG).show(); + if (error != null) { + Toasty.error(context, error.getError(), Toast.LENGTH_LONG).show(); return; } Helper.manageMessageStatusCode(context, statusCode, statusAction); //When muting or blocking an account, its status are removed from the list List statusesToRemove = new ArrayList<>(); - if( statusAction == API.StatusAction.MUTE || statusAction == API.StatusAction.BLOCK){ - for(Status status: statuses){ - if( status.getAccount().getId().equals(targetedId)) + if (statusAction == API.StatusAction.MUTE || statusAction == API.StatusAction.BLOCK) { + for (Status status : statuses) { + if (status.getAccount().getId().equals(targetedId)) statusesToRemove.add(status); } statuses.removeAll(statusesToRemove); statusListAdapter.notifyDataSetChanged(); - }else if( statusAction == API.StatusAction.UNSTATUS ){ + } else if (statusAction == API.StatusAction.UNSTATUS) { int position = 0; - for(Status status: statuses){ - if( status.getId().equals(targetedId)) { + for (Status status : statuses) { + if (status.getId().equals(targetedId)) { statuses.remove(status); statusListAdapter.notifyItemRemoved(position); SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); //Remove the status from cache also try { - new StatusCacheDAO(context, db).remove(StatusCacheDAO.ARCHIVE_CACHE,status); - }catch (Exception ignored){} + new StatusCacheDAO(context, db).remove(StatusCacheDAO.ARCHIVE_CACHE, status); + } catch (Exception ignored) { + } break; } position++; } - } - else if ( statusAction == API.StatusAction.PIN || statusAction == API.StatusAction.UNPIN ) { + } else if (statusAction == API.StatusAction.PIN || statusAction == API.StatusAction.UNPIN) { int position = 0; - for (Status status: statuses) { + for (Status status : statuses) { if (status.getId().equals(targetedId)) { if (statusAction == API.StatusAction.PIN) status.setPinned(true); @@ -291,10 +286,10 @@ public class ArtListAdapter extends RecyclerView.Adapter implements OnPostAction position++; } } - if( statusAction == API.StatusAction.PEERTUBEDELETECOMMENT){ + if (statusAction == API.StatusAction.PEERTUBEDELETECOMMENT) { int position = 0; - for(Status status: statuses){ - if( status.getId().equals(targetedId)) { + for (Status status : statuses) { + if (status.getId().equals(targetedId)) { statuses.remove(status); statusListAdapter.notifyItemRemoved(position); break; @@ -304,7 +299,7 @@ public class ArtListAdapter extends RecyclerView.Adapter implements OnPostAction } } - public void notifyStatusChanged(Status status){ + public void notifyStatusChanged(Status status) { for (int i = 0; i < statusListAdapter.getItemCount(); i++) { //noinspection ConstantConditions if (statusListAdapter.getItemAt(i) != null && statusListAdapter.getItemAt(i).getId().equals(status.getId())) { @@ -316,7 +311,7 @@ public class ArtListAdapter extends RecyclerView.Adapter implements OnPostAction } } - public void notifyStatusWithActionChanged(Status status){ + public void notifyStatusWithActionChanged(Status status) { for (int i = 0; i < statusListAdapter.getItemCount(); i++) { //noinspection ConstantConditions if (statusListAdapter.getItemAt(i) != null && statusListAdapter.getItemAt(i).getId().equals(status.getId())) { @@ -332,11 +327,11 @@ public class ArtListAdapter extends RecyclerView.Adapter implements OnPostAction @Override public void onRetrieveEmoji(Status status, boolean fromTranslation) { - if( status != null) { - if( !fromTranslation) { - status.setEmojiFound(true); - }else { - status.setEmojiTranslateFound(true); + if (status != null) { + if (!fromTranslation) { + status.setEmojiFound(true); + } else { + status.setEmojiTranslateFound(true); } notifyStatusChanged(status); } diff --git a/app/src/main/java/app/fedilab/android/drawers/ConversationDecoration.java b/app/src/main/java/app/fedilab/android/drawers/ConversationDecoration.java index d54d1ff0f..aec6cebb6 100644 --- a/app/src/main/java/app/fedilab/android/drawers/ConversationDecoration.java +++ b/app/src/main/java/app/fedilab/android/drawers/ConversationDecoration.java @@ -19,9 +19,11 @@ import android.content.Context; import android.content.SharedPreferences; import android.graphics.Canvas; import android.graphics.drawable.Drawable; + import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.RecyclerView; + import android.view.View; import app.fedilab.android.client.Entities.Status; @@ -34,20 +36,20 @@ import static app.fedilab.android.drawers.StatusListAdapter.FOCUSED_STATUS; * Created by Thomas on 08/09/2018. * Adapter for thread decoration */ -public class ConversationDecoration extends RecyclerView.ItemDecoration{ +public class ConversationDecoration extends RecyclerView.ItemDecoration { private Drawable divider; private Context context; private boolean compactMode, consoleMode; - public ConversationDecoration(Context context, int theme){ + public ConversationDecoration(Context context, int theme) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - if( theme == Helper.THEME_BLACK) - divider = ContextCompat.getDrawable(context,R.drawable.line_divider_black); - else if(theme == Helper.THEME_DARK) - divider = ContextCompat.getDrawable(context,R.drawable.line_divider_dark); - else if(theme == Helper.THEME_LIGHT) - divider = ContextCompat.getDrawable(context,R.drawable.line_divider_light); + if (theme == Helper.THEME_BLACK) + divider = ContextCompat.getDrawable(context, R.drawable.line_divider_black); + else if (theme == Helper.THEME_DARK) + divider = ContextCompat.getDrawable(context, R.drawable.line_divider_dark); + else if (theme == Helper.THEME_LIGHT) + divider = ContextCompat.getDrawable(context, R.drawable.line_divider_light); this.context = context; this.compactMode = sharedpreferences.getBoolean(Helper.SET_COMPACT_MODE, false); @@ -59,15 +61,15 @@ public class ConversationDecoration extends RecyclerView.ItemDecoration{ int leftSide; - if( consoleMode) + if (consoleMode) leftSide = (int) Helper.convertDpToPixel(6, context); - else if( compactMode) + else if (compactMode) leftSide = (int) Helper.convertDpToPixel(3, context); else leftSide = (int) Helper.convertDpToPixel(28, context); int left = parent.getPaddingLeft() + leftSide; - int right = left + (int)Helper.convertDpToPixel(4, context); + int right = left + (int) Helper.convertDpToPixel(4, context); int childCount = parent.getChildCount(); int offSet = (int) Helper.convertDpToPixel(30, context); @@ -82,27 +84,27 @@ public class ConversationDecoration extends RecyclerView.ItemDecoration{ Status status = adapter.getItem(position); int top, bottom; - if( status != null){ + if (status != null) { int itemViewType = status.getItemViewType(); Status statusBefore = null; - if( itemViewType != FOCUSED_STATUS || position == 0){ - if( position > 0) + if (itemViewType != FOCUSED_STATUS || position == 0) { + if (position > 0) statusBefore = adapter.getItem(position - 1); - top = (statusBefore != null && statusBefore.getId().equals(status.getIn_reply_to_id()))? - child.getTop(): (child.getTop() + offSet); + top = (statusBefore != null && statusBefore.getId().equals(status.getIn_reply_to_id())) ? + child.getTop() : (child.getTop() + offSet); Status statusAfter = null; - if( adapter.getItemCount() > position+1) + if (adapter.getItemCount() > position + 1) statusAfter = adapter.getItem(position + 1); - bottom = (statusAfter != null && status.getId().equals(statusAfter.getIn_reply_to_id()) )? - child.getBottom():child.getTop()+offSet; - if( position == 0 && childCount > 1) - top = bottom - (int)Helper.convertDpToPixel(14, context); - if( position == 0 && childCount <= 1 ) + bottom = (statusAfter != null && status.getId().equals(statusAfter.getIn_reply_to_id())) ? + child.getBottom() : child.getTop() + offSet; + if (position == 0 && childCount > 1) + top = bottom - (int) Helper.convertDpToPixel(14, context); + if (position == 0 && childCount <= 1) top = bottom; - }else{ + } else { top = child.getTop(); - bottom = top + (int)Helper.convertDpToPixel(14, context); + bottom = top + (int) Helper.convertDpToPixel(14, context); } divider.setBounds(left, top, right, bottom); diff --git a/app/src/main/java/app/fedilab/android/drawers/CustomEmojiAdapter.java b/app/src/main/java/app/fedilab/android/drawers/CustomEmojiAdapter.java index 81218b153..237229ab8 100644 --- a/app/src/main/java/app/fedilab/android/drawers/CustomEmojiAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/CustomEmojiAdapter.java @@ -16,6 +16,7 @@ package app.fedilab.android.drawers; import android.content.Context; + import androidx.annotation.NonNull; import androidx.annotation.Nullable; @@ -90,8 +91,7 @@ public class CustomEmojiAdapter extends ArrayAdapter { } - - if( !emoji.isDrawableFound() ) { + if (!emoji.isDrawableFound()) { emoji.setDrawableFound(true); Glide.with(context) .asFile() @@ -104,7 +104,7 @@ public class CustomEmojiAdapter extends ArrayAdapter { Drawable resource; SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); boolean disableAnimatedEmoji = sharedpreferences.getBoolean(Helper.SET_DISABLE_ANIMATED_EMOJI, false); - if( !disableAnimatedEmoji) { + if (!disableAnimatedEmoji) { if (GifParser.isGif(resourceFile.getAbsolutePath())) { resource = GifDrawable.fromFile(resourceFile.getAbsolutePath()); emoji.setDrawable(resource); @@ -116,14 +116,14 @@ public class CustomEmojiAdapter extends ArrayAdapter { emoji.setDrawable(resource); } - }else{ + } else { resource = Drawable.createFromPath(resourceFile.getAbsolutePath()); emoji.setDrawable(resource); } customEmojiAdapter.notifyDataSetChanged(); } }); - }else{ + } else { imageView.setImageDrawable(emoji.getDrawable()); } return convertView; diff --git a/app/src/main/java/app/fedilab/android/drawers/DomainsListAdapter.java b/app/src/main/java/app/fedilab/android/drawers/DomainsListAdapter.java index 2bd113e46..0a97e64fe 100644 --- a/app/src/main/java/app/fedilab/android/drawers/DomainsListAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/DomainsListAdapter.java @@ -18,9 +18,11 @@ import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.AsyncTask; + import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.recyclerview.widget.RecyclerView; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -52,7 +54,7 @@ public class DomainsListAdapter extends RecyclerView.Adapter implements OnRetrie private DomainsListAdapter domainsListAdapter; private RelativeLayout textviewNoAction; - public DomainsListAdapter(List domains, RelativeLayout textviewNoAction){ + public DomainsListAdapter(List domains, RelativeLayout textviewNoAction) { this.domains = domains; this.domainsListAdapter = this; this.textviewNoAction = textviewNoAction; @@ -73,9 +75,9 @@ public class DomainsListAdapter extends RecyclerView.Adapter implements OnRetrie final String domain = domains.get(position); final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if( theme == Helper.THEME_DARK){ + if (theme == Helper.THEME_DARK) { Helper.changeDrawableColor(context, holder.domain_delete, R.color.dark_text); - }else{ + } else { Helper.changeDrawableColor(context, holder.domain_delete, R.color.black); } holder.domain_name.setText(domain); @@ -87,9 +89,9 @@ public class DomainsListAdapter extends RecyclerView.Adapter implements OnRetrie int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } AlertDialog.Builder builder = new AlertDialog.Builder(context, style); @@ -102,7 +104,7 @@ public class DomainsListAdapter extends RecyclerView.Adapter implements OnRetrie domains.remove(domain); domainsListAdapter.notifyItemRemoved(holder.getAdapterPosition()); new DeleteDomainsAsyncTask(context, domain, DomainsListAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - if( domains.size() == 0 && textviewNoAction != null && textviewNoAction.getVisibility() == View.GONE) + if (domains.size() == 0 && textviewNoAction != null && textviewNoAction.getVisibility() == View.GONE) textviewNoAction.setVisibility(View.VISIBLE); dialog.dismiss(); } @@ -131,7 +133,6 @@ public class DomainsListAdapter extends RecyclerView.Adapter implements OnRetrie } - @Override public void onRetrieveDomains(APIResponse apiResponse) { @@ -140,17 +141,17 @@ public class DomainsListAdapter extends RecyclerView.Adapter implements OnRetrie @Override public void onRetrieveDomainsDeleted(int response) { String message; - if( response == 200){ + if (response == 200) { message = context.getString(R.string.toast_unblock_domain); Toasty.success(context, message, Toast.LENGTH_LONG).show(); - }else{ + } else { message = context.getString(R.string.toast_error); Toasty.error(context, message, Toast.LENGTH_LONG).show(); } } - private class ViewHolder extends RecyclerView.ViewHolder{ + private class ViewHolder extends RecyclerView.ViewHolder { TextView domain_name; ImageView domain_delete; diff --git a/app/src/main/java/app/fedilab/android/drawers/DraftsListAdapter.java b/app/src/main/java/app/fedilab/android/drawers/DraftsListAdapter.java index 20ab5419b..7926bfe48 100644 --- a/app/src/main/java/app/fedilab/android/drawers/DraftsListAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/DraftsListAdapter.java @@ -22,7 +22,9 @@ import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.graphics.Typeface; import android.os.Bundle; + import androidx.appcompat.app.AlertDialog; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -48,7 +50,7 @@ import static app.fedilab.android.helper.Helper.changeDrawableColor; * Created by Thomas on 15/07/2017. * Adapter for toot drafts */ -public class DraftsListAdapter extends BaseAdapter { +public class DraftsListAdapter extends BaseAdapter { private List storedStatuses; private Context context; @@ -56,13 +58,13 @@ public class DraftsListAdapter extends BaseAdapter { private boolean clickable; private RelativeLayout textviewNoAction; - public DraftsListAdapter(List storedStatuses){ + public DraftsListAdapter(List storedStatuses) { this.storedStatuses = storedStatuses; draftsListAdapter = this; this.clickable = false; } - public DraftsListAdapter(List storedStatuses, boolean clickable, RelativeLayout textviewNoAction){ + public DraftsListAdapter(List storedStatuses, boolean clickable, RelativeLayout textviewNoAction) { this.storedStatuses = storedStatuses; draftsListAdapter = this; this.clickable = clickable; @@ -106,13 +108,13 @@ public class DraftsListAdapter extends BaseAdapter { final SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - if( this.clickable ){ + if (this.clickable) { if (draft.getStatus().getContent().length() > 300) - holder.draft_title.setText(String.format("%s…",draft.getStatus().getContent().substring(0, 299))); + holder.draft_title.setText(String.format("%s…", draft.getStatus().getContent().substring(0, 299))); else holder.draft_title.setText(draft.getStatus().getContent()); - }else { - if(draft.getStatus() != null && draft.getStatus().getContent() != null ) { + } else { + if (draft.getStatus() != null && draft.getStatus().getContent() != null) { if (draft.getStatus().getContent().length() > 20) holder.draft_title.setText(draft.getStatus().getContent().substring(0, 20)); else @@ -124,9 +126,9 @@ public class DraftsListAdapter extends BaseAdapter { //Manages theme for icon colors final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if( theme == Helper.THEME_DARK || theme == Helper.THEME_BLACK){ + if (theme == Helper.THEME_DARK || theme == Helper.THEME_BLACK) { Helper.changeDrawableColor(context, holder.draft_delete, R.color.dark_text); - }else{ + } else { Helper.changeDrawableColor(context, holder.draft_delete, R.color.black); } holder.draft_date.setText(Helper.dateToString(draft.getCreation_date())); @@ -138,9 +140,9 @@ public class DraftsListAdapter extends BaseAdapter { int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } AlertDialog.Builder builder = new AlertDialog.Builder(context, style); @@ -153,7 +155,7 @@ public class DraftsListAdapter extends BaseAdapter { new StatusStoredDAO(context, db).remove(draft.getId()); storedStatuses.remove(draft); draftsListAdapter.notifyDataSetChanged(); - if( storedStatuses.size() == 0 && textviewNoAction != null && textviewNoAction.getVisibility() == View.GONE) + if (storedStatuses.size() == 0 && textviewNoAction != null && textviewNoAction.getVisibility() == View.GONE) textviewNoAction.setVisibility(View.VISIBLE); dialog.dismiss(); } @@ -167,7 +169,7 @@ public class DraftsListAdapter extends BaseAdapter { .show(); } }); - if( clickable){ + if (clickable) { holder.drafts_container.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { diff --git a/app/src/main/java/app/fedilab/android/drawers/EmojisSearchAdapter.java b/app/src/main/java/app/fedilab/android/drawers/EmojisSearchAdapter.java index a69c1e338..4b2db09ea 100644 --- a/app/src/main/java/app/fedilab/android/drawers/EmojisSearchAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/EmojisSearchAdapter.java @@ -16,7 +16,9 @@ package app.fedilab.android.drawers; import android.content.Context; + import androidx.annotation.NonNull; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -42,10 +44,10 @@ import app.fedilab.android.R; */ public class EmojisSearchAdapter extends ArrayAdapter implements Filterable { - private List emojis, tempEmojis, suggestions ; + private List emojis, tempEmojis, suggestions; private LayoutInflater layoutInflater; - public EmojisSearchAdapter(Context context, List emojis){ + public EmojisSearchAdapter(Context context, List emojis) { super(context, android.R.layout.simple_list_item_1, emojis); this.emojis = emojis; this.tempEmojis = new ArrayList<>(emojis); @@ -85,7 +87,7 @@ public class EmojisSearchAdapter extends ArrayAdapter implements Filtera } else { holder = (ViewHolder) convertView.getTag(); } - if( emoji != null) { + if (emoji != null) { holder.emoji_shortcode.setText(String.format("%s", emoji.getShortcode())); //Profile picture Glide.with(holder.emoji_icon.getContext()) @@ -125,17 +127,18 @@ public class EmojisSearchAdapter extends ArrayAdapter implements Filtera @Override protected void publishResults(CharSequence constraint, FilterResults results) { - try{ + try { ArrayList c = (ArrayList) results.values; if (results.count > 0) { clear(); addAll(c); notifyDataSetChanged(); - } else{ + } else { clear(); notifyDataSetChanged(); } - }catch (Exception ignored){} + } catch (Exception ignored) { + } } }; diff --git a/app/src/main/java/app/fedilab/android/drawers/FilterAdapter.java b/app/src/main/java/app/fedilab/android/drawers/FilterAdapter.java index 64f8a6a7b..92370b768 100644 --- a/app/src/main/java/app/fedilab/android/drawers/FilterAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/FilterAdapter.java @@ -19,8 +19,11 @@ import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.AsyncTask; + import com.google.android.material.floatingactionbutton.FloatingActionButton; + import androidx.appcompat.app.AlertDialog; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -61,7 +64,7 @@ public class FilterAdapter extends BaseAdapter implements OnFilterActionInterfac private FilterAdapter filterAdapter; private RelativeLayout textviewNoAction; - public FilterAdapter(List filters, RelativeLayout textviewNoAction){ + public FilterAdapter(List filters, RelativeLayout textviewNoAction) { this.filters = filters; this.filterAdapter = this; this.textviewNoAction = textviewNoAction; @@ -102,8 +105,8 @@ public class FilterAdapter extends BaseAdapter implements OnFilterActionInterfac } holder.filter_word.setText(filter.getPhrase()); StringBuilder contextString = new StringBuilder(); - if( filter.getContext() != null) - for(String ct: filter.getContext()) + if (filter.getContext() != null) + for (String ct : filter.getContext()) contextString.append(ct).append(" "); holder.filter_context.setText(contextString.toString()); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); @@ -111,17 +114,17 @@ public class FilterAdapter extends BaseAdapter implements OnFilterActionInterfac int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } holder.edit_filter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, style); - LayoutInflater inflater = ((BaseMainActivity)context).getLayoutInflater(); - View dialogView = inflater.inflate(R.layout.add_filter, new LinearLayout(context), false); + LayoutInflater inflater = ((BaseMainActivity) context).getLayoutInflater(); + View dialogView = inflater.inflate(R.layout.add_filter, new LinearLayout(context), false); dialogBuilder.setView(dialogView); EditText add_phrase = dialogView.findViewById(R.id.add_phrase); @@ -139,7 +142,7 @@ public class FilterAdapter extends BaseAdapter implements OnFilterActionInterfac filter_expire.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { - switch (position){ + switch (position) { case 0: expire[0] = -1; break; @@ -160,14 +163,15 @@ public class FilterAdapter extends BaseAdapter implements OnFilterActionInterfac break; } } + @Override public void onNothingSelected(AdapterView parent) { } }); add_phrase.setText(filter.getPhrase()); - if( filter.getContext() != null) - for(String val: filter.getContext()){ + if (filter.getContext() != null) + for (String val : filter.getContext()) { switch (val) { case "home": context_home.setChecked(true); @@ -190,17 +194,17 @@ public class FilterAdapter extends BaseAdapter implements OnFilterActionInterfac @Override public void onClick(DialogInterface dialog, int id) { - if( add_phrase.getText() != null && add_phrase.getText().toString().trim().length() > 0 ) { + if (add_phrase.getText() != null && add_phrase.getText().toString().trim().length() > 0) { Filters filterSent = new Filters(); filterSent.setId(filter.getId()); ArrayList contextFilter = new ArrayList<>(); - if( context_home.isChecked()) + if (context_home.isChecked()) contextFilter.add("home"); - if( context_public.isChecked()) + if (context_public.isChecked()) contextFilter.add("public"); - if( context_notification.isChecked()) + if (context_notification.isChecked()) contextFilter.add("notifications"); - if( context_conversation.isChecked()) + if (context_conversation.isChecked()) contextFilter.add("thread"); filterSent.setContext(contextFilter); filterSent.setExpires_in(expire[0]); @@ -232,7 +236,7 @@ public class FilterAdapter extends BaseAdapter implements OnFilterActionInterfac imm.hideSoftInputFromWindow(add_phrase.getWindowToken(), 0); } }); - if( alertDialog.getWindow() != null ) + if (alertDialog.getWindow() != null) alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); alertDialog.show(); } @@ -241,16 +245,16 @@ public class FilterAdapter extends BaseAdapter implements OnFilterActionInterfac @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(context, style); - builder.setTitle(context.getString(R.string.action_filter_delete) ); - builder.setMessage(context.getString(R.string.action_lists_confirm_delete) ); + builder.setTitle(context.getString(R.string.action_filter_delete)); + builder.setMessage(context.getString(R.string.action_lists_confirm_delete)); builder.setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { filters.remove(filter); filterAdapter.notifyDataSetChanged(); - new ManageFiltersAsyncTask(context, ManageFiltersAsyncTask.action.DELETE_FILTER,filter, FilterAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - if( filters.size() == 0 && textviewNoAction != null && textviewNoAction.getVisibility() == View.GONE) + new ManageFiltersAsyncTask(context, ManageFiltersAsyncTask.action.DELETE_FILTER, filter, FilterAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + if (filters.size() == 0 && textviewNoAction != null && textviewNoAction.getVisibility() == View.GONE) textviewNoAction.setVisibility(View.VISIBLE); dialog.dismiss(); } @@ -268,8 +272,8 @@ public class FilterAdapter extends BaseAdapter implements OnFilterActionInterfac } - private Filters getItemAt(int position){ - if( filters.size() > position) + private Filters getItemAt(int position) { + if (filters.size() > position) return filters.get(position); else return null; @@ -277,7 +281,7 @@ public class FilterAdapter extends BaseAdapter implements OnFilterActionInterfac @Override public void onActionDone(ManageFiltersAsyncTask.action actionType, APIResponse apiResponse, int statusCode) { - if( apiResponse != null) { + if (apiResponse != null) { if (apiResponse.getError() != null) { Toasty.error(context, apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); return; @@ -289,7 +293,7 @@ public class FilterAdapter extends BaseAdapter implements OnFilterActionInterfac } } - private void notifyStatusChanged(Filters filter){ + private void notifyStatusChanged(Filters filter) { for (int i = 0; i < filterAdapter.getCount(); i++) { //noinspection ConstantConditions if (filterAdapter.getItemAt(i) != null && filterAdapter.getItemAt(i).getId().equals(filter.getId())) { diff --git a/app/src/main/java/app/fedilab/android/drawers/HowToVideosAdapter.java b/app/src/main/java/app/fedilab/android/drawers/HowToVideosAdapter.java index 4f6e10551..7cfe45725 100644 --- a/app/src/main/java/app/fedilab/android/drawers/HowToVideosAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/HowToVideosAdapter.java @@ -20,7 +20,9 @@ import android.content.Intent; import android.content.SharedPreferences; import android.graphics.drawable.Drawable; import android.os.Bundle; + import androidx.core.content.ContextCompat; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -56,7 +58,7 @@ public class HowToVideosAdapter extends BaseAdapter implements OnListActionInter private LayoutInflater layoutInflater; private Context context; - public HowToVideosAdapter(List howToVideos){ + public HowToVideosAdapter(List howToVideos) { this.howToVideos = howToVideos; } @@ -97,22 +99,22 @@ public class HowToVideosAdapter extends BaseAdapter implements OnListActionInter SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if( theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { holder.how_to_container.setBackgroundResource(R.color.mastodonC3__); - Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right,R.color.black); - }else if(theme == Helper.THEME_DARK){ + Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right, R.color.black); + } else if (theme == Helper.THEME_DARK) { holder.how_to_container.setBackgroundResource(R.color.mastodonC1_); - Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right,R.color.dark_text); - }else if(theme == Helper.THEME_BLACK) { + Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right, R.color.dark_text); + } else if (theme == Helper.THEME_BLACK) { holder.how_to_container.setBackgroundResource(R.color.black_2); - Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right,R.color.dark_text); + Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right, R.color.dark_text); } Drawable next = ContextCompat.getDrawable(context, R.drawable.ic_keyboard_arrow_right); holder.how_to_description.setText(howToVideo.getDescription()); holder.how_to_title.setText(howToVideo.getName()); assert next != null; final float scale = context.getResources().getDisplayMetrics().density; - next.setBounds(0,0,(int) (30 * scale + 0.5f),(int) (30 * scale + 0.5f)); + next.setBounds(0, 0, (int) (30 * scale + 0.5f), (int) (30 * scale + 0.5f)); holder.how_to_description.setCompoundDrawables(null, null, next, null); Glide.with(holder.how_to_image.getContext()) .load("https://peertube.fedilab.app" + howToVideo.getThumbnailPath()) @@ -127,7 +129,7 @@ public class HowToVideosAdapter extends BaseAdapter implements OnListActionInter b.putBoolean("peertubeLink", true); Pattern link = Pattern.compile("(https?:\\/\\/[\\da-z\\.-]+\\.[a-z\\.]{2,10})\\/videos\\/embed\\/(\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12})$"); Matcher matcherLink = link.matcher(finalUrl); - if( matcherLink.find()) { + if (matcherLink.find()) { String url = matcherLink.group(1) + "/videos/watch/" + matcherLink.group(2); b.putString("peertubeLinkToFetch", url); } diff --git a/app/src/main/java/app/fedilab/android/drawers/ImageAdapter.java b/app/src/main/java/app/fedilab/android/drawers/ImageAdapter.java index 3ac2c604d..048d20b9c 100644 --- a/app/src/main/java/app/fedilab/android/drawers/ImageAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/ImageAdapter.java @@ -17,8 +17,10 @@ package app.fedilab.android.drawers; import android.content.Context; import android.content.Intent; import android.os.Bundle; + import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -72,7 +74,7 @@ public class ImageAdapter extends RecyclerView.Adapter { final ImageAdapter.ViewHolder holder = (ImageAdapter.ViewHolder) viewHolder; - if( !((ShowAccountActivity)context).isFinishing()) + if (!((ShowAccountActivity) context).isFinishing()) Glide.with(context).load(status.getArt_attachment().getPreview_url()).into(holder.imageView); holder.imageView.setOnClickListener(new View.OnClickListener() { @Override @@ -80,11 +82,11 @@ public class ImageAdapter extends RecyclerView.Adapter { Intent intent = new Intent(context, MediaActivity.class); Bundle b = new Bundle(); ArrayList attachmentsTmp = new ArrayList<>(); - for(Status status1: statuses){ + for (Status status1 : statuses) { attachmentsTmp.add(status1.getArt_attachment()); } intent.putParcelableArrayListExtra("mediaArray", attachmentsTmp); - b.putInt("position", (viewHolder.getAdapterPosition()+1)); + b.putInt("position", (viewHolder.getAdapterPosition() + 1)); intent.putExtras(b); context.startActivity(intent); } @@ -112,7 +114,7 @@ public class ImageAdapter extends RecyclerView.Adapter { } - class ViewHolder extends RecyclerView.ViewHolder{ + class ViewHolder extends RecyclerView.ViewHolder { ImageView imageView; public ViewHolder(View itemView) { diff --git a/app/src/main/java/app/fedilab/android/drawers/InstanceRegAdapter.java b/app/src/main/java/app/fedilab/android/drawers/InstanceRegAdapter.java index d2a8563fd..d0e6395ab 100644 --- a/app/src/main/java/app/fedilab/android/drawers/InstanceRegAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/InstanceRegAdapter.java @@ -32,6 +32,7 @@ import com.bumptech.glide.load.resource.bitmap.RoundedCorners; import com.bumptech.glide.request.RequestOptions; import java.util.List; + import app.fedilab.android.R; import app.fedilab.android.activities.MastodonRegisterActivity; import app.fedilab.android.client.Entities.InstanceReg; @@ -75,13 +76,13 @@ public class InstanceRegAdapter extends RecyclerView.Adapter { final InstanceRegAdapter.ViewHolder holder = (InstanceRegAdapter.ViewHolder) viewHolder; holder.instance_choose.setOnClickListener(v -> { - ((MastodonRegisterActivity)context).pickupInstance(instanceReg.getDomain()); + ((MastodonRegisterActivity) context).pickupInstance(instanceReg.getDomain()); }); - holder.instance_count_user.setText(context.getString(R.string.users,Helper.withSuffix(instanceReg.getTotal_users()))); + holder.instance_count_user.setText(context.getString(R.string.users, Helper.withSuffix(instanceReg.getTotal_users()))); holder.instance_description.setText(instanceReg.getDescription()); holder.instance_host.setText(instanceReg.getDomain()); - holder.instance_version.setText(String.format("%s - %s", instanceReg.getCategory(),instanceReg.getVersion())); + holder.instance_version.setText(String.format("%s - %s", instanceReg.getCategory(), instanceReg.getVersion())); Glide.with(context) .load(instanceReg.getProxied_thumbnail()) .apply(new RequestOptions().transforms(new FitCenter(), new RoundedCorners(10))) @@ -98,7 +99,7 @@ public class InstanceRegAdapter extends RecyclerView.Adapter { } - class ViewHolder extends RecyclerView.ViewHolder{ + class ViewHolder extends RecyclerView.ViewHolder { ImageView instance_pp; TextView instance_host, instance_version, instance_description, instance_count_user; ImageButton instance_choose; diff --git a/app/src/main/java/app/fedilab/android/drawers/ListAdapter.java b/app/src/main/java/app/fedilab/android/drawers/ListAdapter.java index 30a7f9a4b..da7db65f0 100644 --- a/app/src/main/java/app/fedilab/android/drawers/ListAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/ListAdapter.java @@ -20,7 +20,9 @@ import android.content.Intent; import android.content.SharedPreferences; import android.graphics.drawable.Drawable; import android.os.Bundle; + import androidx.core.content.ContextCompat; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -47,7 +49,7 @@ public class ListAdapter extends BaseAdapter { private List lists; private Context context; - public ListAdapter(List lists, RelativeLayout textviewNoAction){ + public ListAdapter(List lists, RelativeLayout textviewNoAction) { this.lists = lists; } @@ -85,21 +87,21 @@ public class ListAdapter extends BaseAdapter { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if( theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { holder.search_container.setBackgroundResource(R.color.mastodonC3__); - Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right,R.color.black); - }else if(theme == Helper.THEME_DARK){ + Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right, R.color.black); + } else if (theme == Helper.THEME_DARK) { holder.search_container.setBackgroundResource(R.color.mastodonC1_); - Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right,R.color.dark_text); - }else if(theme == Helper.THEME_BLACK) { + Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right, R.color.dark_text); + } else if (theme == Helper.THEME_BLACK) { holder.search_container.setBackgroundResource(R.color.black_2); - Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right,R.color.dark_text); + Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right, R.color.dark_text); } Drawable next = ContextCompat.getDrawable(context, R.drawable.ic_keyboard_arrow_right); holder.search_title.setText(list.getTitle()); assert next != null; final float scale = context.getResources().getDisplayMetrics().density; - next.setBounds(0,0,(int) (30 * scale + 0.5f),(int) (30 * scale + 0.5f)); + next.setBounds(0, 0, (int) (30 * scale + 0.5f), (int) (30 * scale + 0.5f)); holder.search_title.setCompoundDrawables(null, null, next, null); holder.search_container.setOnClickListener(new View.OnClickListener() { diff --git a/app/src/main/java/app/fedilab/android/drawers/NotificationsListAdapter.java b/app/src/main/java/app/fedilab/android/drawers/NotificationsListAdapter.java index 9c6b969f3..a8fa57898 100644 --- a/app/src/main/java/app/fedilab/android/drawers/NotificationsListAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/NotificationsListAdapter.java @@ -29,6 +29,7 @@ import android.os.Build; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; + import androidx.annotation.NonNull; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.core.content.ContextCompat; @@ -36,6 +37,7 @@ import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.PopupMenu; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; + import android.text.Html; import android.text.method.LinkMovementMethod; import android.util.TypedValue; @@ -136,7 +138,7 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On @Override public void run() { synchronized (lock) { - if( mRecyclerView != null && (mRecyclerView.getLayoutManager()) != null) { + if (mRecyclerView != null && (mRecyclerView.getLayoutManager()) != null) { int firstPosition = ((LinearLayoutManager) mRecyclerView.getLayoutManager()).findFirstCompletelyVisibleItemPosition(); int lastPosition = ((LinearLayoutManager) mRecyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition(); @@ -146,7 +148,7 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On holder.updateAnimatedEmoji(); } } - }else{ + } else { for (NotificationsListAdapter.ViewHolder holder : lstHolders) { holder.updateAnimatedEmoji(); } @@ -157,7 +159,7 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On private Handler mHandler = new Handler(); - public NotificationsListAdapter(boolean isOnWifi, int behaviorWithAttachments, List notifications){ + public NotificationsListAdapter(boolean isOnWifi, int behaviorWithAttachments, List notifications) { this.notifications = notifications; notificationsListAdapter = this; this.isOnWifi = isOnWifi; @@ -174,7 +176,7 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On } @Override - public void onDetachedFromRecyclerView (@NotNull RecyclerView recyclerView) { + public void onDetachedFromRecyclerView(@NotNull RecyclerView recyclerView) { super.onDetachedFromRecyclerView(recyclerView); mRecyclerView = null; } @@ -205,7 +207,6 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On int textSizePercent = sharedpreferences.getInt(Helper.SET_TEXT_SIZE, 110); - final float scale = context.getResources().getDisplayMetrics().density; String type = notification.getType(); String typeString = ""; @@ -215,47 +216,47 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On boolean confirmBoost = sharedpreferences.getBoolean(Helper.SET_NOTIF_VALIDATION, true); boolean hide_notification_delete = sharedpreferences.getBoolean(Helper.SET_HIDE_DELETE_BUTTON_ON_TAB, false); - if (theme == Helper.THEME_DARK ){ + if (theme == Helper.THEME_DARK) { holder.main_container_trans.setBackgroundColor(ContextCompat.getColor(context, R.color.notif_dark_1)); holder.main_container_trans.setAlpha(.5f); - }else if( theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { holder.main_container_trans.setBackgroundColor(ContextCompat.getColor(context, R.color.notif_black_1)); holder.main_container_trans.setAlpha(.5f); - }else{ + } else { holder.main_container_trans.setBackgroundColor(ContextCompat.getColor(context, R.color.notif_light_1)); holder.main_container_trans.setAlpha(.5f); } if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } - if(hide_notification_delete) + if (hide_notification_delete) holder.notification_delete.setVisibility(View.GONE); Drawable imgH = null; holder.status_date.setVisibility(View.VISIBLE); - switch (type){ + switch (type) { case "mention": holder.status_action_container.setVisibility(View.VISIBLE); - if( notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) - typeString = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true),context.getString(R.string.notif_mention)); + if (notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) + typeString = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true), context.getString(R.string.notif_mention)); else - typeString = String.format("@%s %s", notification.getAccount().getUsername(),context.getString(R.string.notif_mention)); - if( theme == Helper.THEME_DARK){ - if( notification.getStatus().getVisibility().equals("direct")) + typeString = String.format("@%s %s", notification.getAccount().getUsername(), context.getString(R.string.notif_mention)); + if (theme == Helper.THEME_DARK) { + if (notification.getStatus().getVisibility().equals("direct")) holder.card_status_container.setBackgroundColor(ContextCompat.getColor(context, R.color.notif_dark_private)); else holder.card_status_container.setBackgroundColor(ContextCompat.getColor(context, R.color.notif_dark_1)); - }else if( theme == Helper.THEME_BLACK){ - if( notification.getStatus().getVisibility().equals("direct")) + } else if (theme == Helper.THEME_BLACK) { + if (notification.getStatus().getVisibility().equals("direct")) holder.card_status_container.setBackgroundColor(ContextCompat.getColor(context, R.color.notif_black_private)); else holder.card_status_container.setBackgroundColor(ContextCompat.getColor(context, R.color.notif_black_1)); - }else { - if( notification.getStatus().getVisibility().equals("direct")) + } else { + if (notification.getStatus().getVisibility().equals("direct")) holder.card_status_container.setBackgroundColor(ContextCompat.getColor(context, R.color.notif_light_private)); else holder.card_status_container.setBackgroundColor(ContextCompat.getColor(context, R.color.notif_light_1)); @@ -266,12 +267,13 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On break; case "poll": holder.status_action_container.setVisibility(View.GONE); - typeString = context.getString(R.string.notif_poll);; - if( theme == Helper.THEME_DARK){ + typeString = context.getString(R.string.notif_poll); + ; + if (theme == Helper.THEME_DARK) { holder.card_status_container.setBackgroundColor(ContextCompat.getColor(context, R.color.notif_dark_1)); - }else if( theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { holder.card_status_container.setBackgroundColor(ContextCompat.getColor(context, R.color.notif_black_1)); - }else { + } else { holder.card_status_container.setBackgroundColor(ContextCompat.getColor(context, R.color.notif_light_1)); } imgH = ContextCompat.getDrawable(context, R.drawable.ic_view_list_poll_notif); @@ -280,15 +282,15 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On break; case "reblog": holder.status_action_container.setVisibility(View.GONE); - if( notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) - typeString = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true),context.getString(R.string.notif_reblog)); + if (notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) + typeString = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true), context.getString(R.string.notif_reblog)); else - typeString = String.format("@%s %s", notification.getAccount().getUsername(),context.getString(R.string.notif_reblog)); - if( theme == Helper.THEME_DARK){ + typeString = String.format("@%s %s", notification.getAccount().getUsername(), context.getString(R.string.notif_reblog)); + if (theme == Helper.THEME_DARK) { holder.card_status_container.setBackgroundColor(ContextCompat.getColor(context, R.color.notif_dark_1)); - }else if( theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { holder.card_status_container.setBackgroundColor(ContextCompat.getColor(context, R.color.notif_black_1)); - }else { + } else { holder.card_status_container.setBackgroundColor(ContextCompat.getColor(context, R.color.notif_light_1)); } imgH = ContextCompat.getDrawable(context, R.drawable.ic_repeat_head); @@ -297,15 +299,15 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On break; case "favourite": holder.status_action_container.setVisibility(View.GONE); - if( notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) - typeString = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true),context.getString(R.string.notif_favourite)); + if (notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) + typeString = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true), context.getString(R.string.notif_favourite)); else - typeString = String.format("@%s %s", notification.getAccount().getUsername(),context.getString(R.string.notif_favourite)); - if( theme == Helper.THEME_DARK){ + typeString = String.format("@%s %s", notification.getAccount().getUsername(), context.getString(R.string.notif_favourite)); + if (theme == Helper.THEME_DARK) { holder.card_status_container.setBackgroundColor(ContextCompat.getColor(context, R.color.notif_dark_1)); - }else if( theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { holder.card_status_container.setBackgroundColor(ContextCompat.getColor(context, R.color.notif_black_1)); - }else { + } else { holder.card_status_container.setBackgroundColor(ContextCompat.getColor(context, R.color.notif_light_1)); } imgH = ContextCompat.getDrawable(context, R.drawable.ic_star_border_header); @@ -315,15 +317,15 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On case "follow": holder.status_action_container.setVisibility(View.GONE); holder.status_date.setVisibility(View.GONE); - if( notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) - typeString = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true),context.getString(R.string.notif_follow)); + if (notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) + typeString = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true), context.getString(R.string.notif_follow)); else - typeString = String.format("@%s %s", notification.getAccount().getUsername(),context.getString(R.string.notif_follow)); - if( theme == Helper.THEME_DARK){ + typeString = String.format("@%s %s", notification.getAccount().getUsername(), context.getString(R.string.notif_follow)); + if (theme == Helper.THEME_DARK) { holder.card_status_container.setBackgroundColor(ContextCompat.getColor(context, R.color.notif_dark_1)); - }else if( theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { holder.card_status_container.setBackgroundColor(ContextCompat.getColor(context, R.color.notif_black_1)); - }else { + } else { holder.card_status_container.setBackgroundColor(ContextCompat.getColor(context, R.color.notif_light_1)); } imgH = ContextCompat.getDrawable(context, R.drawable.ic_follow_notif_header); @@ -331,73 +333,73 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On break; } - if( theme == Helper.THEME_BLACK){ + if (theme == Helper.THEME_BLACK) { Helper.changeDrawableColor(context, R.drawable.ic_chat_bubble_outline, R.color.dark_icon); - Helper.changeDrawableColor(context, R.drawable.ic_repeat_head,R.color.dark_icon); - Helper.changeDrawableColor(context, R.drawable.ic_star_border_header,R.color.dark_icon); - Helper.changeDrawableColor(context, R.drawable.ic_follow_notif_header,R.color.dark_icon); - Helper.changeDrawableColor(context, R.drawable.ic_view_list_poll_notif,R.color.dark_icon); - }else { + Helper.changeDrawableColor(context, R.drawable.ic_repeat_head, R.color.dark_icon); + Helper.changeDrawableColor(context, R.drawable.ic_star_border_header, R.color.dark_icon); + Helper.changeDrawableColor(context, R.drawable.ic_follow_notif_header, R.color.dark_icon); + Helper.changeDrawableColor(context, R.drawable.ic_view_list_poll_notif, R.color.dark_icon); + } else { Helper.changeDrawableColor(context, R.drawable.ic_chat_bubble_outline, R.color.mastodonC4); - Helper.changeDrawableColor(context, R.drawable.ic_repeat_head,R.color.mastodonC4); - Helper.changeDrawableColor(context, R.drawable.ic_star_border_header,R.color.mastodonC4); - Helper.changeDrawableColor(context, R.drawable.ic_follow_notif_header,R.color.mastodonC4); - Helper.changeDrawableColor(context, R.drawable.ic_view_list_poll_notif,R.color.mastodonC4); + Helper.changeDrawableColor(context, R.drawable.ic_repeat_head, R.color.mastodonC4); + Helper.changeDrawableColor(context, R.drawable.ic_star_border_header, R.color.mastodonC4); + Helper.changeDrawableColor(context, R.drawable.ic_follow_notif_header, R.color.mastodonC4); + Helper.changeDrawableColor(context, R.drawable.ic_view_list_poll_notif, R.color.mastodonC4); } - if( notification.getAccount().getdisplayNameSpan() == null) { + if (notification.getAccount().getdisplayNameSpan() == null) { holder.notification_type.setText(typeString); notification.getAccount().setStored_displayname(notification.getAccount().getDisplay_name()); - // notification.getAccount().setDisplay_name(typeString); - }else + // notification.getAccount().setDisplay_name(typeString); + } else holder.notification_type.setText(notification.getAccount().getdisplayNameSpan(), TextView.BufferType.SPANNABLE); - if( imgH != null) { - holder.notification_type.setCompoundDrawablePadding((int)Helper.convertDpToPixel(5, context)); + if (imgH != null) { + holder.notification_type.setCompoundDrawablePadding((int) Helper.convertDpToPixel(5, context)); imgH.setBounds(0, 0, (int) (20 * iconSizePercent / 100 * scale + 0.5f), (int) (20 * iconSizePercent / 100 * scale + 0.5f)); } - holder.notification_type.setCompoundDrawables( imgH, null, null, null); + holder.notification_type.setCompoundDrawables(imgH, null, null, null); - holder.status_privacy.getLayoutParams().height = (int) Helper.convertDpToPixel((20*iconSizePercent/100), context); - holder.status_privacy.getLayoutParams().width = (int) Helper.convertDpToPixel((20*iconSizePercent/100), context); - holder.status_reply.getLayoutParams().height = (int) Helper.convertDpToPixel((20*iconSizePercent/100), context); - holder.status_reply.getLayoutParams().width = (int) Helper.convertDpToPixel((20*iconSizePercent/100), context); - holder.status_spoiler.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14*textSizePercent/100); + holder.status_privacy.getLayoutParams().height = (int) Helper.convertDpToPixel((20 * iconSizePercent / 100), context); + holder.status_privacy.getLayoutParams().width = (int) Helper.convertDpToPixel((20 * iconSizePercent / 100), context); + holder.status_reply.getLayoutParams().height = (int) Helper.convertDpToPixel((20 * iconSizePercent / 100), context); + holder.status_reply.getLayoutParams().width = (int) Helper.convertDpToPixel((20 * iconSizePercent / 100), context); + holder.status_spoiler.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14 * textSizePercent / 100); - holder.notification_status_content.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14*textSizePercent/100); - holder.notification_type.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14*textSizePercent/100); - holder.status_date.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12*textSizePercent/100); + holder.notification_status_content.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14 * textSizePercent / 100); + holder.notification_type.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14 * textSizePercent / 100); + holder.status_date.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12 * textSizePercent / 100); //Manages theme for icon colors - if( theme == Helper.THEME_BLACK){ - Helper.changeDrawableColor(context, R.drawable.ic_reply,R.color.action_black); + if (theme == Helper.THEME_BLACK) { + Helper.changeDrawableColor(context, R.drawable.ic_reply, R.color.action_black); Helper.changeDrawableColor(context, holder.status_more, R.color.action_black); Helper.changeDrawableColor(context, holder.status_privacy, R.color.action_black); - Helper.changeDrawableColor(context, R.drawable.ic_repeat,R.color.action_black); - Helper.changeDrawableColor(context, R.drawable.ic_star_border,R.color.action_black); - Helper.changeDrawableColor(context, R.drawable.ic_photo,R.color.dark_text); - Helper.changeDrawableColor(context, R.drawable.ic_remove_red_eye,R.color.dark_text); - Helper.changeDrawableColor(context, holder.notification_delete,R.color.dark_text); - }else if( theme == Helper.THEME_DARK ){ - Helper.changeDrawableColor(context, R.drawable.ic_reply,R.color.action_dark); + Helper.changeDrawableColor(context, R.drawable.ic_repeat, R.color.action_black); + Helper.changeDrawableColor(context, R.drawable.ic_star_border, R.color.action_black); + Helper.changeDrawableColor(context, R.drawable.ic_photo, R.color.dark_text); + Helper.changeDrawableColor(context, R.drawable.ic_remove_red_eye, R.color.dark_text); + Helper.changeDrawableColor(context, holder.notification_delete, R.color.dark_text); + } else if (theme == Helper.THEME_DARK) { + Helper.changeDrawableColor(context, R.drawable.ic_reply, R.color.action_dark); Helper.changeDrawableColor(context, holder.status_more, R.color.action_dark); Helper.changeDrawableColor(context, holder.status_privacy, R.color.action_dark); - Helper.changeDrawableColor(context, R.drawable.ic_repeat,R.color.action_dark); - Helper.changeDrawableColor(context, R.drawable.ic_star_border,R.color.action_dark); - Helper.changeDrawableColor(context, R.drawable.ic_photo,R.color.mastodonC4); - Helper.changeDrawableColor(context, R.drawable.ic_remove_red_eye,R.color.mastodonC4); - Helper.changeDrawableColor(context, holder.notification_delete,R.color.dark_text); - }else { - Helper.changeDrawableColor(context, R.drawable.ic_reply,R.color.action_light); + Helper.changeDrawableColor(context, R.drawable.ic_repeat, R.color.action_dark); + Helper.changeDrawableColor(context, R.drawable.ic_star_border, R.color.action_dark); + Helper.changeDrawableColor(context, R.drawable.ic_photo, R.color.mastodonC4); + Helper.changeDrawableColor(context, R.drawable.ic_remove_red_eye, R.color.mastodonC4); + Helper.changeDrawableColor(context, holder.notification_delete, R.color.dark_text); + } else { + Helper.changeDrawableColor(context, R.drawable.ic_reply, R.color.action_light); Helper.changeDrawableColor(context, holder.status_more, R.color.action_light); Helper.changeDrawableColor(context, holder.status_privacy, R.color.action_light); - Helper.changeDrawableColor(context, R.drawable.ic_repeat,R.color.action_light); - Helper.changeDrawableColor(context, R.drawable.ic_star_border,R.color.action_light); - Helper.changeDrawableColor(context, R.drawable.ic_photo,R.color.black); - Helper.changeDrawableColor(context, R.drawable.ic_remove_red_eye,R.color.black); - Helper.changeDrawableColor(context, holder.notification_delete,R.color.black); + Helper.changeDrawableColor(context, R.drawable.ic_repeat, R.color.action_light); + Helper.changeDrawableColor(context, R.drawable.ic_star_border, R.color.action_light); + Helper.changeDrawableColor(context, R.drawable.ic_photo, R.color.black); + Helper.changeDrawableColor(context, R.drawable.ic_remove_red_eye, R.color.black); + Helper.changeDrawableColor(context, holder.notification_delete, R.color.black); } holder.spark_button_fav.pressOnTouch(false); holder.spark_button_reblog.pressOnTouch(false); @@ -405,40 +407,40 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On holder.spark_button_reblog.setActiveImageTint(R.color.boost_icon); holder.spark_button_fav.setDisableCircle(true); holder.spark_button_reblog.setDisableCircle(true); - if( theme == Helper.THEME_DARK) { + if (theme == Helper.THEME_DARK) { holder.spark_button_fav.setInActiveImageTint(R.color.action_dark); holder.spark_button_reblog.setInActiveImageTint(R.color.action_dark); - }else if(theme == Helper.THEME_BLACK) { + } else if (theme == Helper.THEME_BLACK) { holder.spark_button_fav.setInActiveImageTint(R.color.action_black); holder.spark_button_reblog.setInActiveImageTint(R.color.action_black); - }else { + } else { holder.spark_button_fav.setInActiveImageTint(R.color.action_light); holder.spark_button_reblog.setInActiveImageTint(R.color.action_light); } holder.spark_button_fav.setColors(R.color.marked_icon, R.color.marked_icon); - holder.spark_button_fav.setImageSize((int) (20 * iconSizePercent/100 * scale + 0.5f)); - holder.spark_button_fav.setMinimumWidth((int)Helper.convertDpToPixel((20 * iconSizePercent/100 * scale + 0.5f),context)); + holder.spark_button_fav.setImageSize((int) (20 * iconSizePercent / 100 * scale + 0.5f)); + holder.spark_button_fav.setMinimumWidth((int) Helper.convertDpToPixel((20 * iconSizePercent / 100 * scale + 0.5f), context)); holder.spark_button_reblog.setColors(R.color.boost_icon, R.color.boost_icon); - holder.spark_button_reblog.setImageSize((int) (20 * iconSizePercent/100 * scale + 0.5f)); - holder.spark_button_reblog.setMinimumWidth((int)Helper.convertDpToPixel((20 * iconSizePercent/100 * scale + 0.5f),context)); + holder.spark_button_reblog.setImageSize((int) (20 * iconSizePercent / 100 * scale + 0.5f)); + holder.spark_button_reblog.setMinimumWidth((int) Helper.convertDpToPixel((20 * iconSizePercent / 100 * scale + 0.5f), context)); final Status status = notification.getStatus(); - if( status != null ){ - if( status.getMedia_attachments() == null || status.getMedia_attachments().size() < 1) + if (status != null) { + if (status.getMedia_attachments() == null || status.getMedia_attachments().size() < 1) holder.status_document_container.setVisibility(View.GONE); else holder.status_document_container.setVisibility(View.VISIBLE); - if( !status.isClickable()) { + if (!status.isClickable()) { status.setClickable(true); Status.transform(context, status); } - if( !notification.isEmojiFound()) { + if (!notification.isEmojiFound()) { notification.setEmojiFound(true); Notification.makeEmojis(context, NotificationsListAdapter.this, notification); } - if( !status.isImageFound()) { + if (!status.isImageFound()) { status.setImageFound(true); Status.makeImage(context, NotificationsListAdapter.this, status); } @@ -462,7 +464,7 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On Helper.absoluteDateTimeReveal(context, holder.status_date, status.getCreated_at()); - holder.status_mention_spoiler.setText(Helper.makeMentionsClick(context,status.getMentions()), TextView.BufferType.SPANNABLE); + holder.status_mention_spoiler.setText(Helper.makeMentionsClick(context, status.getMentions()), TextView.BufferType.SPANNABLE); holder.status_mention_spoiler.setMovementMethod(LinkMovementMethod.getInstance()); //Adds attachment -> disabled, to enable them uncomment the line below @@ -491,25 +493,25 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On holder.status_action_container.setVisibility(View.VISIBLE); - if( !status.isFavAnimated() ) { + if (!status.isFavAnimated()) { if (status.isFavourited() || (status.getReblog() != null && status.getReblog().isFavourited())) { holder.spark_button_fav.setChecked(true); } else { holder.spark_button_fav.setChecked(false); } - }else { + } else { status.setFavAnimated(false); holder.spark_button_fav.setChecked(true); holder.spark_button_fav.setAnimationSpeed(1.0f); holder.spark_button_fav.playAnimation(); } - if( !status.isBoostAnimated()){ - if( status.isReblogged()|| (status.getReblog() != null && status.getReblog().isReblogged())) { + if (!status.isBoostAnimated()) { + if (status.isReblogged() || (status.getReblog() != null && status.getReblog().isReblogged())) { holder.spark_button_reblog.setChecked(true); - }else { + } else { holder.spark_button_reblog.setChecked(false); } - }else { + } else { status.setBoostAnimated(false); holder.spark_button_reblog.setChecked(true); holder.spark_button_reblog.setAnimationSpeed(1.0f); @@ -518,22 +520,21 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On } - - if( theme == Helper.THEME_DARK) - Helper.changeDrawableColor(context, holder.status_reply,R.color.action_dark); - else if(theme == Helper.THEME_BLACK) - Helper.changeDrawableColor(context, holder.status_reply,R.color.action_black); + if (theme == Helper.THEME_DARK) + Helper.changeDrawableColor(context, holder.status_reply, R.color.action_dark); + else if (theme == Helper.THEME_BLACK) + Helper.changeDrawableColor(context, holder.status_reply, R.color.action_black); else - Helper.changeDrawableColor(context, holder.status_reply,R.color.action_light); + Helper.changeDrawableColor(context, holder.status_reply, R.color.action_light); - if( status.getReblog() == null) { - if (status.getSpoiler_text() != null && status.getSpoiler_text().trim().length() > 0 ) { + if (status.getReblog() == null) { + if (status.getSpoiler_text() != null && status.getSpoiler_text().trim().length() > 0) { holder.status_spoiler_container.setVisibility(View.VISIBLE); - if( !status.isSpoilerShown() && !expand_cw) { + if (!status.isSpoilerShown() && !expand_cw) { holder.notification_status_container.setVisibility(View.GONE); holder.status_spoiler_mention_container.setVisibility(View.VISIBLE); holder.status_spoiler_button.setText(context.getString(R.string.load_attachment_spoiler)); - }else { + } else { holder.notification_status_container.setVisibility(View.VISIBLE); holder.status_spoiler_mention_container.setVisibility(View.GONE); holder.status_spoiler_button.setText(context.getString(R.string.load_attachment_spoiler_less)); @@ -544,14 +545,14 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On holder.notification_status_container.setVisibility(View.VISIBLE); } - }else { + } else { if (status.getReblog().getSpoiler_text() != null && status.getReblog().getSpoiler_text().trim().length() > 0) { holder.status_spoiler_container.setVisibility(View.VISIBLE); - if( !status.isSpoilerShown() && !expand_cw) { + if (!status.isSpoilerShown() && !expand_cw) { holder.notification_status_container.setVisibility(View.GONE); holder.status_spoiler_mention_container.setVisibility(View.VISIBLE); holder.status_spoiler_button.setText(context.getString(R.string.load_attachment_spoiler)); - }else { + } else { holder.notification_status_container.setVisibility(View.VISIBLE); holder.status_spoiler_mention_container.setVisibility(View.GONE); holder.status_spoiler_button.setText(context.getString(R.string.load_attachment_spoiler_less)); @@ -564,24 +565,23 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On } - - if( theme == Helper.THEME_DARK ){ + if (theme == Helper.THEME_DARK) { holder.status_favorite_count.setTextColor(ContextCompat.getColor(context, R.color.action_dark)); holder.status_reblog_count.setTextColor(ContextCompat.getColor(context, R.color.action_dark)); holder.status_reply_count.setTextColor(ContextCompat.getColor(context, R.color.action_dark)); - }else if(theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { holder.status_favorite_count.setTextColor(ContextCompat.getColor(context, R.color.action_black)); holder.status_reblog_count.setTextColor(ContextCompat.getColor(context, R.color.action_black)); holder.status_reply_count.setTextColor(ContextCompat.getColor(context, R.color.action_black)); - }else { + } else { holder.status_favorite_count.setTextColor(ContextCompat.getColor(context, R.color.action_light)); holder.status_reblog_count.setTextColor(ContextCompat.getColor(context, R.color.action_light)); holder.status_reply_count.setTextColor(ContextCompat.getColor(context, R.color.action_light)); } - if( type.equals("favourite") || type.equals("reblog")){ + if (type.equals("favourite") || type.equals("reblog")) { holder.status_document_container.setVisibility(View.GONE); holder.status_show_more.setVisibility(View.GONE); - }else { + } else { if (status.getReblog() == null) { if (status.getMedia_attachments() == null || status.getMedia_attachments().size() < 1) { holder.status_document_container.setVisibility(View.GONE); @@ -614,26 +614,26 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On holder.multiple_choice.setVisibility(View.GONE); holder.single_choice.setVisibility(View.GONE); holder.submit_vote.setVisibility(View.GONE); - if( status.getPoll() != null && status.getPoll().getOptionsList() != null ){ + if (status.getPoll() != null && status.getPoll().getOptionsList() != null) { Poll poll = status.getPoll(); - if( poll.isVoted() || poll.isExpired()){ + if (poll.isVoted() || poll.isExpired()) { holder.rated.setVisibility(View.VISIBLE); List items = new ArrayList<>(); int greaterValue = 0; - for(PollOptions pollOption: status.getPoll().getOptionsList()){ - if( pollOption.getVotes_count() > greaterValue) + for (PollOptions pollOption : status.getPoll().getOptionsList()) { + if (pollOption.getVotes_count() > greaterValue) greaterValue = pollOption.getVotes_count(); } - for(PollOptions pollOption: status.getPoll().getOptionsList()){ - double value = ((double)(pollOption.getVotes_count()* 100) / (double)poll.getVotes_count()) ; - if( pollOption.getVotes_count() == greaterValue) { + for (PollOptions pollOption : status.getPoll().getOptionsList()) { + double value = ((double) (pollOption.getVotes_count() * 100) / (double) poll.getVotes_count()); + if (pollOption.getVotes_count() == greaterValue) { BarItem bar = new BarItem(pollOption.getTitle(), value, "%", ContextCompat.getColor(context, R.color.mastodonC4), Color.WHITE); bar.setRounded(true); bar.setHeight1(30); items.add(bar); - }else { + } else { BarItem bar; - if( theme == Helper.THEME_LIGHT) + if (theme == Helper.THEME_LIGHT) bar = new BarItem(pollOption.getTitle(), value, "%", ContextCompat.getColor(context, R.color.mastodonC2), Color.BLACK); else bar = new BarItem(pollOption.getTitle(), value, "%", ContextCompat.getColor(context, R.color.mastodonC2), Color.WHITE); @@ -646,20 +646,20 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On HorizontalBar horizontalBar = new HorizontalBar(context); horizontalBar.hasAnimation(true).addAll(items).build(); holder.rated.addView(horizontalBar); - }else { - if( poll.isMultiple()){ - if((holder.multiple_choice).getChildCount() > 0) + } else { + if (poll.isMultiple()) { + if ((holder.multiple_choice).getChildCount() > 0) (holder.multiple_choice).removeAllViews(); - for(PollOptions pollOption: poll.getOptionsList()){ + for (PollOptions pollOption : poll.getOptionsList()) { CheckBox cb = new CheckBox(context); cb.setText(pollOption.getTitle()); holder.multiple_choice.addView(cb); } holder.multiple_choice.setVisibility(View.VISIBLE); - }else { - if((holder.radio_group).getChildCount() > 0) + } else { + if ((holder.radio_group).getChildCount() > 0) (holder.radio_group).removeAllViews(); - for(PollOptions pollOption: poll.getOptionsList()){ + for (PollOptions pollOption : poll.getOptionsList()) { RadioButton rb = new RadioButton(context); rb.setText(pollOption.getTitle()); holder.radio_group.addView(rb); @@ -670,13 +670,13 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On holder.submit_vote.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - int [] choice; - if( poll.isMultiple()){ + int[] choice; + if (poll.isMultiple()) { ArrayList choices = new ArrayList<>(); int choicesCount = holder.multiple_choice.getChildCount(); - for( int i = 0 ; i < choicesCount ; i++){ - if( holder.multiple_choice.getChildAt(i) != null && holder.multiple_choice.getChildAt(i) instanceof CheckBox){ - if(((CheckBox) holder.multiple_choice.getChildAt(i)).isChecked()){ + for (int i = 0; i < choicesCount; i++) { + if (holder.multiple_choice.getChildAt(i) != null && holder.multiple_choice.getChildAt(i) instanceof CheckBox) { + if (((CheckBox) holder.multiple_choice.getChildAt(i)).isChecked()) { choices.add(i); } } @@ -686,20 +686,20 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On for (int i = 0; i < choice.length; i++) { choice[i] = iterator.next().intValue(); } - if( choice.length == 0) + if (choice.length == 0) return; - }else{ + } else { choice = new int[1]; choice[0] = -1; int choicesCount = holder.radio_group.getChildCount(); - for( int i = 0 ; i < choicesCount ; i++){ - if( holder.radio_group.getChildAt(i) != null && holder.radio_group.getChildAt(i) instanceof RadioButton){ - if(((RadioButton) holder.radio_group.getChildAt(i)).isChecked()){ + for (int i = 0; i < choicesCount; i++) { + if (holder.radio_group.getChildAt(i) != null && holder.radio_group.getChildAt(i) instanceof RadioButton) { + if (((RadioButton) holder.radio_group.getChildAt(i)).isChecked()) { choice[0] = i; } } } - if( choice[0] == -1) + if (choice[0] == -1) return; } new ManagePollAsyncTask(context, ManagePollAsyncTask.type_s.SUBMIT, status, choice, NotificationsListAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); @@ -714,9 +714,9 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On } }); holder.poll_container.setVisibility(View.VISIBLE); - holder.number_votes.setText(context.getResources().getQuantityString(R.plurals.number_of_vote,status.getPoll().getVotes_count(),status.getPoll().getVotes_count())); + holder.number_votes.setText(context.getResources().getQuantityString(R.plurals.number_of_vote, status.getPoll().getVotes_count(), status.getPoll().getVotes_count())); holder.remaining_time.setText(context.getString(R.string.poll_finish_at, Helper.dateToStringPoll(poll.getExpires_at()))); - }else { + } else { holder.poll_container.setVisibility(View.GONE); } } @@ -725,25 +725,25 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On @Override public void onClick(View v) { - if( !status.isFavourited() && confirmFav) + if (!status.isFavourited() && confirmFav) status.setFavAnimated(true); - if( !status.isFavourited() && !confirmFav) { + if (!status.isFavourited() && !confirmFav) { status.setFavAnimated(true); notifyNotificationChanged(notification); } - CrossActions.doCrossAction(context, null, status, null, status.isFavourited()? API.StatusAction.UNFAVOURITE:API.StatusAction.FAVOURITE, notificationsListAdapter, NotificationsListAdapter.this, true); + CrossActions.doCrossAction(context, null, status, null, status.isFavourited() ? API.StatusAction.UNFAVOURITE : API.StatusAction.FAVOURITE, notificationsListAdapter, NotificationsListAdapter.this, true); } }); holder.spark_button_reblog.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - if( !status.isReblogged() && confirmBoost) + if (!status.isReblogged() && confirmBoost) status.setBoostAnimated(true); - if( !status.isReblogged() && !confirmBoost) { + if (!status.isReblogged() && !confirmBoost) { status.setBoostAnimated(true); notifyNotificationChanged(notification); } - CrossActions.doCrossAction(context, null, status, null, status.isReblogged()? API.StatusAction.UNREBLOG:API.StatusAction.REBLOG, notificationsListAdapter, NotificationsListAdapter.this, true); + CrossActions.doCrossAction(context, null, status, null, status.isReblogged() ? API.StatusAction.UNREBLOG : API.StatusAction.REBLOG, notificationsListAdapter, NotificationsListAdapter.this, true); } }); @@ -757,7 +757,7 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On }); - switch (status.getVisibility()){ + switch (status.getVisibility()) { case "public": holder.status_privacy.setImageResource(R.drawable.ic_public); break; @@ -771,7 +771,7 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On holder.status_privacy.setImageResource(R.drawable.ic_mail_outline); break; } - switch (status.getVisibility()){ + switch (status.getVisibility()) { case "direct": case "private": holder.status_reblog_count.setVisibility(View.GONE); @@ -788,7 +788,6 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On } - holder.status_show_more.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -820,7 +819,6 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On }); - holder.status_reply.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -828,31 +826,31 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On } }); - if( !status.getVisibility().equals("direct")) - holder.spark_button_fav.setOnLongClickListener(new View.OnLongClickListener() { - @Override - public boolean onLongClick(View view) { - CrossActions.doCrossAction(context, null, status, null, status.isFavourited()? API.StatusAction.UNFAVOURITE:API.StatusAction.FAVOURITE, notificationsListAdapter, NotificationsListAdapter.this, false); - return true; - } - }); - if( !status.getVisibility().equals("direct")) - holder.status_reply.setOnLongClickListener(new View.OnLongClickListener() { - @Override - public boolean onLongClick(View view) { - CrossActions.doCrossReply(context, status, RetrieveFeedsAsyncTask.Type.LOCAL, false); - return true; - } - }); - if( !status.getVisibility().equals("direct")) - holder.spark_button_reblog.setOnLongClickListener(new View.OnLongClickListener() { - @Override - public boolean onLongClick(View view) { - CrossActions.doCrossAction(context, null, status, null, status.isReblogged()? API.StatusAction.UNREBLOG:API.StatusAction.REBLOG, notificationsListAdapter, NotificationsListAdapter.this, false); - return true; - } - }); - }else { + if (!status.getVisibility().equals("direct")) + holder.spark_button_fav.setOnLongClickListener(new View.OnLongClickListener() { + @Override + public boolean onLongClick(View view) { + CrossActions.doCrossAction(context, null, status, null, status.isFavourited() ? API.StatusAction.UNFAVOURITE : API.StatusAction.FAVOURITE, notificationsListAdapter, NotificationsListAdapter.this, false); + return true; + } + }); + if (!status.getVisibility().equals("direct")) + holder.status_reply.setOnLongClickListener(new View.OnLongClickListener() { + @Override + public boolean onLongClick(View view) { + CrossActions.doCrossReply(context, status, RetrieveFeedsAsyncTask.Type.LOCAL, false); + return true; + } + }); + if (!status.getVisibility().equals("direct")) + holder.spark_button_reblog.setOnLongClickListener(new View.OnLongClickListener() { + @Override + public boolean onLongClick(View view) { + CrossActions.doCrossAction(context, null, status, null, status.isReblogged() ? API.StatusAction.UNREBLOG : API.StatusAction.REBLOG, notificationsListAdapter, NotificationsListAdapter.this, false); + return true; + } + }); + } else { holder.notification_status_container.setVisibility(View.GONE); holder.status_spoiler_container.setVisibility(View.GONE); holder.status_spoiler_mention_container.setVisibility(View.GONE); @@ -861,7 +859,6 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On } - holder.notification_account_profile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -875,7 +872,6 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On }); - holder.notification_delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -891,49 +887,49 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On public void onClick(View v) { PopupMenu popup = new PopupMenu(context, attached); assert status != null; - final boolean isOwner = status.getReblog()!=null?status.getReblog().getAccount().getId().equals(userId):status.getAccount().getId().equals(userId); + final boolean isOwner = status.getReblog() != null ? status.getReblog().getAccount().getId().equals(userId) : status.getAccount().getId().equals(userId); popup.getMenuInflater() .inflate(R.menu.option_toot, popup.getMenu()); - if( notification.getType().equals("mention")) + if (notification.getType().equals("mention")) popup.getMenu().findItem(R.id.action_timed_mute).setVisible(true); else popup.getMenu().findItem(R.id.action_timed_mute).setVisible(false); - if( status.getVisibility().equals("private") || status.getVisibility().equals("direct")){ + if (status.getVisibility().equals("private") || status.getVisibility().equals("direct")) { popup.getMenu().findItem(R.id.action_mention).setVisible(false); } - if( popup.getMenu().findItem(R.id.action_redraft) != null) + if (popup.getMenu().findItem(R.id.action_redraft) != null) popup.getMenu().findItem(R.id.action_redraft).setVisible(false); - if( popup.getMenu().findItem(R.id.action_translate) != null) + if (popup.getMenu().findItem(R.id.action_translate) != null) popup.getMenu().findItem(R.id.action_translate).setVisible(false); final String[] stringArrayConf; - if( isOwner) { + if (isOwner) { popup.getMenu().findItem(R.id.action_block).setVisible(false); popup.getMenu().findItem(R.id.action_mute).setVisible(false); popup.getMenu().findItem(R.id.action_report).setVisible(false); - stringArrayConf = context.getResources().getStringArray(R.array.more_action_owner_confirm); - if( social != UpdateAccountInfoAsyncTask.SOCIAL.MASTODON && social != UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA){ + stringArrayConf = context.getResources().getStringArray(R.array.more_action_owner_confirm); + if (social != UpdateAccountInfoAsyncTask.SOCIAL.MASTODON && social != UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { popup.getMenu().findItem(R.id.action_stats).setVisible(false); } - }else { + } else { popup.getMenu().findItem(R.id.action_stats).setVisible(false); popup.getMenu().findItem(R.id.action_remove).setVisible(false); - stringArrayConf = context.getResources().getStringArray(R.array.more_action_confirm); + stringArrayConf = context.getResources().getStringArray(R.array.more_action_confirm); } if (status.getAccount().getAcct().split("@").length < 2) popup.getMenu().findItem(R.id.action_block_domain).setVisible(false); - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA){ + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { popup.getMenu().findItem(R.id.action_info).setVisible(false); popup.getMenu().findItem(R.id.action_report).setVisible(false); popup.getMenu().findItem(R.id.action_block_domain).setVisible(false); popup.getMenu().findItem(R.id.action_mute_conversation).setVisible(false); } - if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.MASTODON){ + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { popup.getMenu().findItem(R.id.action_admin).setVisible(false); - }else{ + } else { boolean display_admin_statuses = sharedpreferences.getBoolean(Helper.SET_DISPLAY_ADMIN_STATUSES + userId + Helper.getLiveInstance(context), false); - if( !display_admin_statuses){ + if (!display_admin_statuses) { popup.getMenu().findItem(R.id.action_admin).setVisible(false); } } @@ -942,7 +938,7 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On else popup.getMenu().findItem(R.id.action_mute_conversation).setTitle(R.string.mute_conversation); boolean custom_sharing = sharedpreferences.getBoolean(Helper.SET_CUSTOM_SHARING, false); - if( custom_sharing && status.getVisibility().equals("public")) + if (custom_sharing && status.getVisibility().equals("public")) popup.getMenu().findItem(R.id.action_custom_sharing).setVisible(true); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @@ -966,7 +962,7 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On doAction = API.StatusAction.MUTE; break; case R.id.action_mute_conversation: - if( status.isMuted()) + if (status.isMuted()) doAction = API.StatusAction.UNMUTE_CONVERSATION; else doAction = API.StatusAction.MUTE_CONVERSATION; @@ -986,7 +982,7 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On case R.id.action_stats: intent = new Intent(context, OwnerNotificationChartsActivity.class); b = new Bundle(); - b.putString("status_id", status.getReblog()!=null?status.getReblog().getId():status.getId()); + b.putString("status_id", status.getReblog() != null ? status.getReblog().getId() : status.getId()); intent.putExtras(b); context.startActivity(intent); return true; @@ -1038,12 +1034,12 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On ClipData clip = ClipData.newPlainText(Helper.CLIP_BOARD, content); assert clipboard != null; clipboard.setPrimaryClip(clip); - Toasty.info(context,context.getString(R.string.clipboard),Toast.LENGTH_LONG).show(); + Toasty.info(context, context.getString(R.string.clipboard), Toast.LENGTH_LONG).show(); return true; case R.id.action_copy_link: clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); - clip = ClipData.newPlainText(Helper.CLIP_BOARD, status.getReblog()!=null?status.getReblog().getUrl():status.getUrl()); + clip = ClipData.newPlainText(Helper.CLIP_BOARD, status.getReblog() != null ? status.getReblog().getUrl() : status.getUrl()); if (clipboard != null) { clipboard.setPrimaryClip(clip); Toasty.info(context, context.getString(R.string.clipboard_url), Toast.LENGTH_LONG).show(); @@ -1073,26 +1069,27 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On handler.postDelayed(new Runnable() { @Override public void run() { - String name = "@"+(status.getReblog()!=null?status.getReblog().getAccount().getAcct():status.getAccount().getAcct()); - if( name.split("@", -1).length - 1 == 1) + String name = "@" + (status.getReblog() != null ? status.getReblog().getAccount().getAcct() : status.getAccount().getAcct()); + if (name.split("@", -1).length - 1 == 1) name = name + "@" + Helper.getLiveInstance(context); Bitmap bitmap = Helper.convertTootIntoBitmap(context, name, holder.notification_status_content); Intent intent = new Intent(context, TootActivity.class); Bundle b = new Bundle(); - String fname = "tootmention_" + status.getId() +".jpg"; - File file = new File (context.getCacheDir() + "/", fname); - if (file.exists ()) //noinspection ResultOfMethodCallIgnored - file.delete (); + String fname = "tootmention_" + status.getId() + ".jpg"; + File file = new File(context.getCacheDir() + "/", fname); + if (file.exists()) //noinspection ResultOfMethodCallIgnored + file.delete(); try { FileOutputStream out = new FileOutputStream(file); assert bitmap != null; bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); out.flush(); out.close(); - } catch (Exception ignored) {} + } catch (Exception ignored) { + } b.putString("fileMention", fname); - b.putString("tootMention", (status.getReblog() != null)?status.getReblog().getAccount().getAcct():status.getAccount().getAcct()); - b.putString("urlMention", (status.getReblog() != null)?status.getReblog().getUrl():status.getUrl()); + b.putString("tootMention", (status.getReblog() != null) ? status.getReblog().getAccount().getAcct() : status.getAccount().getAcct()); + b.putString("urlMention", (status.getReblog() != null) ? status.getReblog().getUrl() : status.getUrl()); intent.putExtras(b); context.startActivity(intent); } @@ -1105,7 +1102,7 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On //Text for report EditText input = null; - if( doAction == API.StatusAction.REPORT){ + if (doAction == API.StatusAction.REPORT) { input = new EditText(context); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, @@ -1115,23 +1112,23 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On } builderInner.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog,int which) { + public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); final EditText finalInput = input; builderInner.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog,int which) { - if(doAction == API.StatusAction.UNSTATUS ){ + public void onClick(DialogInterface dialog, int which) { + if (doAction == API.StatusAction.UNSTATUS) { String targetedId = status.getId(); new PostActionAsyncTask(context, doAction, targetedId, NotificationsListAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else if(doAction == API.StatusAction.REPORT ){ + } else if (doAction == API.StatusAction.REPORT) { String comment = null; - if( finalInput.getText() != null) + if (finalInput.getText() != null) comment = finalInput.getText().toString(); new PostActionAsyncTask(context, doAction, status.getId(), status, comment, NotificationsListAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else{ + } else { String targetedId = status.getAccount().getId(); new PostActionAsyncTask(context, doAction, targetedId, NotificationsListAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } @@ -1150,12 +1147,15 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (motionEvent.getAction() == MotionEvent.ACTION_UP && !view.hasFocus()) { - try{view.requestFocus();}catch (Exception ignored){} + try { + view.requestFocus(); + } catch (Exception ignored) { + } } return false; } }); - if( theme == Helper.THEME_LIGHT) { + if (theme == Helper.THEME_LIGHT) { holder.status_show_more.setTextColor(ContextCompat.getColor(context, R.color.white)); } @@ -1164,12 +1164,12 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On } - private void notifyNotificationChanged(Notification notification){ + private void notifyNotificationChanged(Notification notification) { for (int i = 0; i < notificationsListAdapter.getItemCount(); i++) { if (notificationsListAdapter.getItemAt(i) != null && notificationsListAdapter.getItemAt(i).getId().trim().compareTo(notification.getId().trim()) == 0) { try { - if( mRecyclerView != null) { + if (mRecyclerView != null) { int finalI = i; mRecyclerView.post(new Runnable() { @Override @@ -1179,20 +1179,21 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On }); } break; - } catch (Exception ignored) {} + } catch (Exception ignored) { + } } } } - public void notifyNotificationWithActionChanged(Status status){ + public void notifyNotificationWithActionChanged(Status status) { for (int i = 0; i < notificationsListAdapter.getItemCount(); i++) { if (notificationsListAdapter.getItemAt(i) != null && notificationsListAdapter.getItemAt(i).getStatus() != null && notificationsListAdapter.getItemAt(i).getStatus().getId().equals(status.getId())) { try { - if( notifications.get(i).getStatus() != null){ + if (notifications.get(i).getStatus() != null) { notifications.get(i).setStatus(status); notifyItemChanged(i); - if( mRecyclerView != null) { + if (mRecyclerView != null) { int finalI = i; mRecyclerView.post(new Runnable() { @Override @@ -1203,7 +1204,8 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On } break; } - } catch (Exception ignored) {} + } catch (Exception ignored) { + } } } } @@ -1219,8 +1221,8 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On } - private Notification getItemAt(int position){ - if( notifications.size() > position) + private Notification getItemAt(int position) { + if (notifications.size() > position) return notifications.get(position); else return null; @@ -1228,9 +1230,10 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On /** * Display a validation message for notification deletion + * * @param notification Notification */ - private void displayConfirmationNotificationDialog(final Notification notification){ + private void displayConfirmationNotificationDialog(final Notification notification) { final ArrayList seletedItems = new ArrayList(); AlertDialog dialog = new AlertDialog.Builder(context, style) @@ -1241,7 +1244,7 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On if (isChecked) { //noinspection unchecked seletedItems.add(indexSelected); - } else { + } else { if (seletedItems.contains(indexSelected)) seletedItems.remove(Integer.valueOf(indexSelected)); } @@ -1267,16 +1270,16 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On @Override public void onPostAction(int statusCode, API.StatusAction statusAction, String targetedId, Error error) { - if( error != null){ - Toasty.error(context, error.getError(),Toast.LENGTH_LONG).show(); + if (error != null) { + Toasty.error(context, error.getError(), Toast.LENGTH_LONG).show(); return; } Helper.manageMessageStatusCode(context, statusCode, statusAction); //When muting or blocking an account, its status are removed from the list List notificationsToRemove = new ArrayList<>(); - if( statusAction == API.StatusAction.MUTE || statusAction == API.StatusAction.BLOCK){ - for(Notification notification: notifications){ - if( notification.getType().toLowerCase().equals("mention") && notification.getAccount().getId().equals(targetedId)) + if (statusAction == API.StatusAction.MUTE || statusAction == API.StatusAction.BLOCK) { + for (Notification notification : notifications) { + if (notification.getType().toLowerCase().equals("mention") && notification.getAccount().getId().equals(targetedId)) notificationsToRemove.add(notification); } notifications.removeAll(notificationsToRemove); @@ -1286,11 +1289,11 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On @Override public void onPostNotificationsAction(APIResponse apiResponse, String targetedId) { - if(apiResponse.getError() != null){ - Toasty.error(context, context.getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + if (apiResponse.getError() != null) { + Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); return; } - if( targetedId != null){ + if (targetedId != null) { int position = 0; for (Notification notif : notifications) { if (notif.getId().equals(targetedId)) { @@ -1300,76 +1303,76 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On } position++; } - Toasty.success(context,context.getString(R.string.delete_notification),Toast.LENGTH_LONG).show(); - }else{ + Toasty.success(context, context.getString(R.string.delete_notification), Toast.LENGTH_LONG).show(); + } else { int size = notifications.size(); notifications.clear(); notificationsListAdapter.notifyItemRangeRemoved(0, size); - Toasty.success(context,context.getString(R.string.delete_notification_all),Toast.LENGTH_LONG).show(); + Toasty.success(context, context.getString(R.string.delete_notification_all), Toast.LENGTH_LONG).show(); } } - private void loadAttachments(final Notification notification, ViewHolder holder){ + private void loadAttachments(final Notification notification, ViewHolder holder) { List attachments = notification.getStatus().getMedia_attachments(); - if( attachments != null && attachments.size() > 0){ + if (attachments != null && attachments.size() > 0) { int i = 0; holder.status_document_container.setVisibility(View.VISIBLE); - if( attachments.size() == 1){ + if (attachments.size() == 1) { holder.status_container2.setVisibility(View.GONE); - if( attachments.get(0).getUrl().trim().contains("missing.png")) + if (attachments.get(0).getUrl().trim().contains("missing.png")) holder.status_document_container.setVisibility(View.GONE); - }else if(attachments.size() == 2){ + } else if (attachments.size() == 2) { holder.status_container2.setVisibility(View.VISIBLE); holder.status_container3.setVisibility(View.GONE); holder.status_prev4_container.setVisibility(View.GONE); - if( attachments.get(1).getUrl().trim().contains("missing.png")) + if (attachments.get(1).getUrl().trim().contains("missing.png")) holder.status_container2.setVisibility(View.GONE); - }else if( attachments.size() == 3){ + } else if (attachments.size() == 3) { holder.status_container2.setVisibility(View.VISIBLE); holder.status_container3.setVisibility(View.VISIBLE); holder.status_prev4_container.setVisibility(View.GONE); - if( attachments.get(2).getUrl().trim().contains("missing.png")) + if (attachments.get(2).getUrl().trim().contains("missing.png")) holder.status_container3.setVisibility(View.GONE); - }else { + } else { holder.status_container2.setVisibility(View.VISIBLE); holder.status_container3.setVisibility(View.VISIBLE); holder.status_prev4_container.setVisibility(View.VISIBLE); - if( attachments.get(2).getUrl().trim().contains("missing.png")) + if (attachments.get(2).getUrl().trim().contains("missing.png")) holder.status_prev4_container.setVisibility(View.GONE); } int position = 1; - for(final Attachment attachment: attachments){ + for (final Attachment attachment : attachments) { ImageView imageView; - if( i == 0) { + if (i == 0) { imageView = holder.status_prev1; - if( attachment.getType().toLowerCase().equals("image")) + if (attachment.getType().toLowerCase().equals("image")) holder.status_prev1_play.setVisibility(View.GONE); else holder.status_prev1_play.setVisibility(View.VISIBLE); - }else if( i == 1) { + } else if (i == 1) { imageView = holder.status_prev2; - if( attachment.getType().toLowerCase().equals("image")) + if (attachment.getType().toLowerCase().equals("image")) holder.status_prev2_play.setVisibility(View.GONE); else holder.status_prev2_play.setVisibility(View.VISIBLE); - }else if(i == 2) { + } else if (i == 2) { imageView = holder.status_prev3; - if( attachment.getType().toLowerCase().equals("image")) + if (attachment.getType().toLowerCase().equals("image")) holder.status_prev3_play.setVisibility(View.GONE); else holder.status_prev3_play.setVisibility(View.VISIBLE); - }else { + } else { imageView = holder.status_prev4; - if( attachment.getType().toLowerCase().equals("image")) + if (attachment.getType().toLowerCase().equals("image")) holder.status_prev4_play.setVisibility(View.GONE); else holder.status_prev4_play.setVisibility(View.VISIBLE); } String url = attachment.getPreview_url(); - if( url == null || url.trim().equals("")) + if (url == null || url.trim().equals("")) url = attachment.getUrl(); - if( !url.trim().contains("missing.png")) + if (!url.trim().contains("missing.png")) Glide.with(imageView.getContext()) .load(url) .into(imageView); @@ -1388,7 +1391,7 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On i++; position++; } - }else{ + } else { holder.status_document_container.setVisibility(View.GONE); } holder.status_show_more.setVisibility(View.GONE); @@ -1402,7 +1405,7 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On @Override public void onRetrieveEmoji(Notification notification) { - if( notification != null && notification.getStatus() != null) { + if (notification != null && notification.getStatus() != null) { notifyNotificationChanged(notification); } } @@ -1426,8 +1429,8 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On @Override public void onRetrieveEmojiAccount(Account account) { - for( Notification notification: notifications){ - if( notification.getAccount().equals(account)){ + for (Notification notification : notifications) { + if (notification.getAccount().equals(account)) { notifyNotificationChanged(notification); } } @@ -1441,7 +1444,7 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On @Override public void onRetrieveImage(Status status, boolean fromTranslation) { - if( status != null ) { + if (status != null) { status.setEmojiFound(true); notifyNotificationWithActionChanged(status); } @@ -1491,7 +1494,7 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On TextView number_votes, remaining_time; Button submit_vote, refresh_poll; - public View getView(){ + public View getView() { return itemView; } @@ -1531,8 +1534,8 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On status_spoiler_mention_container = itemView.findViewById(R.id.status_spoiler_mention_container); status_mention_spoiler = itemView.findViewById(R.id.status_mention_spoiler); status_reply = itemView.findViewById(R.id.status_reply); - spark_button_fav = itemView.findViewById(R.id.spark_button_fav); - spark_button_reblog = itemView.findViewById(R.id.spark_button_reblog); + spark_button_fav = itemView.findViewById(R.id.spark_button_fav); + spark_button_reblog = itemView.findViewById(R.id.spark_button_reblog); poll_container = itemView.findViewById(R.id.poll_container); @@ -1556,8 +1559,8 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); boolean disableAnimatedEmoji = sharedpreferences.getBoolean(Helper.SET_DISABLE_ANIMATED_EMOJI, false); - if( !disableAnimatedEmoji ){ - if( BaseMainActivity.timer == null){ + if (!disableAnimatedEmoji) { + if (BaseMainActivity.timer == null) { BaseMainActivity.timer = new Timer(); } BaseMainActivity.timer.schedule(new TimerTask() { diff --git a/app/src/main/java/app/fedilab/android/drawers/PeertubeAdapter.java b/app/src/main/java/app/fedilab/android/drawers/PeertubeAdapter.java index 4d7eb3724..afad88b4e 100644 --- a/app/src/main/java/app/fedilab/android/drawers/PeertubeAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/PeertubeAdapter.java @@ -19,8 +19,10 @@ import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; + import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -49,7 +51,6 @@ import app.fedilab.android.asynctasks.UpdateAccountInfoAsyncTask; import app.fedilab.android.interfaces.OnListActionInterface; - /** * Created by Thomas on 06/10/2018. * Adapter for peertube @@ -62,14 +63,14 @@ public class PeertubeAdapter extends RecyclerView.Adapter implements OnListActio private String instance; private boolean ownVideos; - public PeertubeAdapter(String instance, List peertubes){ + public PeertubeAdapter(String instance, List peertubes) { this.peertubes = peertubes; this.instance = instance; this.ownVideos = false; } - public PeertubeAdapter(String instance, boolean ownVideos, List peertubes){ + public PeertubeAdapter(String instance, boolean ownVideos, List peertubes) { this.peertubes = peertubes; this.instance = instance; this.ownVideos = ownVideos; @@ -90,15 +91,15 @@ public class PeertubeAdapter extends RecyclerView.Adapter implements OnListActio final PeertubeAdapter.ViewHolder holder = (PeertubeAdapter.ViewHolder) viewHolder; final Peertube peertube = peertubes.get(position); - if( peertube.getInstance() == null) + if (peertube.getInstance() == null) peertube.setInstance(Helper.getLiveInstance(context)); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if( theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { holder.main_container.setBackgroundResource(R.color.mastodonC3__); - }else if (theme == Helper.THEME_DARK){ + } else if (theme == Helper.THEME_DARK) { holder.main_container.setBackgroundResource(R.color.mastodonC1_); - }else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { holder.main_container.setBackgroundResource(R.color.black); } Account account = peertube.getAccount(); @@ -118,9 +119,9 @@ public class PeertubeAdapter extends RecyclerView.Adapter implements OnListActio Helper.loadGiF(context, account.getAvatar(), holder.peertube_profile); - if( peertube.getHeaderType() != null && peertube.getHeaderTypeValue() != null) { + if (peertube.getHeaderType() != null && peertube.getHeaderTypeValue() != null) { String type = peertube.getHeaderType(); - switch (type){ + switch (type) { case "tags": holder.header_title.setText(String.format("#%s", peertube.getHeaderTypeValue())); break; @@ -129,11 +130,11 @@ public class PeertubeAdapter extends RecyclerView.Adapter implements OnListActio break; } holder.header_title.setVisibility(View.VISIBLE); - }else { + } else { holder.header_title.setVisibility(View.GONE); } - if( !this.ownVideos) { + if (!this.ownVideos) { holder.peertube_profile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -171,13 +172,13 @@ public class PeertubeAdapter extends RecyclerView.Adapter implements OnListActio context.startActivity(intent); } }); - }else{ + } else { holder.main_container.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, PeertubeEditUploadActivity.class); Bundle b = new Bundle(); - b.putString("video_id",peertube.getUuid()); + b.putString("video_id", peertube.getUuid()); intent.putExtras(b); context.startActivity(intent); } @@ -202,7 +203,7 @@ public class PeertubeAdapter extends RecyclerView.Adapter implements OnListActio } - class ViewHolder extends RecyclerView.ViewHolder{ + class ViewHolder extends RecyclerView.ViewHolder { LinearLayout main_container; ImageView peertube_profile, peertube_video_image; TextView peertube_account_name, peertube_views, peertube_duration; @@ -223,6 +224,4 @@ public class PeertubeAdapter extends RecyclerView.Adapter implements OnListActio } - - } \ No newline at end of file diff --git a/app/src/main/java/app/fedilab/android/drawers/PeertubeNotificationsListAdapter.java b/app/src/main/java/app/fedilab/android/drawers/PeertubeNotificationsListAdapter.java index fc8c046bb..c0b87a1ac 100644 --- a/app/src/main/java/app/fedilab/android/drawers/PeertubeNotificationsListAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/PeertubeNotificationsListAdapter.java @@ -19,9 +19,11 @@ import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; + import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.RecyclerView; + import android.text.Html; import android.view.LayoutInflater; import android.view.View; @@ -54,7 +56,7 @@ public class PeertubeNotificationsListAdapter extends RecyclerView.Adapter { private List notifications; private PeertubeNotificationsListAdapter peertubeNotificationsListAdapter; - public PeertubeNotificationsListAdapter( List notifications){ + public PeertubeNotificationsListAdapter(List notifications) { this.notifications = notifications; peertubeNotificationsListAdapter = this; @@ -76,28 +78,28 @@ public class PeertubeNotificationsListAdapter extends RecyclerView.Adapter { PeertubeNotification notification = notifications.get(position); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if (theme == Helper.THEME_DARK ){ + if (theme == Helper.THEME_DARK) { holder.main_container_trans.setBackgroundColor(ContextCompat.getColor(context, R.color.notif_dark_1)); holder.main_container_trans.setAlpha(.5f); - }else if( theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { holder.main_container_trans.setBackgroundColor(ContextCompat.getColor(context, R.color.notif_black_1)); holder.main_container_trans.setAlpha(.5f); - }else{ + } else { holder.main_container_trans.setBackgroundColor(ContextCompat.getColor(context, R.color.notif_light_1)); holder.main_container_trans.setAlpha(.5f); } //Follow Notification PeertubeAccountNotification accountAction = null; PeertubeVideoNotification videoAction; - if( notification.getPeertubeActorFollow() != null){ + if (notification.getPeertubeActorFollow() != null) { String profileUrl = Helper.getLiveInstanceWithProtocol(context) + notification.getPeertubeActorFollow().getFollower().getAvatar(); - Helper.loadGiF(context,profileUrl, holder.peertube_notif_pp); - accountAction =notification.getPeertubeActorFollow().getFollower(); + Helper.loadGiF(context, profileUrl, holder.peertube_notif_pp); + accountAction = notification.getPeertubeActorFollow().getFollower(); String type = notification.getPeertubeActorFollow().getFollowing().getType(); String message; - if( type != null && type.equals("account")){ + if (type != null && type.equals("account")) { message = context.getString(R.string.peertube_follow_channel, notification.getPeertubeActorFollow().getFollower().getDisplayName(), notification.getPeertubeActorFollow().getFollowing().getDisplayName()); - }else{ + } else { message = context.getString(R.string.peertube_follow_account, accountAction.getDisplayName()); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) @@ -113,12 +115,12 @@ public class PeertubeNotificationsListAdapter extends RecyclerView.Adapter { intent.putExtras(b); context.startActivity(intent); }); - }else if( notification.getPeertubeComment() != null){ //Comment Notification + } else if (notification.getPeertubeComment() != null) { //Comment Notification String profileUrl = Helper.getLiveInstanceWithProtocol(context) + notification.getPeertubeComment().getPeertubeAccountNotification().getAvatar(); Helper.loadGiF(context, profileUrl, holder.peertube_notif_pp); accountAction = notification.getPeertubeComment().getPeertubeAccountNotification(); - videoAction = notification.getPeertubeComment().getPeertubeVideoNotification(); - String message = context.getString(R.string.peertube_comment_on_video,accountAction.getDisplayName(), videoAction.getName()); + videoAction = notification.getPeertubeComment().getPeertubeVideoNotification(); + String message = context.getString(R.string.peertube_comment_on_video, accountAction.getDisplayName(), videoAction.getName()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) holder.peertube_notif_message.setText(Html.fromHtml(message, Html.FROM_HTML_MODE_LEGACY)); @@ -133,24 +135,24 @@ public class PeertubeNotificationsListAdapter extends RecyclerView.Adapter { intent.putExtras(b); context.startActivity(intent); }); - }else {//Other Notifications - if (notification.getPeertubeVideoNotification() != null && notification.getPeertubeVideoNotification().getPeertubeAccountNotification() != null){ + } else {//Other Notifications + if (notification.getPeertubeVideoNotification() != null && notification.getPeertubeVideoNotification().getPeertubeAccountNotification() != null) { String profileUrl = Helper.getLiveInstanceWithProtocol(context) + notification.getPeertubeVideoNotification().getPeertubeAccountNotification().getAvatar(); Helper.loadGiF(context, profileUrl, holder.peertube_notif_pp); accountAction = notification.getPeertubeVideoNotification().getPeertubeAccountNotification(); - videoAction = notification.getPeertubeVideoNotification(); + videoAction = notification.getPeertubeVideoNotification(); String message = ""; - if (notification.getType() == DisplayPeertubeNotificationsFragment.MY_VIDEO_PUBLISHED){ + if (notification.getType() == DisplayPeertubeNotificationsFragment.MY_VIDEO_PUBLISHED) { message = context.getString(R.string.peertube_video_published, videoAction.getName()); - }else if(notification.getType() == DisplayPeertubeNotificationsFragment.MY_VIDEO_IMPORT_ERROR){ + } else if (notification.getType() == DisplayPeertubeNotificationsFragment.MY_VIDEO_IMPORT_ERROR) { message = context.getString(R.string.peertube_video_import_error, videoAction.getName()); - }else if(notification.getType() == DisplayPeertubeNotificationsFragment.MY_VIDEO_IMPORT_SUCCESS){ + } else if (notification.getType() == DisplayPeertubeNotificationsFragment.MY_VIDEO_IMPORT_SUCCESS) { message = context.getString(R.string.peertube_video_import_success, videoAction.getName()); - }else if(notification.getType() == DisplayPeertubeNotificationsFragment.NEW_VIDEO_FROM_SUBSCRIPTION){ + } else if (notification.getType() == DisplayPeertubeNotificationsFragment.NEW_VIDEO_FROM_SUBSCRIPTION) { message = context.getString(R.string.peertube_video_from_subscription, accountAction.getDisplayName(), videoAction.getName()); - }else if(notification.getType() == DisplayPeertubeNotificationsFragment.BLACKLIST_ON_MY_VIDEO){ + } else if (notification.getType() == DisplayPeertubeNotificationsFragment.BLACKLIST_ON_MY_VIDEO) { message = context.getString(R.string.peertube_video_blacklist, videoAction.getName()); - }else if(notification.getType() == DisplayPeertubeNotificationsFragment.UNBLACKLIST_ON_MY_VIDEO){ + } else if (notification.getType() == DisplayPeertubeNotificationsFragment.UNBLACKLIST_ON_MY_VIDEO) { message = context.getString(R.string.peertube_video_unblacklist, videoAction.getName()); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) @@ -171,7 +173,7 @@ public class PeertubeNotificationsListAdapter extends RecyclerView.Adapter { holder.peertube_notif_date.setText(Helper.dateDiff(context, notification.getCreatedAt())); PeertubeAccountNotification finalAccountAction = accountAction; holder.peertube_notif_pp.setOnClickListener(v -> { - if( finalAccountAction != null){ + if (finalAccountAction != null) { Intent intent = new Intent(context, ShowAccountActivity.class); Bundle b = new Bundle(); b.putBoolean("peertubeaccount", true); @@ -182,18 +184,18 @@ public class PeertubeNotificationsListAdapter extends RecyclerView.Adapter { }); } - private void notifyNotificationChanged(Notification notification){ + private void notifyNotificationChanged(Notification notification) { for (int i = 0; i < peertubeNotificationsListAdapter.getItemCount(); i++) { if (peertubeNotificationsListAdapter.getItemAt(i) != null && peertubeNotificationsListAdapter.getItemAt(i).getId().equals(notification.getId())) { try { peertubeNotificationsListAdapter.notifyItemChanged(i); - } catch (Exception ignored) { } + } catch (Exception ignored) { + } } } } - @Override public long getItemId(int position) { return position; @@ -205,8 +207,8 @@ public class PeertubeNotificationsListAdapter extends RecyclerView.Adapter { } - private PeertubeNotification getItemAt(int position){ - if( notifications.size() > position) + private PeertubeNotification getItemAt(int position) { + if (notifications.size() > position) return notifications.get(position); else return null; @@ -218,7 +220,8 @@ public class PeertubeNotificationsListAdapter extends RecyclerView.Adapter { ImageView peertube_notif_pp; TextView peertube_notif_message, peertube_notif_date; RelativeLayout main_container_trans; - public View getView(){ + + public View getView() { return itemView; } diff --git a/app/src/main/java/app/fedilab/android/drawers/PixelfedListAdapter.java b/app/src/main/java/app/fedilab/android/drawers/PixelfedListAdapter.java index 8b1a26890..9666c6bf2 100644 --- a/app/src/main/java/app/fedilab/android/drawers/PixelfedListAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/PixelfedListAdapter.java @@ -21,11 +21,13 @@ import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.os.Bundle; + import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; import androidx.cardview.widget.CardView; import androidx.recyclerview.widget.RecyclerView; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -87,7 +89,7 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA private static final int DISPLAYED_STATUS = 1; private RetrieveFeedsAsyncTask.Type type; - public PixelfedListAdapter(RetrieveFeedsAsyncTask.Type type, List statuses){ + public PixelfedListAdapter(RetrieveFeedsAsyncTask.Type type, List statuses) { super(); this.statuses = statuses; this.type = type; @@ -106,8 +108,8 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA return statuses.size(); } - private Status getItemAt(int position){ - if( statuses.size() > position) + private Status getItemAt(int position) { + if (statuses.size() > position) return statuses.get(position); else return null; @@ -115,7 +117,7 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA @Override public void onRetrieveReplies(APIResponse apiResponse) { - if( apiResponse.getError() != null || apiResponse.getStatuses() == null || apiResponse.getStatuses().size() == 0){ + if (apiResponse.getError() != null || apiResponse.getStatuses() == null || apiResponse.getStatuses().size() == 0) { return; } List modifiedStatus = apiResponse.getStatuses(); @@ -123,7 +125,7 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA } - private class ViewHolderEmpty extends RecyclerView.ViewHolder{ + private class ViewHolderEmpty extends RecyclerView.ViewHolder { ViewHolderEmpty(View itemView) { super(itemView); } @@ -135,12 +137,13 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA } - private class ViewHolderPixelfed extends RecyclerView.ViewHolder{ + private class ViewHolderPixelfed extends RecyclerView.ViewHolder { ImageView art_media, pf_pp, pf_comment; SparkButton pf_fav, pf_share; TextView pf_username, pf_likes, pf_description, pf_date; CardView pf_cardview; LinearLayout pf_bottom_container; + ViewHolderPixelfed(View itemView) { super(itemView); art_media = itemView.findViewById(R.id.art_media); @@ -158,10 +161,8 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA } - - - public Status getItem(int position){ - if( statuses.size() > position && position >= 0) + public Status getItem(int position) { + if (statuses.size() > position && position >= 0) return statuses.get(position); else return null; } @@ -170,11 +171,11 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA public int getItemViewType(int position) { boolean show_boosts = false; boolean show_replies = false; - if( context instanceof ShowAccountActivity){ + if (context instanceof ShowAccountActivity) { show_boosts = ((ShowAccountActivity) context).showBoosts(); show_replies = ((ShowAccountActivity) context).showReplies(); } - if( !Helper.filterToots(statuses.get(position), null, context instanceof ShowAccountActivity,show_boosts, show_replies)) + if (!Helper.filterToots(statuses.get(position), null, context instanceof ShowAccountActivity, show_boosts, show_replies)) return HIDDEN_STATUS; else return DISPLAYED_STATUS; @@ -185,20 +186,19 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { context = parent.getContext(); LayoutInflater layoutInflater = LayoutInflater.from(this.context); - if( viewType == DISPLAYED_STATUS) + if (viewType == DISPLAYED_STATUS) return new ViewHolderPixelfed(layoutInflater.inflate(R.layout.drawer_pixelfed, parent, false)); else return new ViewHolderEmpty(layoutInflater.inflate(R.layout.drawer_empty, parent, false)); } - @SuppressLint("SetJavaScriptEnabled") @Override public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder viewHolder, int i) { final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); final String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - if( viewHolder.getItemViewType() != HIDDEN_STATUS ) { + if (viewHolder.getItemViewType() != HIDDEN_STATUS) { final ViewHolderPixelfed holder = (ViewHolderPixelfed) viewHolder; final Status status = statuses.get(viewHolder.getAdapterPosition()); if (!status.isClickable()) @@ -282,7 +282,6 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA }); - if (status.getDisplayNameSpan() != null && status.getDisplayNameSpan().toString().trim().length() > 0) holder.pf_username.setText(status.getDisplayNameSpan(), TextView.BufferType.SPANNABLE); else @@ -290,7 +289,6 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if (theme == Helper.THEME_BLACK) { holder.pf_fav.setInActiveImageTint(R.color.action_black); holder.pf_share.setInActiveImageTint(R.color.action_black); @@ -382,48 +380,43 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA } - - - - - @Override public void onPostAction(int statusCode, API.StatusAction statusAction, String targetedId, Error error) { final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - if( error != null){ - Toasty.error(context, error.getError(),Toast.LENGTH_LONG).show(); + if (error != null) { + Toasty.error(context, error.getError(), Toast.LENGTH_LONG).show(); return; } Helper.manageMessageStatusCode(context, statusCode, statusAction); //When muting or blocking an account, its status are removed from the list List statusesToRemove = new ArrayList<>(); - if( statusAction == API.StatusAction.MUTE || statusAction == API.StatusAction.BLOCK){ - for(Status status: statuses){ - if( status.getAccount().getId().equals(targetedId)) + if (statusAction == API.StatusAction.MUTE || statusAction == API.StatusAction.BLOCK) { + for (Status status : statuses) { + if (status.getAccount().getId().equals(targetedId)) statusesToRemove.add(status); } statuses.removeAll(statusesToRemove); pixelfedListAdapter.notifyDataSetChanged(); - }else if( statusAction == API.StatusAction.UNSTATUS ){ + } else if (statusAction == API.StatusAction.UNSTATUS) { int position = 0; - for(Status status: statuses){ - if( status.getId().equals(targetedId)) { + for (Status status : statuses) { + if (status.getId().equals(targetedId)) { statuses.remove(status); pixelfedListAdapter.notifyItemRemoved(position); SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); //Remove the status from cache also try { - new StatusCacheDAO(context, db).remove(StatusCacheDAO.ARCHIVE_CACHE,status); - }catch (Exception ignored){} + new StatusCacheDAO(context, db).remove(StatusCacheDAO.ARCHIVE_CACHE, status); + } catch (Exception ignored) { + } break; } position++; } - } - else if ( statusAction == API.StatusAction.PIN || statusAction == API.StatusAction.UNPIN ) { + } else if (statusAction == API.StatusAction.PIN || statusAction == API.StatusAction.UNPIN) { int position = 0; - for (Status status: statuses) { + for (Status status : statuses) { if (status.getId().equals(targetedId)) { if (statusAction == API.StatusAction.PIN) status.setPinned(true); @@ -435,10 +428,10 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA position++; } } - if( statusAction == API.StatusAction.PEERTUBEDELETECOMMENT){ + if (statusAction == API.StatusAction.PEERTUBEDELETECOMMENT) { int position = 0; - for(Status status: statuses){ - if( status.getId().equals(targetedId)) { + for (Status status : statuses) { + if (status.getId().equals(targetedId)) { statuses.remove(status); pixelfedListAdapter.notifyItemRemoved(position); break; @@ -448,7 +441,7 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA } } - public void notifyStatusChanged(Status status){ + public void notifyStatusChanged(Status status) { for (int i = 0; i < pixelfedListAdapter.getItemCount(); i++) { //noinspection ConstantConditions if (pixelfedListAdapter.getItemAt(i) != null && pixelfedListAdapter.getItemAt(i).getId().equals(status.getId())) { @@ -460,7 +453,7 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA } } - public void notifyStatusWithActionChanged(Status status){ + public void notifyStatusWithActionChanged(Status status) { for (int i = 0; i < pixelfedListAdapter.getItemCount(); i++) { //noinspection ConstantConditions if (pixelfedListAdapter.getItemAt(i) != null && pixelfedListAdapter.getItemAt(i).getId().equals(status.getId())) { @@ -476,11 +469,11 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA @Override public void onRetrieveEmoji(Status status, boolean fromTranslation) { - if( status != null) { - if( !fromTranslation) { - status.setEmojiFound(true); - }else { - status.setEmojiTranslateFound(true); + if (status != null) { + if (!fromTranslation) { + status.setEmojiFound(true); + } else { + status.setEmojiTranslateFound(true); } notifyStatusChanged(status); } diff --git a/app/src/main/java/app/fedilab/android/drawers/PlaylistAdapter.java b/app/src/main/java/app/fedilab/android/drawers/PlaylistAdapter.java index 69115e4dc..56a1c7b17 100644 --- a/app/src/main/java/app/fedilab/android/drawers/PlaylistAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/PlaylistAdapter.java @@ -23,7 +23,9 @@ import android.content.SharedPreferences; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; + import androidx.core.content.ContextCompat; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -55,7 +57,7 @@ public class PlaylistAdapter extends BaseAdapter implements OnPlaylistActionInte private PlaylistAdapter playlistAdapter; private RelativeLayout textviewNoAction; - public PlaylistAdapter(Context context, List lists, RelativeLayout textviewNoAction){ + public PlaylistAdapter(Context context, List lists, RelativeLayout textviewNoAction) { this.playlists = lists; layoutInflater = LayoutInflater.from(context); this.context = context; @@ -96,21 +98,21 @@ public class PlaylistAdapter extends BaseAdapter implements OnPlaylistActionInte SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if( theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { holder.search_container.setBackgroundResource(R.color.mastodonC3__); - Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right,R.color.black); - }else if(theme == Helper.THEME_DARK){ + Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right, R.color.black); + } else if (theme == Helper.THEME_DARK) { holder.search_container.setBackgroundResource(R.color.mastodonC1_); - Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right,R.color.dark_text); - }else if(theme == Helper.THEME_BLACK) { + Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right, R.color.dark_text); + } else if (theme == Helper.THEME_BLACK) { holder.search_container.setBackgroundResource(R.color.black_2); - Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right,R.color.dark_text); + Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right, R.color.dark_text); } Drawable next = ContextCompat.getDrawable(context, R.drawable.ic_keyboard_arrow_right); holder.search_title.setText(playlist.getDisplayName()); assert next != null; final float scale = context.getResources().getDisplayMetrics().density; - next.setBounds(0,0,(int) (30 * scale + 0.5f),(int) (30 * scale + 0.5f)); + next.setBounds(0, 0, (int) (30 * scale + 0.5f), (int) (30 * scale + 0.5f)); holder.search_title.setCompoundDrawables(null, null, next, null); holder.search_container.setOnClickListener(new View.OnClickListener() { @@ -126,9 +128,9 @@ public class PlaylistAdapter extends BaseAdapter implements OnPlaylistActionInte int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } @@ -137,15 +139,15 @@ public class PlaylistAdapter extends BaseAdapter implements OnPlaylistActionInte public boolean onLongClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(context, style); builder.setTitle(context.getString(R.string.action_lists_delete) + ": " + playlist.getDisplayName()); - builder.setMessage(context.getString(R.string.action_lists_confirm_delete) ); + builder.setMessage(context.getString(R.string.action_lists_confirm_delete)); builder.setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { playlists.remove(playlist); playlistAdapter.notifyDataSetChanged(); - new ManagePlaylistsAsyncTask(context, ManagePlaylistsAsyncTask.action.DELETE_PLAYLIST,playlist, null, null, PlaylistAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - if( playlists.size() == 0 && textviewNoAction != null && textviewNoAction.getVisibility() == View.GONE) + new ManagePlaylistsAsyncTask(context, ManagePlaylistsAsyncTask.action.DELETE_PLAYLIST, playlist, null, null, PlaylistAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + if (playlists.size() == 0 && textviewNoAction != null && textviewNoAction.getVisibility() == View.GONE) textviewNoAction.setVisibility(View.VISIBLE); dialog.dismiss(); } diff --git a/app/src/main/java/app/fedilab/android/drawers/ReorderTabAdapter.java b/app/src/main/java/app/fedilab/android/drawers/ReorderTabAdapter.java index 8cb759356..7d43db0ab 100644 --- a/app/src/main/java/app/fedilab/android/drawers/ReorderTabAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/ReorderTabAdapter.java @@ -19,8 +19,10 @@ import android.content.Context; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.graphics.PorterDuff; + import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.RecyclerView; + import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; @@ -30,6 +32,7 @@ import android.widget.TextView; import android.widget.Toast; import org.jetbrains.annotations.NotNull; + import java.util.Collections; import java.util.List; @@ -52,7 +55,7 @@ import app.fedilab.android.activities.ReorderTimelinesActivity; * * @author Paul Burke (ipaulpro) */ -public class ReorderTabAdapter extends RecyclerView.Adapter implements ItemTouchHelperAdapter { +public class ReorderTabAdapter extends RecyclerView.Adapter implements ItemTouchHelperAdapter { private List mItems; @@ -63,7 +66,7 @@ public class ReorderTabAdapter extends RecyclerView.Adapter manageTimelines, OnStartDragListener dragStartListener, OnUndoListener undoListener) { - this. mDragStartListener = dragStartListener; + this.mDragStartListener = dragStartListener; this.mUndoListener = undoListener; this.mItems = manageTimelines; } @@ -83,7 +86,7 @@ public class ReorderTabAdapter extends RecyclerView.Adapter 2 || !tl.isDisplayed()) { + if (count > 2 || !tl.isDisplayed()) { tl.setDisplayed(!tl.isDisplayed()); if (tl.isDisplayed()) { holder.hideView.setImageResource(R.drawable.ic_make_tab_visible); @@ -182,7 +185,7 @@ public class ReorderTabAdapter extends RecyclerView.Adapter reports){ + public ReportsListAdapter(List reports) { this.reports = reports; this.reportsListAdapter = this; } - - @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { @@ -71,46 +70,46 @@ public class ReportsListAdapter extends RecyclerView.Adapter implements OnRetrie Account target_account = report.getTarget_account().getAccount(); Account.makeAccountNameEmoji(context, ReportsListAdapter.this, account); Account.makeAccountNameEmoji(context, ReportsListAdapter.this, target_account); - if( account.getdisplayNameSpan() == null || account.getdisplayNameSpan().toString().trim().equals("")) { - if( account.getDisplay_name() != null && !account.getDisplay_name().trim().equals("")) + if (account.getdisplayNameSpan() == null || account.getdisplayNameSpan().toString().trim().equals("")) { + if (account.getDisplay_name() != null && !account.getDisplay_name().trim().equals("")) holder.account_dn_reporter.setText(Helper.shortnameToUnicode(account.getDisplay_name(), true)); else - holder.account_dn_reporter.setText(account.getUsername().replace("@","")); - }else - holder.account_dn_reporter.setText( account.getdisplayNameSpan(), TextView.BufferType.SPANNABLE); + holder.account_dn_reporter.setText(account.getUsername().replace("@", "")); + } else + holder.account_dn_reporter.setText(account.getdisplayNameSpan(), TextView.BufferType.SPANNABLE); - if( target_account.getdisplayNameSpan() == null || target_account.getdisplayNameSpan().toString().trim().equals("")) { - if( target_account.getDisplay_name() != null && !target_account.getDisplay_name().trim().equals("")) + if (target_account.getdisplayNameSpan() == null || target_account.getdisplayNameSpan().toString().trim().equals("")) { + if (target_account.getDisplay_name() != null && !target_account.getDisplay_name().trim().equals("")) holder.account_dn.setText(Helper.shortnameToUnicode(target_account.getDisplay_name(), true)); else { - if( target_account.getUsername() != null) { + if (target_account.getUsername() != null) { holder.account_dn.setText(target_account.getUsername().replace("@", "")); } } - }else { - if( target_account.getdisplayNameSpan() != null) { + } else { + if (target_account.getdisplayNameSpan() != null) { holder.account_dn.setText(target_account.getdisplayNameSpan(), TextView.BufferType.SPANNABLE); } } - if( target_account.getAvatar() != null) { + if (target_account.getAvatar() != null) { Helper.loadGiF(context, target_account.getAvatar(), holder.account_pp); } Helper.loadGiF(context, account.getAvatar(), holder.account_pp_reporter); - if( target_account.getAcct() != null) { + if (target_account.getAcct() != null) { holder.account_ac.setText(target_account.getAcct()); } holder.report_comment.setText(report.getComment()); - if( report.getStatuses() != null){ + if (report.getStatuses() != null) { holder.report_number_status.setText(String.valueOf(report.getStatuses().size())); - }else{ + } else { holder.report_number_status.setText("0"); } - holder.main_container.setOnClickListener(view ->{ + holder.main_container.setOnClickListener(view -> { Intent intent = new Intent(context, AccountReportActivity.class); Bundle b = new Bundle(); b.putParcelable("report", report); @@ -130,8 +129,8 @@ public class ReportsListAdapter extends RecyclerView.Adapter implements OnRetrie return reports.size(); } - private Report getItemAt(int position){ - if( reports.size() > position) + private Report getItemAt(int position) { + if (reports.size() > position) return reports.get(position); else return null; @@ -142,7 +141,7 @@ public class ReportsListAdapter extends RecyclerView.Adapter implements OnRetrie notifyAccountChanged(account); } - private void notifyAccountChanged(Account account){ + private void notifyAccountChanged(Account account) { for (int i = 0; i < reportsListAdapter.getItemCount(); i++) { //noinspection ConstantConditions if (reportsListAdapter.getItemAt(i) != null && reportsListAdapter.getItemAt(i).getStatuses().size() > 0 && reportsListAdapter.getItemAt(i).getStatuses().get(0).getAccount().getId().equals(account.getId())) { @@ -155,7 +154,7 @@ public class ReportsListAdapter extends RecyclerView.Adapter implements OnRetrie } - private class ViewHolder extends RecyclerView.ViewHolder{ + private class ViewHolder extends RecyclerView.ViewHolder { ImageView account_pp, account_pp_reporter; TextView account_ac; TextView account_dn, account_dn_reporter; diff --git a/app/src/main/java/app/fedilab/android/drawers/ScheduledTootsListAdapter.java b/app/src/main/java/app/fedilab/android/drawers/ScheduledTootsListAdapter.java index e3ab3c67a..39384b896 100644 --- a/app/src/main/java/app/fedilab/android/drawers/ScheduledTootsListAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/ScheduledTootsListAdapter.java @@ -23,7 +23,9 @@ import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; + import androidx.appcompat.app.AlertDialog; + import android.text.Html; import android.text.Spanned; import android.view.LayoutInflater; @@ -82,7 +84,7 @@ public class ScheduledTootsListAdapter extends BaseAdapter implements OnPostActi private RelativeLayout textviewNoAction; private DisplayScheduledTootsFragment.typeOfSchedule type; - public ScheduledTootsListAdapter(Context context, DisplayScheduledTootsFragment.typeOfSchedule type, List storedStatuses, RelativeLayout textviewNoAction){ + public ScheduledTootsListAdapter(Context context, DisplayScheduledTootsFragment.typeOfSchedule type, List storedStatuses, RelativeLayout textviewNoAction) { this.context = context; this.storedStatuses = storedStatuses; layoutInflater = LayoutInflater.from(this.context); @@ -92,7 +94,6 @@ public class ScheduledTootsListAdapter extends BaseAdapter implements OnPostActi } - @Override public int getCount() { return storedStatuses.size(); @@ -118,7 +119,7 @@ public class ScheduledTootsListAdapter extends BaseAdapter implements OnPostActi if (convertView == null) { convertView = layoutInflater.inflate(R.layout.drawer_scheduled_toot, parent, false); holder = new ViewHolder(); - holder.scheduled_toot_pp= convertView.findViewById(R.id.scheduled_toot_pp); + holder.scheduled_toot_pp = convertView.findViewById(R.id.scheduled_toot_pp); holder.scheduled_toot_title = convertView.findViewById(R.id.scheduled_toot_title); holder.scheduled_toot_date_creation = convertView.findViewById(R.id.scheduled_toot_date_creation); holder.scheduled_toot_media_count = convertView.findViewById(R.id.scheduled_toot_media_count); @@ -135,24 +136,24 @@ public class ScheduledTootsListAdapter extends BaseAdapter implements OnPostActi final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); final int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if( theme == Helper.THEME_BLACK) { - Helper.changeDrawableColor(context, R.drawable.ic_cancel,R.color.action_black); - Helper.changeDrawableColor(context, R.drawable.ic_public,R.color.action_black); - Helper.changeDrawableColor(context, R.drawable.ic_lock_open,R.color.action_black); - Helper.changeDrawableColor(context, R.drawable.ic_lock_outline,R.color.action_black); - Helper.changeDrawableColor(context, R.drawable.ic_mail_outline,R.color.action_black); - }else if( theme == Helper.THEME_DARK){ - Helper.changeDrawableColor(context, R.drawable.ic_cancel,R.color.action_dark); - Helper.changeDrawableColor(context, R.drawable.ic_public,R.color.action_dark); - Helper.changeDrawableColor(context, R.drawable.ic_lock_open,R.color.action_dark); - Helper.changeDrawableColor(context, R.drawable.ic_lock_outline,R.color.action_dark); - Helper.changeDrawableColor(context, R.drawable.ic_mail_outline,R.color.action_dark); - }else { - Helper.changeDrawableColor(context, R.drawable.ic_cancel,R.color.action_light); - Helper.changeDrawableColor(context, R.drawable.ic_public,R.color.action_light); - Helper.changeDrawableColor(context, R.drawable.ic_lock_open,R.color.action_light); - Helper.changeDrawableColor(context, R.drawable.ic_lock_outline,R.color.action_light); - Helper.changeDrawableColor(context, R.drawable.ic_mail_outline,R.color.action_light); + if (theme == Helper.THEME_BLACK) { + Helper.changeDrawableColor(context, R.drawable.ic_cancel, R.color.action_black); + Helper.changeDrawableColor(context, R.drawable.ic_public, R.color.action_black); + Helper.changeDrawableColor(context, R.drawable.ic_lock_open, R.color.action_black); + Helper.changeDrawableColor(context, R.drawable.ic_lock_outline, R.color.action_black); + Helper.changeDrawableColor(context, R.drawable.ic_mail_outline, R.color.action_black); + } else if (theme == Helper.THEME_DARK) { + Helper.changeDrawableColor(context, R.drawable.ic_cancel, R.color.action_dark); + Helper.changeDrawableColor(context, R.drawable.ic_public, R.color.action_dark); + Helper.changeDrawableColor(context, R.drawable.ic_lock_open, R.color.action_dark); + Helper.changeDrawableColor(context, R.drawable.ic_lock_outline, R.color.action_dark); + Helper.changeDrawableColor(context, R.drawable.ic_mail_outline, R.color.action_dark); + } else { + Helper.changeDrawableColor(context, R.drawable.ic_cancel, R.color.action_light); + Helper.changeDrawableColor(context, R.drawable.ic_public, R.color.action_light); + Helper.changeDrawableColor(context, R.drawable.ic_lock_open, R.color.action_light); + Helper.changeDrawableColor(context, R.drawable.ic_lock_outline, R.color.action_light); + Helper.changeDrawableColor(context, R.drawable.ic_mail_outline, R.color.action_light); } switch (status.getVisibility()) { @@ -173,9 +174,9 @@ public class ScheduledTootsListAdapter extends BaseAdapter implements OnPostActi int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } //Delete scheduled toot @@ -185,7 +186,7 @@ public class ScheduledTootsListAdapter extends BaseAdapter implements OnPostActi AlertDialog.Builder builder = new AlertDialog.Builder(context, style); String message; - if( type == DisplayScheduledTootsFragment.typeOfSchedule.TOOT) + if (type == DisplayScheduledTootsFragment.typeOfSchedule.TOOT) message = status.getContent() + '\n' + Helper.dateToString(storedStatus.getCreation_date()); else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) @@ -201,7 +202,7 @@ public class ScheduledTootsListAdapter extends BaseAdapter implements OnPostActi .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { - if( type != DisplayScheduledTootsFragment.typeOfSchedule.SERVER) { + if (type != DisplayScheduledTootsFragment.typeOfSchedule.SERVER) { if (type == DisplayScheduledTootsFragment.typeOfSchedule.TOOT) new StatusStoredDAO(context, db).remove(storedStatus.getId()); else if (type == DisplayScheduledTootsFragment.typeOfSchedule.BOOST) @@ -215,7 +216,7 @@ public class ScheduledTootsListAdapter extends BaseAdapter implements OnPostActi ApplicationJob.cancelJob(storedStatus.getJobId()); } catch (Exception ignored) { } - }else{ + } else { new PostActionAsyncTask(context, API.StatusAction.DELETESCHEDULED, storedStatus, ScheduledTootsListAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); storedStatuses.remove(storedStatus); scheduledTootsListAdapter.notifyDataSetChanged(); @@ -236,7 +237,7 @@ public class ScheduledTootsListAdapter extends BaseAdapter implements OnPostActi } }); - if( type != DisplayScheduledTootsFragment.typeOfSchedule.SERVER) { + if (type != DisplayScheduledTootsFragment.typeOfSchedule.SERVER) { if (storedStatus.getJobId() > 0) { holder.scheduled_toot_failed.setVisibility(View.GONE); } else { @@ -246,35 +247,35 @@ public class ScheduledTootsListAdapter extends BaseAdapter implements OnPostActi holder.scheduled_toot_media_count.setText(context.getString(R.string.media_count, status.getMedia_attachments().size())); holder.scheduled_toot_date_creation.setText(Helper.dateToString(storedStatus.getCreation_date())); holder.scheduled_toot_date.setText(Helper.dateToString(storedStatus.getScheduled_date())); - if( type == DisplayScheduledTootsFragment.typeOfSchedule.BOOST){ + if (type == DisplayScheduledTootsFragment.typeOfSchedule.BOOST) { holder.scheduled_toot_media_count.setVisibility(View.GONE); holder.scheduled_toot_date_creation.setVisibility(View.GONE); holder.scheduled_toot_privacy.setVisibility(View.GONE); Helper.loadGiF(context, storedStatus.getStatus().getAccount().getAvatar(), holder.scheduled_toot_pp); - }else { + } else { holder.scheduled_toot_pp.setVisibility(View.GONE); } holder.scheduled_toot_date.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, style); - LayoutInflater inflater = ((MainActivity)context).getLayoutInflater(); - View dialogView = inflater.inflate(R.layout.datetime_picker, new LinearLayout(context), false); + LayoutInflater inflater = ((MainActivity) context).getLayoutInflater(); + View dialogView = inflater.inflate(R.layout.datetime_picker, new LinearLayout(context), false); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if( theme == Helper.THEME_BLACK){ - Helper.changeDrawableColor(context, R.drawable.ic_skip_previous,R.color.action_black); - Helper.changeDrawableColor(context, R.drawable.ic_skip_next,R.color.action_black); - Helper.changeDrawableColor(context, R.drawable.ic_check,R.color.action_black); - }else if( theme == Helper.THEME_DARK){ - Helper.changeDrawableColor(context, R.drawable.ic_skip_previous,R.color.action_dark); - Helper.changeDrawableColor(context, R.drawable.ic_skip_next,R.color.action_dark); - Helper.changeDrawableColor(context, R.drawable.ic_check,R.color.action_dark); - }else { - Helper.changeDrawableColor(context, R.drawable.ic_skip_previous,R.color.action_light); - Helper.changeDrawableColor(context, R.drawable.ic_skip_next,R.color.action_light); - Helper.changeDrawableColor(context, R.drawable.ic_check,R.color.action_light); + if (theme == Helper.THEME_BLACK) { + Helper.changeDrawableColor(context, R.drawable.ic_skip_previous, R.color.action_black); + Helper.changeDrawableColor(context, R.drawable.ic_skip_next, R.color.action_black); + Helper.changeDrawableColor(context, R.drawable.ic_check, R.color.action_black); + } else if (theme == Helper.THEME_DARK) { + Helper.changeDrawableColor(context, R.drawable.ic_skip_previous, R.color.action_dark); + Helper.changeDrawableColor(context, R.drawable.ic_skip_next, R.color.action_dark); + Helper.changeDrawableColor(context, R.drawable.ic_check, R.color.action_dark); + } else { + Helper.changeDrawableColor(context, R.drawable.ic_skip_previous, R.color.action_light); + Helper.changeDrawableColor(context, R.drawable.ic_skip_next, R.color.action_light); + Helper.changeDrawableColor(context, R.drawable.ic_check, R.color.action_light); } dialogBuilder.setView(dialogView); final AlertDialog alertDialog = dialogBuilder.create(); @@ -322,7 +323,7 @@ public class ScheduledTootsListAdapter extends BaseAdapter implements OnPostActi if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { hour = timePicker.getHour(); minute = timePicker.getMinute(); - }else { + } else { //noinspection deprecation hour = timePicker.getCurrentHour(); //noinspection deprecation @@ -334,11 +335,11 @@ public class ScheduledTootsListAdapter extends BaseAdapter implements OnPostActi hour, minute); long time = calendar.getTimeInMillis(); - if( (time - new Date().getTime()) < 60000 ){ + if ((time - new Date().getTime()) < 60000) { Toasty.error(context, context.getString(R.string.toot_scheduled_date), Toast.LENGTH_LONG).show(); - }else { + } else { //Schedules the toot to the new date - if( type != DisplayScheduledTootsFragment.typeOfSchedule.SERVER) { + if (type != DisplayScheduledTootsFragment.typeOfSchedule.SERVER) { try { //Removes the job ApplicationJob.cancelJob(storedStatus.getJobId()); @@ -362,7 +363,7 @@ public class ScheduledTootsListAdapter extends BaseAdapter implements OnPostActi Toasty.success(context, context.getString(R.string.boost_scheduled), Toast.LENGTH_LONG).show(); } catch (Exception ignored) { } - }else{ + } else { int offset = TimeZone.getDefault().getRawOffset(); calendar.add(Calendar.MILLISECOND, -offset); final String date = Helper.dateToString(new Date(calendar.getTimeInMillis())); @@ -377,9 +378,9 @@ public class ScheduledTootsListAdapter extends BaseAdapter implements OnPostActi alertDialog.show(); } }); - if( type == DisplayScheduledTootsFragment.typeOfSchedule.TOOT) + if (type == DisplayScheduledTootsFragment.typeOfSchedule.TOOT) holder.scheduled_toot_title.setText(status.getContent()); - else if( type == DisplayScheduledTootsFragment.typeOfSchedule.BOOST){ + else if (type == DisplayScheduledTootsFragment.typeOfSchedule.BOOST) { Spanned message; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) message = Html.fromHtml(status.getContent(), Html.FROM_HTML_MODE_LEGACY); @@ -390,8 +391,7 @@ public class ScheduledTootsListAdapter extends BaseAdapter implements OnPostActi } - - if( type == DisplayScheduledTootsFragment.typeOfSchedule.TOOT) + if (type == DisplayScheduledTootsFragment.typeOfSchedule.TOOT) holder.scheduled_toot_container.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -403,7 +403,7 @@ public class ScheduledTootsListAdapter extends BaseAdapter implements OnPostActi context.startActivity(intentToot); } }); - else if( type == DisplayScheduledTootsFragment.typeOfSchedule.BOOST) + else if (type == DisplayScheduledTootsFragment.typeOfSchedule.BOOST) holder.scheduled_toot_container.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -414,13 +414,13 @@ public class ScheduledTootsListAdapter extends BaseAdapter implements OnPostActi context.startActivity(intentToot); } }); - else if( type == DisplayScheduledTootsFragment.typeOfSchedule.SERVER) + else if (type == DisplayScheduledTootsFragment.typeOfSchedule.SERVER) holder.scheduled_toot_container.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intentToot = new Intent(context, TootActivity.class); Bundle b = new Bundle(); - if( storedStatus.getStatus().getSpoiler_text().equals("null")) + if (storedStatus.getStatus().getSpoiler_text().equals("null")) storedStatus.getStatus().setSpoiler_text(""); b.putParcelable("storedStatus", storedStatus); intentToot.putExtras(b); diff --git a/app/src/main/java/app/fedilab/android/drawers/SearchListAdapter.java b/app/src/main/java/app/fedilab/android/drawers/SearchListAdapter.java index 972eae2de..43c8509af 100644 --- a/app/src/main/java/app/fedilab/android/drawers/SearchListAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/SearchListAdapter.java @@ -20,7 +20,9 @@ import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; + import androidx.core.content.ContextCompat; + import android.text.Html; import android.text.util.Linkify; import android.view.LayoutInflater; @@ -62,19 +64,19 @@ public class SearchListAdapter extends BaseAdapter { private static final int TAG_TYPE = 2; private LayoutInflater layoutInflater; - public SearchListAdapter(Context context, List statuses, List accounts, List tags){ + public SearchListAdapter(Context context, List statuses, List accounts, List tags) { this.context = context; - this.statuses = ( statuses != null)?statuses:new ArrayList(); - this.accounts = ( accounts != null)?accounts:new ArrayList(); - this.tags = ( tags != null)?tags:new ArrayList(); + this.statuses = (statuses != null) ? statuses : new ArrayList(); + this.accounts = (accounts != null) ? accounts : new ArrayList(); + this.tags = (tags != null) ? tags : new ArrayList(); layoutInflater = LayoutInflater.from(context); } @Override - public int getItemViewType(int position){ - if( position < statuses.size()) + public int getItemViewType(int position) { + if (position < statuses.size()) return STATUS_TYPE; - else if( position < statuses.size() + accounts.size() ) + else if (position < statuses.size() + accounts.size()) return ACCOUNT_TYPE; else return TAG_TYPE; @@ -87,9 +89,9 @@ public class SearchListAdapter extends BaseAdapter { @Override public Object getItem(int position) { - if( position < statuses.size()) + if (position < statuses.size()) return statuses.get(position); - else if( position < statuses.size() + accounts.size() ) + else if (position < statuses.size() + accounts.size()) return accounts.get(position - statuses.size()); else return tags.get(position - (statuses.size() + accounts.size())); @@ -101,7 +103,7 @@ public class SearchListAdapter extends BaseAdapter { } @Override - public int getViewTypeCount(){ + public int getViewTypeCount() { return 3; } @@ -109,7 +111,7 @@ public class SearchListAdapter extends BaseAdapter { public View getView(final int position, View convertView, ViewGroup parent) { int type = getItemViewType(position); - if( type == STATUS_TYPE){ + if (type == STATUS_TYPE) { View v = convertView; final Status status = (Status) getItem(position); final ViewHolderStatus holder; @@ -128,23 +130,23 @@ public class SearchListAdapter extends BaseAdapter { } else { holder = (ViewHolderStatus) v.getTag(); } - if( isFirstTypeItem(type, position) ) + if (isFirstTypeItem(type, position)) holder.status_search_title.setVisibility(View.VISIBLE); else holder.status_search_title.setVisibility(View.GONE); final float scale = context.getResources().getDisplayMetrics().density; - if( !status.getIn_reply_to_account_id().equals("null") || !status.getIn_reply_to_id().equals("null") ){ + if (!status.getIn_reply_to_account_id().equals("null") || !status.getIn_reply_to_id().equals("null")) { Drawable img = ContextCompat.getDrawable(context, R.drawable.ic_reply); assert img != null; - img.setBounds(0,0,(int) (20 * scale + 0.5f),(int) (15 * scale + 0.5f)); - holder.status_account_displayname.setCompoundDrawables( img, null, null, null); - }else if( status.getReblog() != null){ + img.setBounds(0, 0, (int) (20 * scale + 0.5f), (int) (15 * scale + 0.5f)); + holder.status_account_displayname.setCompoundDrawables(img, null, null, null); + } else if (status.getReblog() != null) { Drawable img = ContextCompat.getDrawable(context, R.drawable.ic_repeat); assert img != null; - img.setBounds(0,0,(int) (20 * scale + 0.5f),(int) (15 * scale + 0.5f)); - holder.status_account_displayname.setCompoundDrawables( img, null, null, null); - }else{ - holder.status_account_displayname.setCompoundDrawables( null, null, null, null); + img.setBounds(0, 0, (int) (20 * scale + 0.5f), (int) (15 * scale + 0.5f)); + holder.status_account_displayname.setCompoundDrawables(img, null, null, null); + } else { + holder.status_account_displayname.setCompoundDrawables(null, null, null, null); } //Click on a conversation holder.status_content.setOnClickListener(new View.OnClickListener() { @@ -159,23 +161,23 @@ public class SearchListAdapter extends BaseAdapter { }); final String content, displayName, username, ppurl; - if( status.getReblog() != null){ + if (status.getReblog() != null) { content = status.getReblog().getContent(); displayName = Helper.shortnameToUnicode(status.getReblog().getAccount().getDisplay_name(), true); username = status.getReblog().getAccount().getUsername(); - holder.status_reblog_user.setText(String.format("%s @%s",displayName, username)); + holder.status_reblog_user.setText(String.format("%s @%s", displayName, username)); ppurl = status.getReblog().getAccount().getAvatar(); holder.status_reblog_user.setVisibility(View.VISIBLE); holder.status_account_displayname.setText(context.getResources().getString(R.string.reblog_by, status.getAccount().getAcct())); - holder.status_account_username.setText( ""); - }else { + holder.status_account_username.setText(""); + } else { ppurl = status.getAccount().getAvatar(); content = status.getContent(); displayName = Helper.shortnameToUnicode(status.getAccount().getDisplay_name(), true); username = status.getAccount().getUsername(); holder.status_reblog_user.setVisibility(View.GONE); holder.status_account_displayname.setText(displayName); - holder.status_account_username.setText( String.format("@%s",username)); + holder.status_account_username.setText(String.format("@%s", username)); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) @@ -197,7 +199,7 @@ public class SearchListAdapter extends BaseAdapter { public void onClick(View v) { Intent intent = new Intent(context, ShowAccountActivity.class); Bundle b = new Bundle(); - if( status.getReblog() == null) + if (status.getReblog() == null) b.putParcelable("account", status.getAccount()); else b.putParcelable("account", status.getReblog().getAccount()); @@ -206,7 +208,7 @@ public class SearchListAdapter extends BaseAdapter { } }); return v; - }else if( type == ACCOUNT_TYPE ){ + } else if (type == ACCOUNT_TYPE) { View v = convertView; final Account account = (Account) getItem(position); final ViewHolderAccounts holder; @@ -228,15 +230,15 @@ public class SearchListAdapter extends BaseAdapter { holder = (ViewHolderAccounts) v.getTag(); } - if( isFirstTypeItem(type, position) ) + if (isFirstTypeItem(type, position)) holder.account_search_title.setVisibility(View.VISIBLE); else holder.account_search_title.setVisibility(View.GONE); holder.account_dn.setText(account.getDisplay_name()); - holder.account_un.setText(String.format("@%s",account.getUsername())); + holder.account_un.setText(String.format("@%s", account.getUsername())); holder.account_ac.setText(account.getAcct()); - if( account.getDisplay_name().equals(account.getAcct())) + if (account.getDisplay_name().equals(account.getAcct())) holder.account_ac.setVisibility(View.GONE); else holder.account_ac.setVisibility(View.VISIBLE); @@ -259,7 +261,7 @@ public class SearchListAdapter extends BaseAdapter { } }); return v; - }else{ + } else { final String tag = (String) getItem(position); final ViewHolderTag holder; View v = convertView; @@ -272,11 +274,11 @@ public class SearchListAdapter extends BaseAdapter { } else { holder = (ViewHolderTag) v.getTag(); } - if( isFirstTypeItem(type, position) ) + if (isFirstTypeItem(type, position)) holder.tag_search_title.setVisibility(View.VISIBLE); else holder.tag_search_title.setVisibility(View.GONE); - holder.tag_name.setText(String.format("#%s",tag)); + holder.tag_name.setText(String.format("#%s", tag)); holder.tag_name.setPaintFlags(holder.tag_name.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); holder.tag_name.setOnClickListener(new View.OnClickListener() { @Override @@ -292,12 +294,12 @@ public class SearchListAdapter extends BaseAdapter { } } - private boolean isFirstTypeItem(int type, int position){ - if( position == 0 && type == STATUS_TYPE) + private boolean isFirstTypeItem(int type, int position) { + if (position == 0 && type == STATUS_TYPE) return true; - else if( position == statuses.size() && type == ACCOUNT_TYPE ) + else if (position == statuses.size() && type == ACCOUNT_TYPE) return true; - else if( position == (statuses.size() + accounts.size()) && type == TAG_TYPE ) + else if (position == (statuses.size() + accounts.size()) && type == TAG_TYPE) return true; return false; } diff --git a/app/src/main/java/app/fedilab/android/drawers/SearchTagsAdapter.java b/app/src/main/java/app/fedilab/android/drawers/SearchTagsAdapter.java index 48ab2d862..f057a8a4a 100644 --- a/app/src/main/java/app/fedilab/android/drawers/SearchTagsAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/SearchTagsAdapter.java @@ -17,14 +17,18 @@ package app.fedilab.android.drawers; import android.content.Context; import android.content.Intent; import android.os.Bundle; + import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; + import java.util.ArrayList; import java.util.List; + import app.fedilab.android.R; import app.fedilab.android.activities.HashTagActivity; @@ -38,12 +42,12 @@ public class SearchTagsAdapter extends RecyclerView.Adapter { private Context context; private List tags; - public SearchTagsAdapter(List tags){ - this.tags = ( tags != null)?tags:new ArrayList<>(); + public SearchTagsAdapter(List tags) { + this.tags = (tags != null) ? tags : new ArrayList<>(); } public String getItem(int position) { - return tags.get(position); + return tags.get(position); } @NonNull @@ -54,8 +58,9 @@ public class SearchTagsAdapter extends RecyclerView.Adapter { return new ViewHolder(layoutInflater.inflate(R.layout.drawer_tag_search_tab, parent, false)); } - class ViewHolder extends RecyclerView.ViewHolder{ + class ViewHolder extends RecyclerView.ViewHolder { private TextView tag_name; + public ViewHolder(@NonNull View itemView) { super(itemView); tag_name = itemView.findViewById(R.id.tag_name); @@ -67,7 +72,7 @@ public class SearchTagsAdapter extends RecyclerView.Adapter { final ViewHolder holder = (ViewHolder) viewHolder; final String tag = getItem(i); - holder.tag_name.setText(String.format("#%s",tag)); + holder.tag_name.setText(String.format("#%s", tag)); holder.tag_name.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -92,5 +97,4 @@ public class SearchTagsAdapter extends RecyclerView.Adapter { } - } \ No newline at end of file diff --git a/app/src/main/java/app/fedilab/android/drawers/SearchTootsListAdapter.java b/app/src/main/java/app/fedilab/android/drawers/SearchTootsListAdapter.java index 7a795f170..bfe164dfa 100644 --- a/app/src/main/java/app/fedilab/android/drawers/SearchTootsListAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/SearchTootsListAdapter.java @@ -22,8 +22,10 @@ import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.graphics.drawable.Drawable; import android.os.Bundle; + import androidx.core.content.ContextCompat; import androidx.appcompat.app.AlertDialog; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -31,6 +33,7 @@ import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; + import java.util.List; import app.fedilab.android.helper.Helper; @@ -46,7 +49,7 @@ import static app.fedilab.android.helper.Helper.changeDrawableColor; * Created by Thomas on 22/11/2017. * Adapter for search */ -public class SearchTootsListAdapter extends BaseAdapter { +public class SearchTootsListAdapter extends BaseAdapter { private List searches; private LayoutInflater layoutInflater; @@ -54,7 +57,7 @@ public class SearchTootsListAdapter extends BaseAdapter { private SearchTootsListAdapter searchTootsListAdapter; private RelativeLayout textviewNoAction; - public SearchTootsListAdapter(Context context, List searches, RelativeLayout textviewNoAction){ + public SearchTootsListAdapter(Context context, List searches, RelativeLayout textviewNoAction) { this.searches = searches; this.searchTootsListAdapter = this; this.textviewNoAction = textviewNoAction; @@ -93,21 +96,21 @@ public class SearchTootsListAdapter extends BaseAdapter { } SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if( theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { holder.search_container.setBackgroundResource(R.color.mastodonC3__); - Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right,R.color.black); - }else if(theme == Helper.THEME_DARK){ + Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right, R.color.black); + } else if (theme == Helper.THEME_DARK) { holder.search_container.setBackgroundResource(R.color.mastodonC1_); - Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right,R.color.dark_text); - }else if(theme == Helper.THEME_BLACK) { + Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right, R.color.dark_text); + } else if (theme == Helper.THEME_BLACK) { holder.search_container.setBackgroundResource(R.color.black_2); - Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right,R.color.dark_text); + Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right, R.color.dark_text); } Drawable next = ContextCompat.getDrawable(context, R.drawable.ic_keyboard_arrow_right); holder.search_title.setText(search); final float scale = context.getResources().getDisplayMetrics().density; assert next != null; - next.setBounds(0,0,(int) (30 * scale + 0.5f),(int) (30 * scale + 0.5f)); + next.setBounds(0, 0, (int) (30 * scale + 0.5f), (int) (30 * scale + 0.5f)); holder.search_title.setCompoundDrawables(null, null, next, null); holder.search_container.setOnClickListener(new View.OnClickListener() { @@ -124,9 +127,9 @@ public class SearchTootsListAdapter extends BaseAdapter { int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } holder.search_container.setOnLongClickListener(new View.OnLongClickListener() { @@ -141,7 +144,7 @@ public class SearchTootsListAdapter extends BaseAdapter { new SearchDAO(context, db).remove(search.trim()); searches.remove(search); searchTootsListAdapter.notifyDataSetChanged(); - if( searches.size() == 0 && textviewNoAction != null && textviewNoAction.getVisibility() == View.GONE) + if (searches.size() == 0 && textviewNoAction != null && textviewNoAction.getVisibility() == View.GONE) textviewNoAction.setVisibility(View.VISIBLE); dialog.dismiss(); } diff --git a/app/src/main/java/app/fedilab/android/drawers/StatusListAdapter.java b/app/src/main/java/app/fedilab/android/drawers/StatusListAdapter.java index a5e2e9d82..e3ef503be 100644 --- a/app/src/main/java/app/fedilab/android/drawers/StatusListAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/StatusListAdapter.java @@ -33,6 +33,7 @@ import android.os.Bundle; import android.os.CountDownTimer; import android.os.Environment; import android.os.Handler; + import androidx.annotation.NonNull; import androidx.appcompat.widget.TooltipCompat; import androidx.constraintlayout.widget.ConstraintLayout; @@ -41,6 +42,7 @@ import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.PopupMenu; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; + import android.text.Html; import android.text.InputType; import android.text.Spannable; @@ -222,13 +224,13 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct private List lstHolders; private final Object lock = new Object(); - private List emojisPicker; + private List emojisPicker; private Runnable updateAnimatedEmoji = new Runnable() { @Override public void run() { synchronized (lock) { - if( mRecyclerView != null && (mRecyclerView.getLayoutManager()) != null) { + if (mRecyclerView != null && (mRecyclerView.getLayoutManager()) != null) { int firstPosition = ((LinearLayoutManager) mRecyclerView.getLayoutManager()).findFirstCompletelyVisibleItemPosition(); int lastPosition = ((LinearLayoutManager) mRecyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition(); for (ViewHolder holder : lstHolders) { @@ -236,7 +238,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.updateAnimatedEmoji(); } } - }else{ + } else { for (ViewHolder holder : lstHolders) { holder.updateAnimatedEmoji(); } @@ -255,12 +257,12 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct @Override - public void onDetachedFromRecyclerView (@NotNull RecyclerView recyclerView) { + public void onDetachedFromRecyclerView(@NotNull RecyclerView recyclerView) { super.onDetachedFromRecyclerView(recyclerView); mRecyclerView = null; } - public StatusListAdapter(RetrieveFeedsAsyncTask.Type type, String targetedId, boolean isOnWifi, List statuses){ + public StatusListAdapter(RetrieveFeedsAsyncTask.Type type, String targetedId, boolean isOnWifi, List statuses) { super(); this.statuses = statuses; this.isOnWifi = isOnWifi; @@ -271,7 +273,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct lstHolders = new ArrayList<>(); } - public StatusListAdapter(TagTimeline tagTimeline, String targetedId, boolean isOnWifi, List statuses){ + public StatusListAdapter(TagTimeline tagTimeline, String targetedId, boolean isOnWifi, List statuses) { super(); this.statuses = statuses; this.isOnWifi = isOnWifi; @@ -283,7 +285,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct lstHolders = new ArrayList<>(); } - public StatusListAdapter(int position, String targetedId, boolean isOnWifi, List statuses){ + public StatusListAdapter(int position, String targetedId, boolean isOnWifi, List statuses) { this.statuses = statuses; this.isOnWifi = isOnWifi; statusListAdapter = this; @@ -306,8 +308,8 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct return statuses.size(); } - private Status getItemAt(int position){ - if( statuses.size() > position) + private Status getItemAt(int position) { + if (statuses.size() > position) return statuses.get(position); else return null; @@ -315,7 +317,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct @Override public void onRetrieveReplies(APIResponse apiResponse) { - if( apiResponse.getError() != null || apiResponse.getStatuses() == null || apiResponse.getStatuses().size() == 0){ + if (apiResponse.getError() != null || apiResponse.getStatuses() == null || apiResponse.getStatuses().size() == 0) { return; } List modifiedStatus = apiResponse.getStatuses(); @@ -324,9 +326,9 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct @Override public void onPoll(Status status, Poll poll) { - if( status.getReblog() != null){ + if (status.getReblog() != null) { status.getReblog().setPoll(poll); - }else{ + } else { status.setPoll(poll); } notifyStatusChanged(status); @@ -334,7 +336,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct @Override public void onRefresh(Status refreshedStatus) { - if( refreshedStatus.getCreated_at() == null){ + if (refreshedStatus.getCreated_at() == null) { SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); new TimelineCacheDAO(context, db).remove(refreshedStatus.getId()); new PostActionAsyncTask(context, API.StatusAction.UNSTATUS, refreshedStatus.getId(), StatusListAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); @@ -344,17 +346,17 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct @Override public void onRetrieveSearchAccounts(APIResponse apiResponse) { - if( apiResponse.getError() != null) + if (apiResponse.getError() != null) return; final List accounts = apiResponse.getAccounts(); - if( accounts != null && accounts.size() > 0){ + if (accounts != null && accounts.size() > 0) { int currentCursorPosition = toot_content.getSelectionStart(); AccountsSearchAdapter accountsListAdapter = new AccountsSearchAdapter(context, accounts); toot_content.setThreshold(1); toot_content.setAdapter(accountsListAdapter); final String oldContent = toot_content.getText().toString(); - if( oldContent.length() >= currentCursorPosition) { + if (oldContent.length() >= currentCursorPosition) { String[] searchA = oldContent.substring(0, currentCursorPosition).split("@"); if (searchA.length > 0) { final String search = searchA[searchA.length - 1]; @@ -379,7 +381,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct newContent += deltaSearch; newContent += "@" + account.getAcct() + " "; int newPosition = newContent.length(); - if (currentCursorPosition < oldContent.length() ) + if (currentCursorPosition < oldContent.length()) newContent += oldContent.substring(currentCursorPosition, oldContent.length()); toot_content.setText(newContent); toot_space_left.setText(String.valueOf(TootActivity.countLength(social, toot_content, toot_cw_content))); @@ -404,13 +406,13 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct public void onRetrieveSearchEmoji(List emojis) { int currentCursorPosition = toot_content.getSelectionStart(); - if( emojis != null && emojis.size() > 0){ + if (emojis != null && emojis.size() > 0) { EmojisSearchAdapter emojisSearchAdapter = new EmojisSearchAdapter(context, emojis); toot_content.setThreshold(1); toot_content.setAdapter(emojisSearchAdapter); final String oldContent = toot_content.getText().toString(); - String[] searchA = oldContent.substring(0,currentCursorPosition).split(":"); - final String search = searchA[searchA.length-1]; + String[] searchA = oldContent.substring(0, currentCursorPosition).split(":"); + final String search = searchA[searchA.length - 1]; toot_content.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { @@ -420,21 +422,21 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct if (currentCursorPosition < 15) { //Less than 15 characters are written before the cursor position searchLength = currentCursorPosition; } - if( currentCursorPosition-searchLength > 0 && currentCursorPosition < oldContent.length() ) - deltaSearch = oldContent.substring(currentCursorPosition-searchLength, currentCursorPosition); + if (currentCursorPosition - searchLength > 0 && currentCursorPosition < oldContent.length()) + deltaSearch = oldContent.substring(currentCursorPosition - searchLength, currentCursorPosition); else { - if( currentCursorPosition >= oldContent.length() ) - deltaSearch = oldContent.substring(currentCursorPosition-searchLength, oldContent.length()); + if (currentCursorPosition >= oldContent.length()) + deltaSearch = oldContent.substring(currentCursorPosition - searchLength, oldContent.length()); } - if( !search.equals("")) - deltaSearch = deltaSearch.replace(":"+search,""); - String newContent = oldContent.substring(0,currentCursorPosition-searchLength); + if (!search.equals("")) + deltaSearch = deltaSearch.replace(":" + search, ""); + String newContent = oldContent.substring(0, currentCursorPosition - searchLength); newContent += deltaSearch; newContent += ":" + shortcode + ": "; int newPosition = newContent.length(); - if( currentCursorPosition < oldContent.length() ) - newContent += oldContent.substring(currentCursorPosition, oldContent.length()); + if (currentCursorPosition < oldContent.length()) + newContent += oldContent.substring(currentCursorPosition, oldContent.length()); toot_content.setText(newContent); toot_space_left.setText(String.valueOf(TootActivity.countLength(social, toot_content, toot_cw_content))); toot_content.setSelection(newPosition); @@ -449,27 +451,27 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct @Override public void onRetrieveSearch(APIResponse apiResponse) { - if( apiResponse == null || apiResponse.getResults() == null || toot_content == null) + if (apiResponse == null || apiResponse.getResults() == null || toot_content == null) return; app.fedilab.android.client.Entities.Results results = apiResponse.getResults(); int currentCursorPosition = toot_content.getSelectionStart(); final List tags = results.getHashtags(); - if( tags != null && tags.size() > 0){ + if (tags != null && tags.size() > 0) { TagsSearchAdapter tagsSearchAdapter = new TagsSearchAdapter(context, tags); toot_content.setThreshold(1); toot_content.setAdapter(tagsSearchAdapter); final String oldContent = toot_content.getText().toString(); - if( oldContent.length() < currentCursorPosition) + if (oldContent.length() < currentCursorPosition) return; - String[] searchA = oldContent.substring(0,currentCursorPosition).split("#"); - if( searchA.length < 1) + String[] searchA = oldContent.substring(0, currentCursorPosition).split("#"); + if (searchA.length < 1) return; - final String search = searchA[searchA.length-1]; + final String search = searchA[searchA.length - 1]; toot_content.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { - if( position >= tags.size() ) + if (position >= tags.size()) return; String tag = tags.get(position); String deltaSearch = ""; @@ -477,23 +479,23 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct if (currentCursorPosition < 15) { //Less than 15 characters are written before the cursor position searchLength = currentCursorPosition; } - if( currentCursorPosition-searchLength > 0 && currentCursorPosition < oldContent.length() ) - deltaSearch = oldContent.substring(currentCursorPosition-searchLength, currentCursorPosition); + if (currentCursorPosition - searchLength > 0 && currentCursorPosition < oldContent.length()) + deltaSearch = oldContent.substring(currentCursorPosition - searchLength, currentCursorPosition); else { - if( currentCursorPosition >= oldContent.length() ) - deltaSearch = oldContent.substring(currentCursorPosition-searchLength, oldContent.length()); + if (currentCursorPosition >= oldContent.length()) + deltaSearch = oldContent.substring(currentCursorPosition - searchLength, oldContent.length()); } - if( !search.equals("")) - deltaSearch = deltaSearch.replace("#"+search,""); - String newContent = oldContent.substring(0,currentCursorPosition-searchLength); + if (!search.equals("")) + deltaSearch = deltaSearch.replace("#" + search, ""); + String newContent = oldContent.substring(0, currentCursorPosition - searchLength); newContent += deltaSearch; newContent += "#" + tag + " "; int newPosition = newContent.length(); - if( currentCursorPosition < oldContent.length() ) - newContent += oldContent.substring(currentCursorPosition, oldContent.length()); + if (currentCursorPosition < oldContent.length()) + newContent += oldContent.substring(currentCursorPosition, oldContent.length()); toot_content.setText(newContent); - toot_space_left.setText(String.valueOf(TootActivity.countLength(social,toot_content, toot_cw_content))); + toot_space_left.setText(String.valueOf(TootActivity.countLength(social, toot_content, toot_cw_content))); toot_content.setSelection(newPosition); TagsSearchAdapter tagsSearchAdapter = new TagsSearchAdapter(context, new ArrayList<>()); toot_content.setThreshold(1); @@ -505,7 +507,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct @Override public void onPostStatusAction(APIResponse apiResponse) { - if( apiResponse.getError() != null ) { + if (apiResponse.getError() != null) { if (apiResponse.getError().getError().contains("422")) { Toasty.error(context, context.getString(R.string.toast_error_char_limit), Toast.LENGTH_SHORT).show(); return; @@ -518,20 +520,20 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct boolean split_toot = sharedpreferences.getBoolean(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS, false); final String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); - int split_toot_size = sharedpreferences.getInt(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS_SIZE+userId+instance, Helper.SPLIT_TOOT_SIZE); + int split_toot_size = sharedpreferences.getInt(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS_SIZE + userId + instance, Helper.SPLIT_TOOT_SIZE); int cwSize = toot_cw_content.getText().toString().trim().length(); int size = toot_content.getText().toString().trim().length() + cwSize; - if( split_toot && splitToot != null && stepSpliToot < splitToot.size()){ + if (split_toot && splitToot != null && stepSpliToot < splitToot.size()) { String tootContent = splitToot.get(stepSpliToot); stepSpliToot += 1; Status toot = new Status(); toot.setSensitive(false); - if( toot_cw_content.getText().toString().trim().length() > 0) + if (toot_cw_content.getText().toString().trim().length() > 0) toot.setSpoiler_text(toot_cw_content.getText().toString().trim()); toot.setVisibility(visibility); - if( apiResponse.getStatuses() != null && apiResponse.getStatuses().size() > 0) + if (apiResponse.getStatuses() != null && apiResponse.getStatuses().size() > 0) toot.setIn_reply_to_id(apiResponse.getStatuses().get(0).getId()); toot.setContent(tootContent); final SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); @@ -544,17 +546,17 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct toot_cw_content = null; tootReply = null; currentToId = -1; - if(apiResponse.getError() == null) { + if (apiResponse.getError() == null) { boolean display_confirm = sharedpreferences.getBoolean(Helper.SET_DISPLAY_CONFIRM, true); - if( display_confirm){ + if (display_confirm) { Toasty.success(context, context.getString(R.string.toot_sent), Toast.LENGTH_LONG).show(); } - }else { - if(apiResponse.getError().getStatusCode() == -33) + } else { + if (apiResponse.getError().getStatusCode() == -33) Toasty.info(context, context.getString(R.string.toast_toot_saved_error), Toast.LENGTH_LONG).show(); } //For conversation - if( context instanceof ShowConversationActivity){ + if (context instanceof ShowConversationActivity) { ((ShowConversationActivity) context).addStatuses(apiResponse.getStatuses().get(0)); } @@ -562,20 +564,19 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct @Override public void onRetrieveRelationshipQuickReply(Relationship relationship, Status status, Error error) { - if( error != null){ + if (error != null) { return; } - if( relationship != null && relationship.isBlocked_by() ){ + if (relationship != null && relationship.isBlocked_by()) { warning_message.setVisibility(View.VISIBLE); status.setWarningFetched(1); - }else{ + } else { status.setWarningFetched(0); } } - - private class ViewHolderEmpty extends RecyclerView.ViewHolder{ + private class ViewHolderEmpty extends RecyclerView.ViewHolder { ViewHolderEmpty(View itemView) { super(itemView); } @@ -585,7 +586,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct public void onViewAttachedToWindow(@NonNull RecyclerView.ViewHolder holder) { super.onViewAttachedToWindow(holder); context = holder.itemView.getContext(); - if( type != RetrieveFeedsAsyncTask.Type.ART && type != RetrieveFeedsAsyncTask.Type.PIXELFED && (tagTimeline == null || !tagTimeline.isART()) && (holder.getItemViewType() == DISPLAYED_STATUS || holder.getItemViewType() == COMPACT_STATUS|| holder.getItemViewType() == CONSOLE_STATUS)) { + if (type != RetrieveFeedsAsyncTask.Type.ART && type != RetrieveFeedsAsyncTask.Type.PIXELFED && (tagTimeline == null || !tagTimeline.isART()) && (holder.getItemViewType() == DISPLAYED_STATUS || holder.getItemViewType() == COMPACT_STATUS || holder.getItemViewType() == CONSOLE_STATUS)) { final ViewHolder viewHolder = (ViewHolder) holder; // Bug workaround for losing text selection ability, see: // https://code.google.com/p/android/issues/detail?id=208169 @@ -598,7 +599,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } - class ViewHolder extends RecyclerView.ViewHolder{ + class ViewHolder extends RecyclerView.ViewHolder { LinearLayout status_content_container; LinearLayout status_spoiler_container; CustomTextView status_spoiler; @@ -695,13 +696,13 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct Button quick_reply_button; ImageView quick_reply_privacy; - public View getView(){ + public View getView() { return itemView; } ViewHolder(View itemView) { super(itemView); - fetch_more = itemView.findViewById(R.id.fetch_more); + fetch_more = itemView.findViewById(R.id.fetch_more); webview_preview_card = itemView.findViewById(R.id.webview_preview_card); webview_preview = itemView.findViewById(R.id.webview_preview); status_horizontal_document_container = itemView.findViewById(R.id.status_horizontal_document_container); @@ -774,10 +775,10 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct conversation_pp_4 = itemView.findViewById(R.id.conversation_pp_4); conversation_pp_2_container = itemView.findViewById(R.id.conversation_pp_2_container); conversation_pp_3_container = itemView.findViewById(R.id.conversation_pp_3_container); - left_buttons = itemView.findViewById(R.id.left_buttons); + left_buttons = itemView.findViewById(R.id.left_buttons); status_show_more_content = itemView.findViewById(R.id.status_show_more_content); - spark_button_fav = itemView.findViewById(R.id.spark_button_fav); - spark_button_reblog = itemView.findViewById(R.id.spark_button_reblog); + spark_button_fav = itemView.findViewById(R.id.spark_button_fav); + spark_button_reblog = itemView.findViewById(R.id.spark_button_reblog); horizontal_second_image = itemView.findViewById(R.id.horizontal_second_image); status_peertube_container = itemView.findViewById(R.id.status_peertube_container); @@ -805,18 +806,18 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct status_account_bot = itemView.findViewById(R.id.status_account_bot); - quick_reply_text = itemView.findViewById(R.id.quick_reply_text); quick_reply_switch_to_full = itemView.findViewById(R.id.quick_reply_switch_to_full); toot_space_left = itemView.findViewById(R.id.toot_space_left); quick_reply_emoji = itemView.findViewById(R.id.quick_reply_emoji); quick_reply_button = itemView.findViewById(R.id.quick_reply_button); - quick_reply_privacy = itemView.findViewById(R.id.quick_reply_privacy); + quick_reply_privacy = itemView.findViewById(R.id.quick_reply_privacy); - warning_message = itemView.findViewById(R.id.warning_message); + warning_message = itemView.findViewById(R.id.warning_message); } + void updateAnimatedEmoji() { - if( type != RetrieveFeedsAsyncTask.Type.CONVERSATION) { + if (type != RetrieveFeedsAsyncTask.Type.CONVERSATION) { status_account_displayname.invalidate(); } status_content.invalidate(); @@ -827,8 +828,8 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); boolean disableAnimatedEmoji = sharedpreferences.getBoolean(Helper.SET_DISABLE_ANIMATED_EMOJI, false); - if( !disableAnimatedEmoji ){ - if( BaseMainActivity.timer == null){ + if (!disableAnimatedEmoji) { + if (BaseMainActivity.timer == null) { BaseMainActivity.timer = new Timer(); } BaseMainActivity.timer.schedule(new TimerTask() { @@ -842,8 +843,8 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } - public Status getItem(int position){ - if( statuses.size() > position && position >= 0) + public Status getItem(int position) { + if (statuses.size() > position && position >= 0) return statuses.get(position); else return null; } @@ -852,13 +853,13 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct public int getItemViewType(int position) { boolean show_boosts = false; boolean show_replies = false; - if( context instanceof ShowAccountActivity){ + if (context instanceof ShowAccountActivity) { show_boosts = ((ShowAccountActivity) context).showBoosts(); show_replies = ((ShowAccountActivity) context).showReplies(); } - if( type != RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE && type != RetrieveFeedsAsyncTask.Type.NEWS && !Helper.filterToots(statuses.get(position), type, context instanceof ShowAccountActivity,show_boosts, show_replies)) - return HIDDEN_STATUS; - if( statuses.get(position).isFocused() && type == RetrieveFeedsAsyncTask.Type.CONTEXT && statuses.get(position).getViewType() != CONSOLE_STATUS) + if (type != RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE && type != RetrieveFeedsAsyncTask.Type.NEWS && !Helper.filterToots(statuses.get(position), type, context instanceof ShowAccountActivity, show_boosts, show_replies)) + return HIDDEN_STATUS; + if (statuses.get(position).isFocused() && type == RetrieveFeedsAsyncTask.Type.CONTEXT && statuses.get(position).getViewType() != CONSOLE_STATUS) return FOCUSED_STATUS; else return statuses.get(position).getViewType(); @@ -870,27 +871,26 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct context = parent.getContext(); LayoutInflater layoutInflater = LayoutInflater.from(this.context); - if( viewType == DISPLAYED_STATUS) + if (viewType == DISPLAYED_STATUS) return new ViewHolder(layoutInflater.inflate(R.layout.drawer_status, parent, false)); - else if(viewType == COMPACT_STATUS) + else if (viewType == COMPACT_STATUS) return new ViewHolder(layoutInflater.inflate(R.layout.drawer_status_compact, parent, false)); - else if(viewType == CONSOLE_STATUS) - return new ViewHolder(layoutInflater.inflate(R.layout.drawer_status_console, parent, false)); - else if(viewType == FOCUSED_STATUS) + else if (viewType == CONSOLE_STATUS) + return new ViewHolder(layoutInflater.inflate(R.layout.drawer_status_console, parent, false)); + else if (viewType == FOCUSED_STATUS) return new ViewHolder(layoutInflater.inflate(R.layout.drawer_status_focused, parent, false)); else return new ViewHolderEmpty(layoutInflater.inflate(R.layout.drawer_empty, parent, false)); } - @SuppressLint("SetJavaScriptEnabled") @Override public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder viewHolder, int i) { final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); final String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); context = viewHolder.itemView.getContext(); - if( viewHolder.getItemViewType() != HIDDEN_STATUS ) { + if (viewHolder.getItemViewType() != HIDDEN_STATUS) { final ViewHolder holder = (ViewHolder) viewHolder; synchronized (lock) { lstHolders.add(holder); @@ -899,7 +899,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.startUpdateTimer(); final Status status = statuses.get(i); - if( status == null) + if (status == null) return; //TODO:It sounds that sometimes this value is null - need deeper investigation @@ -912,7 +912,6 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct status.setItemViewType(viewHolder.getItemViewType()); - boolean fullAttachement = sharedpreferences.getBoolean(Helper.SET_FULL_PREVIEW, false); boolean isCompactMode = sharedpreferences.getBoolean(Helper.SET_COMPACT_MODE, false); boolean isConsoleMode = sharedpreferences.getBoolean(Helper.SET_CONSOLE_MODE, false); @@ -958,7 +957,6 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } - //Display a preview for accounts that have replied *if enabled and only for home timeline* if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { holder.rated.setVisibility(View.GONE); @@ -966,30 +964,30 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.single_choice.setVisibility(View.GONE); holder.submit_vote.setVisibility(View.GONE); Poll poll; - if( status.getReblog() != null) { + if (status.getReblog() != null) { poll = status.getReblog().getPoll(); - }else { + } else { poll = status.getPoll(); } - if( poll != null && poll.getOptionsList() != null){ - if( poll.isVoted() || poll.isExpired()){ + if (poll != null && poll.getOptionsList() != null) { + if (poll.isVoted() || poll.isExpired()) { holder.rated.setVisibility(View.VISIBLE); List items = new ArrayList<>(); int greaterValue = 0; - for(PollOptions pollOption: poll.getOptionsList()){ - if( pollOption.getVotes_count() > greaterValue) + for (PollOptions pollOption : poll.getOptionsList()) { + if (pollOption.getVotes_count() > greaterValue) greaterValue = pollOption.getVotes_count(); } - for(PollOptions pollOption: poll.getOptionsList()){ - double value = ((double)(pollOption.getVotes_count()* 100) / (double)poll.getVotes_count()) ; - if( pollOption.getVotes_count() == greaterValue) { + for (PollOptions pollOption : poll.getOptionsList()) { + double value = ((double) (pollOption.getVotes_count() * 100) / (double) poll.getVotes_count()); + if (pollOption.getVotes_count() == greaterValue) { BarItem bar = new BarItem(pollOption.getTitle(), value, "%", ContextCompat.getColor(context, R.color.mastodonC4), Color.WHITE); bar.setRounded(true); bar.setHeight1(30); items.add(bar); - }else { + } else { BarItem bar; - if( theme == Helper.THEME_LIGHT) + if (theme == Helper.THEME_LIGHT) bar = new BarItem(pollOption.getTitle(), value, "%", ContextCompat.getColor(context, R.color.mastodonC2), Color.BLACK); else bar = new BarItem(pollOption.getTitle(), value, "%", ContextCompat.getColor(context, R.color.mastodonC2), Color.WHITE); @@ -1002,22 +1000,22 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct HorizontalBar horizontalBar = new HorizontalBar(context); horizontalBar.hasAnimation(true).addAll(items).build(); holder.rated.addView(horizontalBar); - }else { - if( poll.isMultiple()){ + } else { + if (poll.isMultiple()) { - if((holder.multiple_choice).getChildCount() > 0) + if ((holder.multiple_choice).getChildCount() > 0) (holder.multiple_choice).removeAllViews(); - for(PollOptions pollOption: poll.getOptionsList()){ + for (PollOptions pollOption : poll.getOptionsList()) { CheckBox cb = new CheckBox(context); cb.setText(pollOption.getTitle()); holder.multiple_choice.addView(cb); } holder.multiple_choice.setVisibility(View.VISIBLE); - }else { - if((holder.radio_group).getChildCount() > 0) + } else { + if ((holder.radio_group).getChildCount() > 0) (holder.radio_group).removeAllViews(); - for(PollOptions pollOption: poll.getOptionsList()){ + for (PollOptions pollOption : poll.getOptionsList()) { RadioButton rb = new RadioButton(context); rb.setText(pollOption.getTitle()); holder.radio_group.addView(rb); @@ -1028,13 +1026,13 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.submit_vote.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - int [] choice; - if( poll.isMultiple()){ + int[] choice; + if (poll.isMultiple()) { ArrayList choices = new ArrayList<>(); int choicesCount = holder.multiple_choice.getChildCount(); - for( int i = 0 ; i < choicesCount ; i++){ - if( holder.multiple_choice.getChildAt(i) != null && holder.multiple_choice.getChildAt(i) instanceof CheckBox){ - if(((CheckBox) holder.multiple_choice.getChildAt(i)).isChecked()){ + for (int i = 0; i < choicesCount; i++) { + if (holder.multiple_choice.getChildAt(i) != null && holder.multiple_choice.getChildAt(i) instanceof CheckBox) { + if (((CheckBox) holder.multiple_choice.getChildAt(i)).isChecked()) { choices.add(i); } } @@ -1044,20 +1042,20 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct for (int i = 0; i < choice.length; i++) { choice[i] = iterator.next().intValue(); } - if( choice.length == 0) + if (choice.length == 0) return; - }else{ + } else { choice = new int[1]; choice[0] = -1; int choicesCount = holder.radio_group.getChildCount(); - for( int i = 0 ; i < choicesCount ; i++){ - if( holder.radio_group.getChildAt(i) != null && holder.radio_group.getChildAt(i) instanceof RadioButton){ - if(((RadioButton) holder.radio_group.getChildAt(i)).isChecked()){ + for (int i = 0; i < choicesCount; i++) { + if (holder.radio_group.getChildAt(i) != null && holder.radio_group.getChildAt(i) instanceof RadioButton) { + if (((RadioButton) holder.radio_group.getChildAt(i)).isChecked()) { choice[0] = i; } } } - if( choice[0] == -1) + if (choice[0] == -1) return; } new ManagePollAsyncTask(context, ManagePollAsyncTask.type_s.SUBMIT, status, choice, StatusListAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); @@ -1072,9 +1070,9 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } }); holder.poll_container.setVisibility(View.VISIBLE); - holder.number_votes.setText(context.getResources().getQuantityString(R.plurals.number_of_vote,poll.getVotes_count(),poll.getVotes_count())); + holder.number_votes.setText(context.getResources().getQuantityString(R.plurals.number_of_vote, poll.getVotes_count(), poll.getVotes_count())); holder.remaining_time.setText(context.getString(R.string.poll_finish_at, Helper.dateToStringPoll(poll.getExpires_at()))); - }else { + } else { holder.poll_container.setVisibility(View.GONE); } } @@ -1161,7 +1159,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } - holder.quick_reply_emoji.setOnClickListener(view ->{ + holder.quick_reply_emoji.setOnClickListener(view -> { int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; @@ -1176,42 +1174,41 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct final AlertDialog.Builder builder = new AlertDialog.Builder(context, style); int paddingPixel = 15; float density = context.getResources().getDisplayMetrics().density; - int paddingDp = (int)(paddingPixel * density); + int paddingDp = (int) (paddingPixel * density); builder.setNeutralButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setTitle(R.string.insert_emoji); - if( emojisPicker != null && emojisPicker.size() > 0) { + if (emojisPicker != null && emojisPicker.size() > 0) { GridView gridView = new GridView(context); gridView.setAdapter(new CustomEmojiAdapter(context, android.R.layout.simple_list_item_1, emojisPicker)); gridView.setNumColumns(5); gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { - holder.quick_reply_text.getText().insert(holder.quick_reply_text.getSelectionStart(), " :" + emojisPicker.get(position).getShortcode()+": "); + holder.quick_reply_text.getText().insert(holder.quick_reply_text.getSelectionStart(), " :" + emojisPicker.get(position).getShortcode() + ": "); alertDialogEmoji.dismiss(); } }); - gridView.setPadding(paddingDp,paddingDp,paddingDp,paddingDp); + gridView.setPadding(paddingDp, paddingDp, paddingDp, paddingDp); builder.setView(gridView); - }else{ + } else { TextView textView = new TextView(context); textView.setText(context.getString(R.string.no_emoji)); - textView.setPadding(paddingDp,paddingDp,paddingDp,paddingDp); + textView.setPadding(paddingDp, paddingDp, paddingDp, paddingDp); builder.setView(textView); } alertDialogEmoji = builder.show(); }); - if (status.isNew() && new_badge){ + if (status.isNew() && new_badge) { if (theme == Helper.THEME_BLACK) holder.new_element.setImageResource(R.drawable.ic_fiber_new_dark); holder.new_element.setVisibility(View.VISIBLE); - } - else + } else holder.new_element.setVisibility(View.GONE); @@ -1254,9 +1251,8 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct //Manages theme for icon colors - Helper.changeDrawableColor(context, R.drawable.ic_http, R.color.mastodonC4); - if (getItemViewType(viewHolder.getAdapterPosition()) == COMPACT_STATUS || getItemViewType(viewHolder.getAdapterPosition()) == CONSOLE_STATUS ) + if (getItemViewType(viewHolder.getAdapterPosition()) == COMPACT_STATUS || getItemViewType(viewHolder.getAdapterPosition()) == CONSOLE_STATUS) holder.status_privacy.setVisibility(View.GONE); else holder.status_privacy.setVisibility(View.VISIBLE); @@ -1365,9 +1361,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } - - - if( holder.cached_status != null && (holder.getItemViewType() == DISPLAYED_STATUS && !fedilab_features_button)) { + if (holder.cached_status != null && (holder.getItemViewType() == DISPLAYED_STATUS && !fedilab_features_button)) { if (status.iscached()) { holder.cached_status.setVisibility(View.VISIBLE); } else { @@ -1431,7 +1425,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.fedilab_features_panel.setBackgroundColor(ContextCompat.getColor(context, R.color.custom_features_panel_background_light)); } - if( !status.iscached()){ + if (!status.iscached()) { holder.custom_feature_cache.setVisibility(View.GONE); } @@ -1459,7 +1453,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct return false; }); - if (type == RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE || type == RetrieveFeedsAsyncTask.Type.NEWS){ + if (type == RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE || type == RetrieveFeedsAsyncTask.Type.NEWS) { holder.custom_feature_timed_mute.setVisibility(View.GONE); holder.custom_feature_schedule.setVisibility(View.GONE); holder.custom_feature_cache.setVisibility(View.GONE); @@ -1494,7 +1488,6 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } - //Redraws top icons (boost/reply) final float scale = context.getResources().getDisplayMetrics().density; holder.spark_button_fav.pressOnTouch(false); @@ -1537,12 +1530,12 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.status_toot_date.setCompoundDrawables(imgConversation, null, null, null); } else { holder.status_account_displayname.setCompoundDrawables(null, null, null, null); - holder.status_toot_date.setCompoundDrawables(imgConversation, null, null , null); + holder.status_toot_date.setCompoundDrawables(imgConversation, null, null, null); } - if( expand_media && status.isSensitive() || (status.getReblog() != null && status.getReblog().isSensitive())) { + if (expand_media && status.isSensitive() || (status.getReblog() != null && status.getReblog().isSensitive())) { Helper.changeDrawableColor(context, holder.hide_preview, R.color.red_1); Helper.changeDrawableColor(context, holder.hide_preview_h, R.color.red_1); - }else { + } else { Helper.changeDrawableColor(context, holder.hide_preview, R.color.white); Helper.changeDrawableColor(context, holder.hide_preview_h, R.color.white); } @@ -1597,7 +1590,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct /* if( holder.getAdapterPosition() == position && type == RetrieveFeedsAsyncTask.Type.CONTEXT) return;*/ Bundle b = new Bundle(); - if( social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) + if (social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) b.putString("conversationId", status.getConversationId()); if (status.getReblog() == null) b.putParcelable("status", status); @@ -1622,7 +1615,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct /* if( holder.getAdapterPosition() == position && type == RetrieveFeedsAsyncTask.Type.CONTEXT) return;*/ Bundle b = new Bundle(); - if( social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) + if (social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) b.putString("conversationId", status.getConversationId()); if (status.getReblog() == null) b.putParcelable("status", status); @@ -1647,7 +1640,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct /*if( holder.getAdapterPosition() == position && type == RetrieveFeedsAsyncTask.Type.CONTEXT) return;*/ Bundle b = new Bundle(); - if( social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) + if (social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) b.putString("conversationId", status.getConversationId()); if (status.getReblog() == null) b.putParcelable("status", status); @@ -1666,121 +1659,122 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } - if( isConsoleMode){ + if (isConsoleMode) { String starting = ""; String acct = status.getAccount().getAcct(); String acctReblog = null; - if( !acct.contains("@")) + if (!acct.contains("@")) acct += "@" + Helper.getLiveInstance(context); - if( status.getReblog() != null){ + if (status.getReblog() != null) { acctReblog = status.getReblog().getAccount().getAcct(); - if( !acctReblog.contains("@")) + if (!acctReblog.contains("@")) acctReblog += "@" + Helper.getLiveInstance(context); } - SpannableString acctSpan = new SpannableString(acct+":~$"); + SpannableString acctSpan = new SpannableString(acct + ":~$"); SpannableString acctReblogSpan = null; - if( acctReblog != null) - acctReblogSpan = new SpannableString( " <" + acctReblog + ">"); + if (acctReblog != null) + acctReblogSpan = new SpannableString(" <" + acctReblog + ">"); if (theme == Helper.THEME_LIGHT) - acctSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.console_marker)), (acctSpan.length()-3), acctSpan.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); + acctSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.console_marker)), (acctSpan.length() - 3), acctSpan.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); else if (theme == Helper.THEME_DARK) - acctSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.console_marker)), (acctSpan.length()-3), acctSpan.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); + acctSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.console_marker)), (acctSpan.length() - 3), acctSpan.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); else if (theme == Helper.THEME_BLACK) - acctSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.console_marker)), (acctSpan.length()-3), acctSpan.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); + acctSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.console_marker)), (acctSpan.length() - 3), acctSpan.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); - URLSpan[] urls = acctSpan.getSpans(0, (acctSpan.length()-3), URLSpan.class); - for(URLSpan span : urls) + URLSpan[] urls = acctSpan.getSpans(0, (acctSpan.length() - 3), URLSpan.class); + for (URLSpan span : urls) acctSpan.removeSpan(span); acctSpan.setSpan(new ClickableSpan() { - @Override - public void onClick(@NonNull View textView) { - Intent intent = new Intent(context, ShowAccountActivity.class); - Bundle b = new Bundle(); - b.putParcelable("account", status.getAccount()); - intent.putExtras(b); - context.startActivity(intent); - } - @Override - public void updateDrawState(@NonNull TextPaint ds) { - super.updateDrawState(ds); - ds.setUnderlineText(false); - if (theme == Helper.THEME_DARK) - ds.setColor(ContextCompat.getColor(context, R.color.console_name)); - else if (theme == Helper.THEME_BLACK) - ds.setColor(ContextCompat.getColor(context, R.color.console_name)); - else if (theme == Helper.THEME_LIGHT) - ds.setColor(ContextCompat.getColor(context, R.color.console_name)); - } - }, - 0, (acctSpan.length()-3), + @Override + public void onClick(@NonNull View textView) { + Intent intent = new Intent(context, ShowAccountActivity.class); + Bundle b = new Bundle(); + b.putParcelable("account", status.getAccount()); + intent.putExtras(b); + context.startActivity(intent); + } + + @Override + public void updateDrawState(@NonNull TextPaint ds) { + super.updateDrawState(ds); + ds.setUnderlineText(false); + if (theme == Helper.THEME_DARK) + ds.setColor(ContextCompat.getColor(context, R.color.console_name)); + else if (theme == Helper.THEME_BLACK) + ds.setColor(ContextCompat.getColor(context, R.color.console_name)); + else if (theme == Helper.THEME_LIGHT) + ds.setColor(ContextCompat.getColor(context, R.color.console_name)); + } + }, + 0, (acctSpan.length() - 3), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); SpannableString startingSpan = new SpannableString(starting); - if( acctReblogSpan != null) { - for(URLSpan span : urls) + if (acctReblogSpan != null) { + for (URLSpan span : urls) acctReblogSpan.removeSpan(span); acctReblogSpan.setSpan(new ClickableSpan() { - @Override - public void onClick(@NonNull View textView) { - Intent intent = new Intent(context, ShowAccountActivity.class); - Bundle b = new Bundle(); - b.putParcelable("account", status.getReblog().getAccount()); - intent.putExtras(b); - context.startActivity(intent); - } - @Override - public void updateDrawState(@NonNull TextPaint ds) { - super.updateDrawState(ds); - ds.setUnderlineText(false); - if (theme == Helper.THEME_DARK) - ds.setColor(ContextCompat.getColor(context, R.color.console_reblog_name)); - else if (theme == Helper.THEME_BLACK) - ds.setColor(ContextCompat.getColor(context, R.color.console_reblog_name)); - else if (theme == Helper.THEME_LIGHT) - ds.setColor(ContextCompat.getColor(context, R.color.console_reblog_name)); - } - }, - 2, acctReblogSpan.length()-1, + @Override + public void onClick(@NonNull View textView) { + Intent intent = new Intent(context, ShowAccountActivity.class); + Bundle b = new Bundle(); + b.putParcelable("account", status.getReblog().getAccount()); + intent.putExtras(b); + context.startActivity(intent); + } + + @Override + public void updateDrawState(@NonNull TextPaint ds) { + super.updateDrawState(ds); + ds.setUnderlineText(false); + if (theme == Helper.THEME_DARK) + ds.setColor(ContextCompat.getColor(context, R.color.console_reblog_name)); + else if (theme == Helper.THEME_BLACK) + ds.setColor(ContextCompat.getColor(context, R.color.console_reblog_name)); + else if (theme == Helper.THEME_LIGHT) + ds.setColor(ContextCompat.getColor(context, R.color.console_reblog_name)); + } + }, + 2, acctReblogSpan.length() - 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); if (theme == Helper.THEME_LIGHT) acctReblogSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.console_marker)), 1, 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); else if (theme == Helper.THEME_DARK) - acctReblogSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.console_marker)), 1, 2,Spanned.SPAN_INCLUSIVE_EXCLUSIVE); + acctReblogSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.console_marker)), 1, 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); else if (theme == Helper.THEME_BLACK) - acctReblogSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.console_marker)), 1, 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); + acctReblogSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.console_marker)), 1, 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); if (theme == Helper.THEME_LIGHT) - acctReblogSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.console_marker)), acctReblogSpan.length()-1, acctReblogSpan.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); + acctReblogSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.console_marker)), acctReblogSpan.length() - 1, acctReblogSpan.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); else if (theme == Helper.THEME_DARK) - acctReblogSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.console_marker)), acctReblogSpan.length()-1, acctReblogSpan.length(),Spanned.SPAN_INCLUSIVE_EXCLUSIVE); + acctReblogSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.console_marker)), acctReblogSpan.length() - 1, acctReblogSpan.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); else if (theme == Helper.THEME_BLACK) - acctReblogSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.console_marker)), acctReblogSpan.length()-1, acctReblogSpan.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); + acctReblogSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.console_marker)), acctReblogSpan.length() - 1, acctReblogSpan.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); startingSpan = new SpannableString(TextUtils.concat(acctSpan, new SpannableString(" "), acctReblogSpan)); - }else + } else startingSpan = acctSpan; - if( startingSpan == null) + if (startingSpan == null) startingSpan = new SpannableString(""); - if( status.getContentSpan() == null) + if (status.getContentSpan() == null) status.setContentSpan(new SpannableString("")); - if( status.getReblog() == null && status.getSpoiler_text() != null && status.getSpoiler_text().length() > 0) { + if (status.getReblog() == null && status.getSpoiler_text() != null && status.getSpoiler_text().length() > 0) { holder.status_spoiler.setText(TextUtils.concat(startingSpan, new SpannableString(" "), status.getContentSpanCW()), TextView.BufferType.SPANNABLE); holder.status_content.setText(status.getContentSpan(), TextView.BufferType.SPANNABLE); - }else if( status.getReblog() != null && status.getReblog().getSpoiler_text() != null && status.getReblog().getSpoiler_text().length() > 0) { + } else if (status.getReblog() != null && status.getReblog().getSpoiler_text() != null && status.getReblog().getSpoiler_text().length() > 0) { holder.status_spoiler.setText(TextUtils.concat(startingSpan, new SpannableString(" "), status.getContentSpanCW()), TextView.BufferType.SPANNABLE); holder.status_content.setText(status.getContentSpan(), TextView.BufferType.SPANNABLE); } else { holder.status_spoiler.setText(status.getContentSpanCW(), TextView.BufferType.SPANNABLE); - holder.status_content.setText(TextUtils.concat(startingSpan, new SpannableString(" "), status.getContentSpan()!=null?status.getContentSpan():new SpannableString("")), TextView.BufferType.SPANNABLE); + holder.status_content.setText(TextUtils.concat(startingSpan, new SpannableString(" "), status.getContentSpan() != null ? status.getContentSpan() : new SpannableString("")), TextView.BufferType.SPANNABLE); } - }else { + } else { holder.status_content.setText(status.getContentSpan(), TextView.BufferType.SPANNABLE); holder.status_spoiler.setText(status.getContentSpanCW(), TextView.BufferType.SPANNABLE); } - holder.status_content.setMovementMethod(LinkMovementMethod.getInstance()); holder.status_spoiler.setMovementMethod(LinkMovementMethod.getInstance()); if (truncate_toots_size > 0) { @@ -1899,18 +1893,18 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct status.setFetchMore(false); holder.fetch_more.setEnabled(false); holder.fetch_more.setVisibility(View.GONE); - if( context instanceof BaseMainActivity) { + if (context instanceof BaseMainActivity) { SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); List timelines = new TimelinesDAO(context, db).getDisplayedTimelines(); - for(ManageTimelines tl: timelines) { - if( tl.getType() == ManageTimelines.Type.HOME && mPageReferenceMap != null) { + for (ManageTimelines tl : timelines) { + if (tl.getType() == ManageTimelines.Type.HOME && mPageReferenceMap != null) { DisplayStatusFragment homeFragment = (DisplayStatusFragment) mPageReferenceMap.get(tl.getPosition()); if (homeFragment != null) homeFragment.fetchMore(status.getId()); break; } } - }else{ + } else { Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); } } @@ -1921,11 +1915,11 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct status.setFetchMore(false); holder.fetch_more.setEnabled(false); holder.fetch_more.setVisibility(View.GONE); - if( context instanceof BaseMainActivity) { + if (context instanceof BaseMainActivity) { SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); List timelines = new TimelinesDAO(context, db).getDisplayedTimelines(); - for(ManageTimelines tl: timelines) { - if( tl.getType() == ManageTimelines.Type.HOME && mPageReferenceMap != null) { + for (ManageTimelines tl : timelines) { + if (tl.getType() == ManageTimelines.Type.HOME && mPageReferenceMap != null) { DisplayStatusFragment homeFragment = (DisplayStatusFragment) mPageReferenceMap.get(tl.getPosition()); if (homeFragment != null) { fetch_all_more = true; @@ -1934,7 +1928,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct break; } } - }else{ + } else { Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); } return false; @@ -1949,12 +1943,12 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.status_mention_spoiler.setText(Helper.makeMentionsClick(context, status.getMentions()), TextView.BufferType.SPANNABLE); holder.status_mention_spoiler.setMovementMethod(LinkMovementMethod.getInstance()); - if ((isCompactMode || isConsoleMode) && getItemViewType(viewHolder.getAdapterPosition()) != FOCUSED_STATUS){ + if ((isCompactMode || isConsoleMode) && getItemViewType(viewHolder.getAdapterPosition()) != FOCUSED_STATUS) { - if((status.getReblog() == null && status.getReplies_count() > 1) || (status.getReblog() != null && status.getReblog().getReplies_count() > 1)) { + if ((status.getReblog() == null && status.getReplies_count() > 1) || (status.getReblog() != null && status.getReblog().getReplies_count() > 1)) { Drawable img = context.getResources().getDrawable(R.drawable.ic_plus_one); holder.status_reply_count.setCompoundDrawablesWithIntrinsicBounds(null, null, img, null); - }else{ + } else { holder.status_reply_count.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); } } @@ -1965,8 +1959,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.status_reply_count.setText(String.valueOf(status.getReplies_count())); else holder.status_reply_count.setText(""); - } - else { + } else { if (status.getReblog().getReplies_count() > 0) holder.status_reply_count.setText(String.valueOf(status.getReblog().getReplies_count())); else @@ -1978,8 +1971,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.status_favorite_count.setText(String.valueOf(status.getFavourites_count())); else holder.status_favorite_count.setText(""); - } - else { + } else { if (status.getReblog().getFavourites_count() > 0) holder.status_favorite_count.setText(String.valueOf(status.getReblog().getFavourites_count())); else @@ -1991,8 +1983,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.status_reblog_count.setText(String.valueOf(status.getReblogs_count())); else holder.status_reblog_count.setText(""); - } - else { + } else { if (status.getReblog().getReblogs_count() > 0) holder.status_reblog_count.setText(String.valueOf(status.getReblog().getReblogs_count())); else @@ -2012,7 +2003,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct if (status.getReblog() != null) { Helper.loadGiF(context, accountForUrl.getAvatar(), holder.status_account_profile_boost); - Helper.loadGiF(context, status.getAccount().getAvatar(),holder.status_account_profile_boost_by); + Helper.loadGiF(context, status.getAccount().getAvatar(), holder.status_account_profile_boost_by); holder.status_account_profile_boost.setVisibility(View.VISIBLE); holder.status_account_profile_boost_by.setVisibility(View.VISIBLE); holder.status_account_profile.setVisibility(View.GONE); @@ -2090,11 +2081,11 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.status_spoiler_mention_container.setVisibility(View.GONE); holder.status_spoiler_button.setText(context.getString(R.string.load_attachment_spoiler)); } else { - if( !status.isAutoHiddenCW()) { + if (!status.isAutoHiddenCW()) { holder.status_content_container.setVisibility(View.VISIBLE); holder.status_spoiler_mention_container.setVisibility(View.GONE); holder.status_spoiler_button.setText(context.getString(R.string.load_attachment_spoiler_less)); - }else{ + } else { holder.status_content_container.setVisibility(View.GONE); if (status.getMentions().size() > 0) holder.status_spoiler_mention_container.setVisibility(View.VISIBLE); @@ -2119,11 +2110,11 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.status_spoiler_mention_container.setVisibility(View.GONE); holder.status_spoiler_button.setText(context.getString(R.string.load_attachment_spoiler)); } else { - if( !status.isAutoHiddenCW()) { + if (!status.isAutoHiddenCW()) { holder.status_content_container.setVisibility(View.VISIBLE); holder.status_spoiler_mention_container.setVisibility(View.GONE); holder.status_spoiler_button.setText(context.getString(R.string.load_attachment_spoiler_less)); - }else { + } else { holder.status_content_container.setVisibility(View.GONE); if (status.getMentions().size() > 0) holder.status_spoiler_mention_container.setVisibility(View.VISIBLE); @@ -2147,7 +2138,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.status_show_more.setVisibility(View.GONE); } else { //If medias are loaded without any conditions or if device is on wifi - if(behaviorWithAttachments != Helper.ATTACHMENT_ASK ) { + if (behaviorWithAttachments != Helper.ATTACHMENT_ASK) { if (expand_media || !status.isSensitive() && (behaviorWithAttachments == Helper.ATTACHMENT_ALWAYS || (behaviorWithAttachments == Helper.ATTACHMENT_WIFI && isOnWifi))) { loadAttachments(status, holder, false); holder.status_show_more.setVisibility(View.GONE); @@ -2162,14 +2153,14 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.status_horizontal_document_container.setVisibility(View.GONE); else holder.status_document_container.setVisibility(View.GONE); - if(blur_sensitive && (behaviorWithAttachments == Helper.ATTACHMENT_ALWAYS || (behaviorWithAttachments == Helper.ATTACHMENT_WIFI && isOnWifi))){ + if (blur_sensitive && (behaviorWithAttachments == Helper.ATTACHMENT_ALWAYS || (behaviorWithAttachments == Helper.ATTACHMENT_WIFI && isOnWifi))) { loadAttachments(status, holder, true); } } else { loadAttachments(status, holder, false); } } - }else { + } else { //Text depending if toots is sensitive or not String textShowMore = (status.isSensitive()) ? context.getString(R.string.load_sensitive_attachment) : context.getString(R.string.set_attachment_action); holder.show_more_content.setText(textShowMore); @@ -2191,7 +2182,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.status_document_container.setVisibility(View.GONE); holder.status_show_more.setVisibility(View.GONE); } else { - if(behaviorWithAttachments != Helper.ATTACHMENT_ASK ) { + if (behaviorWithAttachments != Helper.ATTACHMENT_ASK) { //If medias are loaded without any conditions or if device is on wifi if (expand_media || !status.getReblog().isSensitive() && (behaviorWithAttachments == Helper.ATTACHMENT_ALWAYS || (behaviorWithAttachments == Helper.ATTACHMENT_WIFI && isOnWifi))) { loadAttachments(status, holder, false); @@ -2207,14 +2198,14 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.status_horizontal_document_container.setVisibility(View.GONE); else holder.status_document_container.setVisibility(View.GONE); - if(blur_sensitive && (behaviorWithAttachments == Helper.ATTACHMENT_ALWAYS || (behaviorWithAttachments == Helper.ATTACHMENT_WIFI && isOnWifi))){ + if (blur_sensitive && (behaviorWithAttachments == Helper.ATTACHMENT_ALWAYS || (behaviorWithAttachments == Helper.ATTACHMENT_WIFI && isOnWifi))) { loadAttachments(status, holder, true); } } else { loadAttachments(status, holder, false); } } - }else{ + } else { //Text depending if toots is sensitive or not String textShowMore = (status.getReblog().isSensitive()) ? context.getString(R.string.load_sensitive_attachment) : context.getString(R.string.set_attachment_action); holder.show_more_content.setText(textShowMore); @@ -2303,7 +2294,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.spark_button_reblog.setVisibility(View.GONE); break; case "private": - final boolean isOwner = status.getReblog()!=null?status.getReblog().getAccount().getId().equals(userId):status.getAccount().getId().equals(userId); + final boolean isOwner = status.getReblog() != null ? status.getReblog().getAccount().getId().equals(userId) : status.getAccount().getId().equals(userId); if (isOwner) { holder.status_reblog_count.setVisibility(View.VISIBLE); holder.spark_button_reblog.setVisibility(View.VISIBLE); @@ -2370,7 +2361,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct else Helper.changeDrawableColor(context, R.drawable.ic_reply, R.color.action_light); - final boolean isOwner = status.getReblog()!=null?status.getReblog().getAccount().getId().equals(userId):status.getAccount().getId().equals(userId); + final boolean isOwner = status.getReblog() != null ? status.getReblog().getAccount().getId().equals(userId) : status.getAccount().getId().equals(userId); // Pinning toots is only available on Mastodon 1._6_.0 instances. if (isOwner && Helper.canPin && (status.getVisibility().equals("public") || status.getVisibility().equals("unlisted")) && status.getReblog() == null) { @@ -2396,15 +2387,15 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.status_pin.setVisibility(View.GONE); } - if( (isAdmin || isModerator) && !isCompactMode && !isConsoleMode && getItemViewType(viewHolder.getAdapterPosition()) != FOCUSED_STATUS && type != RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE && type != RetrieveFeedsAsyncTask.Type.NEWS){ + if ((isAdmin || isModerator) && !isCompactMode && !isConsoleMode && getItemViewType(viewHolder.getAdapterPosition()) != FOCUSED_STATUS && type != RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE && type != RetrieveFeedsAsyncTask.Type.NEWS) { holder.status_remove.setVisibility(View.VISIBLE); - }else { + } else { holder.status_remove.setVisibility(View.GONE); } - if( status.getReblog() == null){ + if (status.getReblog() == null) { if (status.getWebviewURL() != null) { - String url = status.getWebviewURL().replaceAll("&","&"); + String url = status.getWebviewURL().replaceAll("&", "&"); holder.status_cardview_webview.loadUrl(url); holder.status_cardview_webview.setVisibility(View.VISIBLE); holder.status_cardview_video.setVisibility(View.VISIBLE); @@ -2414,9 +2405,9 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.status_cardview_video.setVisibility(View.GONE); holder.webview_preview.setVisibility(View.VISIBLE); } - }else{ + } else { if (status.getReblog().getWebviewURL() != null) { - String url = status.getReblog().getWebviewURL().replaceAll("&","&"); + String url = status.getReblog().getWebviewURL().replaceAll("&", "&"); holder.status_cardview_webview.loadUrl(url); holder.status_cardview_webview.setVisibility(View.VISIBLE); holder.status_cardview_video.setVisibility(View.VISIBLE); @@ -2429,7 +2420,6 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } - holder.quick_reply_button.setOnClickListener(view -> { sendToot(null); status.setShortReply(false); @@ -2497,7 +2487,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct dialog.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int position) { - switch (position){ + switch (position) { case 0: visibility = "public"; holder.quick_reply_privacy.setImageResource(R.drawable.ic_public_toot); @@ -2523,7 +2513,6 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct }); - if ((type == RetrieveFeedsAsyncTask.Type.CONTEXT && viewHolder.getAdapterPosition() == conversationPosition) || display_card || display_video_preview) { if (type == RetrieveFeedsAsyncTask.Type.CONTEXT & viewHolder.getAdapterPosition() == conversationPosition) @@ -2581,14 +2570,14 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct @Override public void onClick(View v) { String url = finalSrc; - if( url != null) { + if (url != null) { boolean invidious = sharedpreferences.getBoolean(Helper.SET_INVIDIOUS, false); Matcher matcher = Helper.youtubeOembedPattern.matcher(url); if (invidious) { while (matcher.find()) { final String youtubeId = matcher.group(2); String invidiousHost = sharedpreferences.getString(Helper.SET_INVIDIOUS_HOST, Helper.DEFAULT_INVIDIOUS_HOST); - url = url.replaceAll(Pattern.quote(matcher.group()), Matcher.quoteReplacement(invidiousHost+"/embed/" + youtubeId+"?feature=oembed")); + url = url.replaceAll(Pattern.quote(matcher.group()), Matcher.quoteReplacement(invidiousHost + "/embed/" + youtubeId + "?feature=oembed")); } } @@ -2612,9 +2601,9 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.status_cardview_video.setVisibility(View.GONE); } - if( status.isShortReply()){ + if (status.isShortReply()) { holder.quick_reply_container.setVisibility(View.VISIBLE); - }else{ + } else { holder.quick_reply_container.setVisibility(View.GONE); } holder.quick_reply_container.setOnClickListener(view -> { @@ -2626,18 +2615,18 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct if (quick_reply && type != RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE && type != RetrieveFeedsAsyncTask.Type.NEWS) { - if( context instanceof BaseMainActivity){ + if (context instanceof BaseMainActivity) { FloatingActionButton toot = ((BaseMainActivity) context).findViewById(R.id.toot); - if( toot != null){ + if (toot != null) { toot.hide(); } } holder.warning_message.setVisibility(View.GONE); - if( status.getWarningFetched() == -1 ){ + if (status.getWarningFetched() == -1) { warning_message = holder.warning_message; - new RetrieveRelationshipQuickReplyAsyncTask(context, status,StatusListAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new RetrieveRelationshipQuickReplyAsyncTask(context, status, StatusListAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else if(status.getWarningFetched() == 1){ + } else if (status.getWarningFetched() == 1) { holder.warning_message.setVisibility(View.VISIBLE); } @@ -2658,9 +2647,9 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct InputMethodManager.SHOW_FORCED, 0); holder.quick_reply_text.requestFocus(); EditText content_cw = new EditText(context); - content_cw.setText(status.getReblog()!=null?status.getReblog().getSpoiler_text():status.getSpoiler_text()); - TootActivity.manageMentions(context, social,userId, - holder.quick_reply_text,content_cw, holder.toot_space_left,status.getReblog()!=null?status.getReblog():status); + content_cw.setText(status.getReblog() != null ? status.getReblog().getSpoiler_text() : status.getSpoiler_text()); + TootActivity.manageMentions(context, social, userId, + holder.quick_reply_text, content_cw, holder.toot_space_left, status.getReblog() != null ? status.getReblog() : status); TextWatcher textWatcher = TootActivity.initializeTextWatcher(context, social, holder.quick_reply_text, content_cw, holder.toot_space_left, null, null, StatusListAdapter.this, StatusListAdapter.this, StatusListAdapter.this); toot_content = holder.quick_reply_text; @@ -2668,23 +2657,23 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct toot_content.setInputType(newInputType); toot_cw_content = content_cw; toot_space_left = holder.toot_space_left; - in_reply_to_status = status.getReblog() != null ? status.getReblog().getId():status.getId(); + in_reply_to_status = status.getReblog() != null ? status.getReblog().getId() : status.getId(); tootReply = status; - if( theme == Helper.THEME_DARK || theme == Helper.THEME_BLACK) { + if (theme == Helper.THEME_DARK || theme == Helper.THEME_BLACK) { changeDrawableColor(context, R.drawable.emoji_one_category_smileysandpeople, R.color.dark_text); changeDrawableColor(context, R.drawable.ic_public_toot, R.color.dark_text); changeDrawableColor(context, R.drawable.ic_lock_open_toot, R.color.dark_text); changeDrawableColor(context, R.drawable.ic_lock_outline_toot, R.color.dark_text); changeDrawableColor(context, R.drawable.ic_mail_outline_toot, R.color.dark_text); changeDrawableColor(context, holder.quick_reply_switch_to_full, R.color.dark_text); - if( theme == Helper.THEME_DARK) { + if (theme == Helper.THEME_DARK) { holder.quick_reply_container.setBackgroundResource(R.drawable.quick_reply_background); changeDrawableColor(context, R.drawable.quick_reply_background, R.color.quick_reply_background_dark); - }else{ + } else { holder.quick_reply_container.setBackgroundResource(R.drawable.quick_reply_background_black); changeDrawableColor(context, R.drawable.quick_reply_background, R.color.quick_reply_background_black); } - }else { + } else { holder.quick_reply_container.setBackgroundResource(R.drawable.quick_reply_background_light); changeDrawableColor(context, R.drawable.emoji_one_category_smileysandpeople, R.color.black); changeDrawableColor(context, R.drawable.ic_public_toot, R.color.black); @@ -2699,16 +2688,16 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, null); Account account = new AccountDAO(context, db).getUniqAccount(userId, instance); - String defaultVisibility = account.isLocked()?"private":"public"; + String defaultVisibility = account.isLocked() ? "private" : "public"; String settingsVisibility = sharedpreferences.getString(Helper.SET_TOOT_VISIBILITY + "@" + account.getAcct() + "@" + account.getInstance(), defaultVisibility); int initialTootVisibility = 0; int ownerTootVisibility = 0; - switch (status.getReblog() != null ?status.getReblog().getVisibility():status.getVisibility()){ + switch (status.getReblog() != null ? status.getReblog().getVisibility() : status.getVisibility()) { case "public": initialTootVisibility = 4; break; case "unlisted": - initialTootVisibility = 3; + initialTootVisibility = 3; break; case "private": visibility = "private"; @@ -2720,12 +2709,12 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct break; } if (settingsVisibility != null) { - switch (settingsVisibility){ + switch (settingsVisibility) { case "public": ownerTootVisibility = 4; break; case "unlisted": - ownerTootVisibility = 3; + ownerTootVisibility = 3; break; case "private": visibility = "private"; @@ -2738,12 +2727,12 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } } int tootVisibility; - if( ownerTootVisibility >= initialTootVisibility){ + if (ownerTootVisibility >= initialTootVisibility) { tootVisibility = initialTootVisibility; - }else { + } else { tootVisibility = ownerTootVisibility; } - switch (tootVisibility){ + switch (tootVisibility) { case 4: visibility = "public"; holder.quick_reply_privacy.setImageResource(R.drawable.ic_public_toot); @@ -2778,9 +2767,9 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.quick_reply_container.setVisibility(View.GONE); Intent intent = new Intent(context, TootActivity.class); Bundle b = new Bundle(); - if( status != null && status.getReblog() != null ) { + if (status != null && status.getReblog() != null) { b.putParcelable("tootReply", status.getReblog()); - }else { + } else { b.putParcelable("tootReply", status); } @@ -2788,11 +2777,12 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct b.putString("quickmessagecontent", holder.quick_reply_text.getText().toString()); intent.putExtras(b); //Put your id to your next Intent context.startActivity(intent); - if( type == RetrieveFeedsAsyncTask.Type.CONTEXT ){ + if (type == RetrieveFeedsAsyncTask.Type.CONTEXT) { try { //Avoid to open multi activities when replying in a conversation - ((ShowConversationActivity)context).finish(); - }catch (Exception ignored){} + ((ShowConversationActivity) context).finish(); + } catch (Exception ignored) { + } } } @@ -2981,9 +2971,9 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.status_spoiler_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - if( expand_cw && !status.isSpoilerShown() ){ + if (expand_cw && !status.isSpoilerShown()) { status.setAutoHiddenCW(true); - }else{ + } else { status.setAutoHiddenCW(false); } status.setSpoilerShown(!status.isSpoilerShown()); @@ -3000,7 +2990,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct @Override public void onClick(View v) { PopupMenu popup = new PopupMenu(context, attached); - final boolean isOwner = status.getReblog()!=null?status.getReblog().getAccount().getId().equals(userId):status.getAccount().getId().equals(userId); + final boolean isOwner = status.getReblog() != null ? status.getReblog().getAccount().getId().equals(userId) : status.getAccount().getId().equals(userId); popup.getMenuInflater() .inflate(R.menu.option_toot, popup.getMenu()); if (status.getVisibility().equals("private") || status.getVisibility().equals("direct")) { @@ -3026,16 +3016,16 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct popup.getMenu().findItem(R.id.action_timed_mute).setVisible(false); popup.getMenu().findItem(R.id.action_block_domain).setVisible(false); stringArrayConf = context.getResources().getStringArray(R.array.more_action_owner_confirm); - if( social != UpdateAccountInfoAsyncTask.SOCIAL.MASTODON && social != UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA){ + if (social != UpdateAccountInfoAsyncTask.SOCIAL.MASTODON && social != UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { popup.getMenu().findItem(R.id.action_stats).setVisible(false); } } else { popup.getMenu().findItem(R.id.action_stats).setVisible(false); popup.getMenu().findItem(R.id.action_redraft).setVisible(false); //popup.getMenu().findItem(R.id.action_mute_conversation).setVisible(false); - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA && (isAdmin || isModerator)) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA && (isAdmin || isModerator)) { popup.getMenu().findItem(R.id.action_remove).setVisible(true); - }else { + } else { popup.getMenu().findItem(R.id.action_remove).setVisible(false); } //Same instance @@ -3043,7 +3033,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct popup.getMenu().findItem(R.id.action_block_domain).setVisible(false); stringArrayConf = context.getResources().getStringArray(R.array.more_action_confirm); } - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA){ + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { popup.getMenu().findItem(R.id.action_info).setVisible(false); popup.getMenu().findItem(R.id.action_report).setVisible(false); popup.getMenu().findItem(R.id.action_block_domain).setVisible(false); @@ -3056,17 +3046,17 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct popup.getMenu().findItem(R.id.action_schedule_boost).setVisible(false); popup.getMenu().findItem(R.id.action_mention).setVisible(false); } - if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.MASTODON && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA){ + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.MASTODON && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { popup.getMenu().findItem(R.id.action_admin).setVisible(false); - }else{ + } else { boolean display_admin_statuses = sharedpreferences.getBoolean(Helper.SET_DISPLAY_ADMIN_STATUSES + userId + Helper.getLiveInstance(context), false); - if( !display_admin_statuses){ + if (!display_admin_statuses) { popup.getMenu().findItem(R.id.action_admin).setVisible(false); } } boolean custom_sharing = sharedpreferences.getBoolean(Helper.SET_CUSTOM_SHARING, false); - if( custom_sharing && status.getVisibility().equals("public")) + if (custom_sharing && status.getVisibility().equals("public")) popup.getMenu().findItem(R.id.action_custom_sharing).setVisible(true); MenuItem itemBookmark = popup.getMenu().findItem(R.id.action_bookmark); if (itemBookmark.getActionView() != null) @@ -3101,9 +3091,9 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct String acct = status.getReblog() != null ? status.getReblog().getAccount().getAcct() : status.getAccount().getAcct(); Intent intent = new Intent(context, AccountReportActivity.class); Bundle b = new Bundle(); - if( social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { + if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { b.putString("account_id", account_id); - }else if( social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA){ + } else if (social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { b.putString("account_id", acct); } intent.putExtras(b); @@ -3139,7 +3129,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct doAction = API.StatusAction.MUTE; break; case R.id.action_mute_conversation: - if( status.isMuted()) + if (status.isMuted()) doAction = API.StatusAction.UNMUTE_CONVERSATION; else doAction = API.StatusAction.MUTE_CONVERSATION; @@ -3181,7 +3171,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct case R.id.action_stats: intent = new Intent(context, OwnerNotificationChartsActivity.class); b = new Bundle(); - b.putString("status_id", status.getReblog()!=null?status.getReblog().getId():status.getId()); + b.putString("status_id", status.getReblog() != null ? status.getReblog().getId() : status.getId()); intent.putExtras(b); context.startActivity(intent); return true; @@ -3226,7 +3216,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct case R.id.action_copy_link: clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); - clip = ClipData.newPlainText(Helper.CLIP_BOARD, status.getReblog()!=null?status.getReblog().getUrl():status.getUrl()); + clip = ClipData.newPlainText(Helper.CLIP_BOARD, status.getReblog() != null ? status.getReblog().getUrl() : status.getUrl()); if (clipboard != null) { clipboard.setPrimaryClip(clip); Toasty.info(context, context.getString(R.string.clipboard_url), Toast.LENGTH_LONG).show(); @@ -3322,9 +3312,9 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct toot.setSpoiler_text(status.getSpoiler_text().trim()); toot.setContent(status.getContent()); toot.setVisibility(status.getVisibility()); - if( status.getPoll() != null){ + if (status.getPoll() != null) { toot.setPoll(status.getPoll()); - }else if(status.getReblog() != null && status.getReblog().getPoll() != null ) { + } else if (status.getReblog() != null && status.getReblog().getPoll() != null) { toot.setPoll(status.getPoll()); } new RetrieveFeedsAsyncTask(context, RetrieveFeedsAsyncTask.Type.ONESTATUS, status.getIn_reply_to_id(), null, false, false, StatusListAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); @@ -3336,9 +3326,9 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct toot.setSpoiler_text(status.getSpoiler_text().trim()); toot.setVisibility(status.getVisibility()); toot.setContent(status.getContent()); - if( status.getPoll() != null){ + if (status.getPoll() != null) { toot.setPoll(status.getPoll()); - }else if(status.getReblog() != null && status.getReblog().getPoll() != null ) { + } else if (status.getReblog() != null && status.getReblog().getPoll() != null) { toot.setPoll(status.getPoll()); } final SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); @@ -3418,7 +3408,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct instance = matcher.group(1); } account.setInstance(instance); - if(MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) CrossActions.doCrossProfile(context, account); else { Intent intent = new Intent(context, ShowAccountActivity.class); @@ -3443,7 +3433,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct instance = matcher.group(1); } account.setInstance(instance); - if(MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) CrossActions.doCrossProfile(context, account); else { Intent intent = new Intent(context, ShowAccountActivity.class); @@ -3458,7 +3448,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct }); } - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON){ + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { if (getItemViewType(viewHolder.getAdapterPosition()) == FOCUSED_STATUS && status.getApplication() != null && status.getApplication().getName() != null && status.getApplication().getName().length() > 0) { Application application = status.getApplication(); holder.status_toot_app.setText(application.getName()); @@ -3474,7 +3464,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } else { holder.status_toot_app.setVisibility(View.GONE); } - }else{ + } else { holder.status_toot_app.setVisibility(View.GONE); } } @@ -3482,28 +3472,27 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } - - private void loadAttachments(final Status status, final ViewHolder holder, boolean blur){ + private void loadAttachments(final Status status, final ViewHolder holder, boolean blur) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); boolean fullAttachement = sharedpreferences.getBoolean(Helper.SET_FULL_PREVIEW, false); List attachments; - if( status.getReblog() != null) + if (status.getReblog() != null) attachments = status.getReblog().getMedia_attachments(); else attachments = status.getMedia_attachments(); - if( !blur) + if (!blur) holder.status_show_more.setVisibility(View.GONE); else holder.status_show_more.setVisibility(View.VISIBLE); - if( attachments != null && attachments.size() > 0){ + if (attachments != null && attachments.size() > 0) { int i = 0; holder.horizontal_second_image.setVisibility(View.VISIBLE); - if(fullAttachement) + if (fullAttachement) holder.status_horizontal_document_container.setVisibility(View.VISIBLE); else holder.status_document_container.setVisibility(View.VISIBLE); - if( attachments.size() == 1 ){ - if( !fullAttachement) + if (attachments.size() == 1) { + if (!fullAttachement) holder.status_container2.setVisibility(View.GONE); else { holder.status_prev1_h.setVisibility(View.VISIBLE); @@ -3512,19 +3501,19 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.status_prev4_h.setVisibility(View.GONE); holder.horizontal_second_image.setVisibility(View.GONE); } - if( attachments.get(0).getUrl().trim().contains("missing.png")) - if(fullAttachement) + if (attachments.get(0).getUrl().trim().contains("missing.png")) + if (fullAttachement) holder.status_horizontal_document_container.setVisibility(View.GONE); else holder.status_document_container.setVisibility(View.GONE); - }else if(attachments.size() == 2){ - if( !fullAttachement) { + } else if (attachments.size() == 2) { + if (!fullAttachement) { holder.status_container2.setVisibility(View.VISIBLE); holder.status_container3.setVisibility(View.GONE); holder.status_prev4_container.setVisibility(View.GONE); if (attachments.get(1).getUrl().trim().contains("missing.png")) holder.status_container2.setVisibility(View.GONE); - }else { + } else { holder.status_prev1_h.setVisibility(View.VISIBLE); holder.status_prev2_h.setVisibility(View.VISIBLE); holder.status_prev3_h.setVisibility(View.GONE); @@ -3532,14 +3521,14 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct if (attachments.get(1).getUrl().trim().contains("missing.png")) holder.status_prev2_h.setVisibility(View.GONE); } - }else if( attachments.size() == 3 ){ - if( !fullAttachement) { + } else if (attachments.size() == 3) { + if (!fullAttachement) { holder.status_container2.setVisibility(View.VISIBLE); holder.status_container3.setVisibility(View.VISIBLE); holder.status_prev4_container.setVisibility(View.GONE); if (attachments.get(2).getUrl().trim().contains("missing.png")) holder.status_container3.setVisibility(View.GONE); - }else { + } else { holder.status_prev1_h.setVisibility(View.VISIBLE); holder.status_prev2_h.setVisibility(View.VISIBLE); holder.status_prev3_h.setVisibility(View.VISIBLE); @@ -3547,14 +3536,14 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct if (attachments.get(2).getUrl().trim().contains("missing.png")) holder.status_prev3_h.setVisibility(View.GONE); } - }else { - if(!fullAttachement) { + } else { + if (!fullAttachement) { holder.status_container2.setVisibility(View.VISIBLE); holder.status_container3.setVisibility(View.VISIBLE); holder.status_prev4_container.setVisibility(View.VISIBLE); if (attachments.get(2).getUrl().trim().contains("missing.png")) holder.status_prev4_container.setVisibility(View.GONE); - }else { + } else { holder.status_prev1_h.setVisibility(View.VISIBLE); holder.status_prev2_h.setVisibility(View.VISIBLE); holder.status_prev3_h.setVisibility(View.VISIBLE); @@ -3564,24 +3553,24 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } } int position = 1; - for(final Attachment attachment: attachments){ + for (final Attachment attachment : attachments) { ImageView imageView; RelativeLayout container = holder.status_horizontal_document_container; - if( i == 0) { - imageView = fullAttachement?holder.status_prev1_h:holder.status_prev1; - if( attachment.getType().toLowerCase().equals("image") || attachment.getType().toLowerCase().equals("unknown")) - if( fullAttachement) + if (i == 0) { + imageView = fullAttachement ? holder.status_prev1_h : holder.status_prev1; + if (attachment.getType().toLowerCase().equals("image") || attachment.getType().toLowerCase().equals("unknown")) + if (fullAttachement) holder.status_prev1_play_h.setVisibility(View.GONE); else holder.status_prev1_play.setVisibility(View.GONE); else { - if( attachment.getType().toLowerCase().equals("video") || attachment.getType().toLowerCase().equals("audio")) { + if (attachment.getType().toLowerCase().equals("video") || attachment.getType().toLowerCase().equals("audio")) { holder.status_prev1_play_h.setImageResource(R.drawable.ic_video_preview); holder.status_prev1_play.setImageResource(R.drawable.ic_video_preview); - }else if( attachment.getType().toLowerCase().equals("gifv")) { + } else if (attachment.getType().toLowerCase().equals("gifv")) { holder.status_prev1_play.setImageResource(R.drawable.ic_gif_preview); holder.status_prev1_play_h.setImageResource(R.drawable.ic_gif_preview); - }else if(attachment.getType().toLowerCase().equals("web")){ + } else if (attachment.getType().toLowerCase().equals("web")) { holder.status_prev1_play.setImageResource(R.drawable.ic_http); } if (fullAttachement) @@ -3589,21 +3578,21 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct else holder.status_prev1_play.setVisibility(View.VISIBLE); } - }else if( i == 1) { - imageView = fullAttachement?holder.status_prev2_h:holder.status_prev2; - if( attachment.getType().toLowerCase().equals("image") || attachment.getType().toLowerCase().equals("unknown")) - if( fullAttachement) + } else if (i == 1) { + imageView = fullAttachement ? holder.status_prev2_h : holder.status_prev2; + if (attachment.getType().toLowerCase().equals("image") || attachment.getType().toLowerCase().equals("unknown")) + if (fullAttachement) holder.status_prev2_play_h.setVisibility(View.GONE); else holder.status_prev2_play.setVisibility(View.GONE); else { - if( attachment.getType().toLowerCase().equals("video") || attachment.getType().toLowerCase().equals("audio")) { + if (attachment.getType().toLowerCase().equals("video") || attachment.getType().toLowerCase().equals("audio")) { holder.status_prev2_play_h.setImageResource(R.drawable.ic_video_preview); holder.status_prev2_play.setImageResource(R.drawable.ic_video_preview); - }else if( attachment.getType().toLowerCase().equals("gifv")) { + } else if (attachment.getType().toLowerCase().equals("gifv")) { holder.status_prev2_play_h.setImageResource(R.drawable.ic_gif_preview); holder.status_prev2_play.setImageResource(R.drawable.ic_gif_preview); - }else if(attachment.getType().toLowerCase().equals("web")){ + } else if (attachment.getType().toLowerCase().equals("web")) { holder.status_prev1_play.setImageResource(R.drawable.ic_http); } if (fullAttachement) @@ -3611,21 +3600,21 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct else holder.status_prev2_play.setVisibility(View.VISIBLE); } - }else if(i == 2) { - imageView = fullAttachement?holder.status_prev3_h:holder.status_prev3; - if( attachment.getType().toLowerCase().equals("image") || attachment.getType().toLowerCase().equals("unknown")) - if( fullAttachement) + } else if (i == 2) { + imageView = fullAttachement ? holder.status_prev3_h : holder.status_prev3; + if (attachment.getType().toLowerCase().equals("image") || attachment.getType().toLowerCase().equals("unknown")) + if (fullAttachement) holder.status_prev3_play_h.setVisibility(View.GONE); else holder.status_prev3_play.setVisibility(View.GONE); else { - if( attachment.getType().toLowerCase().equals("video") || attachment.getType().toLowerCase().equals("audio")) { + if (attachment.getType().toLowerCase().equals("video") || attachment.getType().toLowerCase().equals("audio")) { holder.status_prev3_play_h.setImageResource(R.drawable.ic_video_preview); holder.status_prev3_play.setImageResource(R.drawable.ic_video_preview); - }else if( attachment.getType().toLowerCase().equals("gifv")) { + } else if (attachment.getType().toLowerCase().equals("gifv")) { holder.status_prev3_play_h.setImageResource(R.drawable.ic_gif_preview); holder.status_prev3_play.setImageResource(R.drawable.ic_gif_preview); - }else if(attachment.getType().toLowerCase().equals("web")){ + } else if (attachment.getType().toLowerCase().equals("web")) { holder.status_prev1_play.setImageResource(R.drawable.ic_http); } if (fullAttachement) @@ -3633,21 +3622,21 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct else holder.status_prev3_play.setVisibility(View.VISIBLE); } - }else { - imageView = fullAttachement?holder.status_prev4_h:holder.status_prev4; - if( attachment.getType().toLowerCase().equals("image") || attachment.getType().toLowerCase().equals("unknown")) - if( fullAttachement) + } else { + imageView = fullAttachement ? holder.status_prev4_h : holder.status_prev4; + if (attachment.getType().toLowerCase().equals("image") || attachment.getType().toLowerCase().equals("unknown")) + if (fullAttachement) holder.status_prev4_play_h.setVisibility(View.GONE); else holder.status_prev4_play.setVisibility(View.GONE); else { - if( attachment.getType().toLowerCase().equals("video") || attachment.getType().toLowerCase().equals("audio")) { + if (attachment.getType().toLowerCase().equals("video") || attachment.getType().toLowerCase().equals("audio")) { holder.status_prev4_play_h.setImageResource(R.drawable.ic_video_preview); holder.status_prev4_play.setImageResource(R.drawable.ic_video_preview); - }else if( attachment.getType().toLowerCase().equals("gifv")) { + } else if (attachment.getType().toLowerCase().equals("gifv")) { holder.status_prev4_play_h.setImageResource(R.drawable.ic_gif_preview); holder.status_prev4_play.setImageResource(R.drawable.ic_gif_preview); - }else if(attachment.getType().toLowerCase().equals("web")){ + } else if (attachment.getType().toLowerCase().equals("web")) { holder.status_prev1_play.setImageResource(R.drawable.ic_http); } if (fullAttachement) @@ -3658,18 +3647,18 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } String url = attachment.getPreview_url(); - if( url == null || url.trim().equals("") ) + if (url == null || url.trim().equals("")) url = attachment.getUrl(); - else if( attachment.getType().toLowerCase().equals("unknown")) + else if (attachment.getType().toLowerCase().equals("unknown")) url = attachment.getRemote_url(); - if( fullAttachement){ + if (fullAttachement) { imageView.setImageBitmap(null); - if( !url.trim().contains("missing.png") && !((Activity)context).isFinishing() ) { - if( !blur) { + if (!url.trim().contains("missing.png") && !((Activity) context).isFinishing()) { + if (!blur) { Glide.with(imageView.getContext()) .asBitmap() - .load( !attachment.getType().toLowerCase().equals("audio")?url:R.drawable.ic_audio_wave) + .load(!attachment.getType().toLowerCase().equals("audio") ? url : R.drawable.ic_audio_wave) .thumbnail(0.1f) .apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(10))) .into(new SimpleTarget() { @@ -3689,12 +3678,12 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct status.setMedia_height(container.getHeight()); } }); - }else{ + } else { Glide.with(imageView.getContext()) .asBitmap() - .load(!attachment.getType().toLowerCase().equals("audio")?url:R.drawable.ic_audio_wave) + .load(!attachment.getType().toLowerCase().equals("audio") ? url : R.drawable.ic_audio_wave) .thumbnail(0.1f) - .apply(new RequestOptions().transforms(new BlurTransformation(50,3), new RoundedCorners(10))) + .apply(new RequestOptions().transforms(new BlurTransformation(50, 3), new RoundedCorners(10))) .into(new SimpleTarget() { @Override public void onResourceReady(@NonNull Bitmap resource, Transition transition) { @@ -3713,35 +3702,35 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct }); } } - }else { + } else { if (!url.trim().contains("missing.png") && !((Activity) context).isFinishing()) { - if( !blur) { + if (!blur) { Glide.with(imageView.getContext()) - .load(!attachment.getType().toLowerCase().equals("audio")?url:R.drawable.ic_audio_wave) + .load(!attachment.getType().toLowerCase().equals("audio") ? url : R.drawable.ic_audio_wave) .thumbnail(0.1f) .apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(10))) .transition(DrawableTransitionOptions.withCrossFade()) .into(imageView); - }else{ + } else { Glide.with(imageView.getContext()) - .load(!attachment.getType().toLowerCase().equals("audio")?url:R.drawable.ic_audio_wave) + .load(!attachment.getType().toLowerCase().equals("audio") ? url : R.drawable.ic_audio_wave) .thumbnail(0.1f) - .apply(new RequestOptions().transforms(new BlurTransformation(50,3), new RoundedCorners(10))) + .apply(new RequestOptions().transforms(new BlurTransformation(50, 3), new RoundedCorners(10))) .transition(DrawableTransitionOptions.withCrossFade()) .into(imageView); } } } final int finalPosition = position; - if( attachment.getDescription() != null && !attachment.getDescription().equals("null")) + if (attachment.getDescription() != null && !attachment.getDescription().equals("null")) imageView.setContentDescription(attachment.getDescription()); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - if( status.isAttachmentShown()) { + if (status.isAttachmentShown()) { ArrayList attachmentArrayList; - if( status.getReblog() == null) + if (status.getReblog() == null) attachmentArrayList = status.getMedia_attachments(); else attachmentArrayList = status.getReblog().getMedia_attachments(); @@ -3755,7 +3744,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct intent.putExtras(b); context.startActivity(intent); } - }else{ + } else { status.setAttachmentShown(true); notifyStatusChanged(status); /* @@ -3781,7 +3770,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } }); boolean long_press_media = sharedpreferences.getBoolean(Helper.SET_LONG_PRESS_MEDIA, true); - if( long_press_media) { + if (long_press_media) { imageView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { @@ -3795,7 +3784,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct i++; position++; } - }else{ + } else { holder.status_horizontal_document_container.setVisibility(View.GONE); holder.status_document_container.setVisibility(View.GONE); holder.status_show_more.setVisibility(View.GONE); @@ -3803,12 +3792,12 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } - private int closePanels(){ + private int closePanels() { int position = -1; - if( statuses != null && statuses.size() > 0){ - for(Status status: statuses){ + if (statuses != null && statuses.size() > 0) { + for (Status status : statuses) { position++; - if( status.isCustomFeaturesDisplayed()) { + if (status.isCustomFeaturesDisplayed()) { status.setCustomFeaturesDisplayed(false); notifyItemChanged(position); break; @@ -3818,7 +3807,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct return position; } - private void timedMuteAction(Status status){ + private void timedMuteAction(Status status) { final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); int style; @@ -3831,7 +3820,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, style); LayoutInflater inflater = ((Activity) context).getLayoutInflater(); - View dialogView = inflater.inflate(R.layout.datetime_picker, new LinearLayout(context), false); + View dialogView = inflater.inflate(R.layout.datetime_picker, new LinearLayout(context), false); dialogBuilder.setView(dialogView); final AlertDialog alertDialog = dialogBuilder.create(); final DatePicker datePicker = dialogView.findViewById(R.id.date_picker); @@ -3914,11 +3903,11 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct alertDialog.show(); } - private void send_delete_statuses(String targetedId){ + private void send_delete_statuses(String targetedId) { //Delete in the current timeline List statusesToRemove = new ArrayList<>(); - for(Status status: statuses){ - if( status.getAccount().getId().equals(targetedId)) + for (Status status : statuses) { + if (status.getAccount().getId().equals(targetedId)) statusesToRemove.add(status); } statuses.removeAll(statusesToRemove); @@ -3930,7 +3919,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct intentBC.putExtras(b); } - private void scheduleBoost(Status status){ + private void scheduleBoost(Status status) { final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); @@ -3945,7 +3934,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct AlertDialog.Builder dialogBuilderBoost = new AlertDialog.Builder(context, style); LayoutInflater inflaterBoost = ((Activity) context).getLayoutInflater(); - View dialogViewBoost = inflaterBoost.inflate(R.layout.datetime_picker, new LinearLayout(context), false); + View dialogViewBoost = inflaterBoost.inflate(R.layout.datetime_picker, new LinearLayout(context), false); dialogBuilderBoost.setView(dialogViewBoost); final AlertDialog alertDialogBoost = dialogBuilderBoost.create(); @@ -4017,7 +4006,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct alertDialogBoost.show(); } - private void mention(Status status){ + private void mention(Status status) { // Get a handler that can be used to post to the main thread final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @@ -4050,7 +4039,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct }, 500); } - private void tootInformation(Status status){ + private void tootInformation(Status status) { Intent intent = new Intent(context, TootInfoActivity.class); Bundle b = new Bundle(); if (status.getReblog() != null) { @@ -4066,39 +4055,39 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct context.startActivity(intent); } - private void sendToot(String content_type){ + private void sendToot(String content_type) { - if(toot_content == null || toot_content.getText() == null){ - Toasty.error(context, context.getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + if (toot_content == null || toot_content.getText() == null) { + Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); return; } - if( toot_content.getText().toString().trim().length() == 0){ - Toasty.error(context, context.getString(R.string.toot_error_no_content),Toast.LENGTH_LONG).show(); + if (toot_content.getText().toString().trim().length() == 0) { + Toasty.error(context, context.getString(R.string.toot_error_no_content), Toast.LENGTH_LONG).show(); return; } SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); boolean split_toot = sharedpreferences.getBoolean(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS, false); final String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); - int split_toot_size = sharedpreferences.getInt(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS_SIZE+userId+instance, Helper.SPLIT_TOOT_SIZE); + int split_toot_size = sharedpreferences.getInt(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS_SIZE + userId + instance, Helper.SPLIT_TOOT_SIZE); String tootContent; - if( toot_cw_content.getText() != null && toot_cw_content.getText().toString().trim().length() > 0 ) + if (toot_cw_content.getText() != null && toot_cw_content.getText().toString().trim().length() > 0) split_toot_size -= toot_cw_content.getText().toString().trim().length(); - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || !split_toot || (TootActivity.countLength(social, toot_content, toot_cw_content) < split_toot_size)){ + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || !split_toot || (TootActivity.countLength(social, toot_content, toot_cw_content) < split_toot_size)) { tootContent = toot_content.getText().toString().trim(); - }else{ + } else { splitToot = Helper.splitToots(toot_content.getText().toString().trim(), split_toot_size); tootContent = splitToot.get(0); stepSpliToot = 1; } Status toot = new Status(); - if(content_type != null) + if (content_type != null) toot.setContentType(content_type); toot.setSensitive(false); final SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); Account account = new AccountDAO(context, db).getUniqAccount(userId, instance); - if( toot_cw_content.getText().toString().trim().length() > 0) + if (toot_cw_content.getText().toString().trim().length() > 0) toot.setSpoiler_text(toot_cw_content.getText().toString().trim()); toot.setVisibility(visibility); toot.setIn_reply_to_id(in_reply_to_status); @@ -4107,7 +4096,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } - private void bookmark(Status status){ + private void bookmark(Status status) { if (type != RetrieveFeedsAsyncTask.Type.CACHE_BOOKMARKS) { status.setBookmarked(!status.isBookmarked()); try { @@ -4144,7 +4133,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct @Override public void onRetrieveFeeds(APIResponse apiResponse) { - if( apiResponse.getStatuses() != null && apiResponse.getStatuses().size() > 0){ + if (apiResponse.getStatuses() != null && apiResponse.getStatuses().size() > 0) { SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); long id = new StatusStoredDAO(context, db).insertStatus(toot, apiResponse.getStatuses().get(0)); @@ -4159,12 +4148,11 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } - @Override public void onRetrieveAccount(Card card) { - if( conversationPosition < this.statuses.size() && card != null) + if (conversationPosition < this.statuses.size() && card != null) this.statuses.get(conversationPosition).setCard(card); - if( conversationPosition < this.statuses.size()) + if (conversationPosition < this.statuses.size()) statusListAdapter.notifyItemChanged(conversationPosition); } @@ -4173,55 +4161,55 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct public void onPostAction(int statusCode, API.StatusAction statusAction, String targetedId, Error error) { final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); - if( error != null){ - Toasty.error(context, error.getError(),Toast.LENGTH_LONG).show(); + if (error != null) { + Toasty.error(context, error.getError(), Toast.LENGTH_LONG).show(); return; } Helper.manageMessageStatusCode(context, statusCode, statusAction); //When muting or blocking an account, its status are removed from the list List statusesToRemove = new ArrayList<>(); - if( statusAction == API.StatusAction.MUTE || statusAction == API.StatusAction.BLOCK){ - for(Status status: statuses){ - if( status.getAccount().getId().equals(targetedId)) + if (statusAction == API.StatusAction.MUTE || statusAction == API.StatusAction.BLOCK) { + for (Status status : statuses) { + if (status.getAccount().getId().equals(targetedId)) statusesToRemove.add(status); } statuses.removeAll(statusesToRemove); statusListAdapter.notifyDataSetChanged(); - }else if( statusAction == API.StatusAction.MUTE_CONVERSATION ){ - for(Status status: statuses){ - if( status.getId().equals(targetedId)) { + } else if (statusAction == API.StatusAction.MUTE_CONVERSATION) { + for (Status status : statuses) { + if (status.getId().equals(targetedId)) { status.setMuted(true); notifyStatusChanged(status); break; } } - }else if( statusAction == API.StatusAction.UNMUTE_CONVERSATION ){ - for(Status status: statuses){ - if( status.getId().equals(targetedId)) { + } else if (statusAction == API.StatusAction.UNMUTE_CONVERSATION) { + for (Status status : statuses) { + if (status.getId().equals(targetedId)) { status.setMuted(false); notifyStatusChanged(status); break; } } - }else if( statusAction == API.StatusAction.UNSTATUS ){ + } else if (statusAction == API.StatusAction.UNSTATUS) { int position = 0; - for(Status status: statuses){ - if( status.getId().equals(targetedId)) { + for (Status status : statuses) { + if (status.getId().equals(targetedId)) { statuses.remove(status); statusListAdapter.notifyItemRemoved(position); SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); //Remove the status from cache also try { - new StatusCacheDAO(context, db).remove(StatusCacheDAO.ARCHIVE_CACHE,status); - }catch (Exception ignored){} + new StatusCacheDAO(context, db).remove(StatusCacheDAO.ARCHIVE_CACHE, status); + } catch (Exception ignored) { + } break; } position++; } - } - else if ( statusAction == API.StatusAction.PIN || statusAction == API.StatusAction.UNPIN ) { + } else if (statusAction == API.StatusAction.PIN || statusAction == API.StatusAction.UNPIN) { int position = 0; - for (Status status: statuses) { + for (Status status : statuses) { if (status.getId().equals(targetedId)) { if (statusAction == API.StatusAction.PIN) status.setPinned(true); @@ -4233,10 +4221,10 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct position++; } } - if( statusAction == API.StatusAction.PEERTUBEDELETECOMMENT){ + if (statusAction == API.StatusAction.PEERTUBEDELETECOMMENT) { int position = 0; - for(Status status: statuses){ - if( status.getId().equals(targetedId)) { + for (Status status : statuses) { + if (status.getId().equals(targetedId)) { statuses.remove(status); statusListAdapter.notifyItemRemoved(position); break; @@ -4246,7 +4234,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } } - public void notifyStatusChanged(Status status){ + public void notifyStatusChanged(Status status) { for (int i = 0; i < statusListAdapter.getItemCount(); i++) { //noinspection ConstantConditions if (statusListAdapter.getItemAt(i) != null && statusListAdapter.getItemAt(i).getId().equals(status.getId())) { @@ -4262,14 +4250,15 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } }); }*/ - } catch (Exception ignored) {} + } catch (Exception ignored) { + } break; } } } - public void notifyStatusWithActionChanged(Status status){ - if( status == null) + public void notifyStatusWithActionChanged(Status status) { + if (status == null) return; for (int i = 0; i < statusListAdapter.getItemCount(); i++) { //noinspection ConstantConditions @@ -4286,7 +4275,8 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } }); }*/ - } catch (Exception ignored) {} + } catch (Exception ignored) { + } break; } } @@ -4295,10 +4285,10 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct @Override public void onRetrieveImage(Status status, boolean fromTranslation) { - if( status != null) { - if( !fromTranslation) { + if (status != null) { + if (!fromTranslation) { status.setImageFound(true); - }else { + } else { status.setImageFound(true); } notifyStatusChanged(status); @@ -4308,11 +4298,11 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct @Override public void onRetrieveEmoji(Status status, boolean fromTranslation) { - if( status != null) { - if( !fromTranslation) { - status.setEmojiFound(true); - }else { - status.setEmojiTranslateFound(true); + if (status != null) { + if (!fromTranslation) { + status.setEmojiFound(true); + } else { + status.setEmojiTranslateFound(true); } notifyStatusChanged(status); } @@ -4324,9 +4314,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } - - - private void translateToot(Status status){ + private void translateToot(Status status) { //Manages translations SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int trans = sharedpreferences.getInt(Helper.SET_TRANSLATOR, Helper.TRANS_YANDEX); @@ -4334,86 +4322,87 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct String api_key = null; - - if( trans == Helper.TRANS_YANDEX) { + if (trans == Helper.TRANS_YANDEX) { et = MyTransL.translatorEngine.YANDEX; - }else if( trans == Helper.TRANS_DEEPL) { + } else if (trans == Helper.TRANS_DEEPL) { et = MyTransL.translatorEngine.DEEPL; } final MyTransL myTransL = MyTransL.getInstance(et); myTransL.setObfuscation(true); - if( trans == Helper.TRANS_YANDEX) { + if (trans == Helper.TRANS_YANDEX) { api_key = sharedpreferences.getString(Helper.SET_YANDEX_API_KEY, Helper.YANDEX_KEY); myTransL.setYandexAPIKey(api_key); - }else if( trans == Helper.TRANS_DEEPL) { + } else if (trans == Helper.TRANS_DEEPL) { api_key = sharedpreferences.getString(Helper.SET_DEEPL_API_KEY, ""); myTransL.setDeeplAPIKey(api_key); } - if( !status.isTranslated() ){ + if (!status.isTranslated()) { String statusToTranslate; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) - statusToTranslate = Html.fromHtml(status.getReblog() != null ?status.getReblog().getContent():status.getContent(), Html.FROM_HTML_MODE_LEGACY).toString(); + statusToTranslate = Html.fromHtml(status.getReblog() != null ? status.getReblog().getContent() : status.getContent(), Html.FROM_HTML_MODE_LEGACY).toString(); else //noinspection deprecation - statusToTranslate = Html.fromHtml(status.getReblog() != null ?status.getReblog().getContent():status.getContent()).toString(); + statusToTranslate = Html.fromHtml(status.getReblog() != null ? status.getReblog().getContent() : status.getContent()).toString(); //TODO: removes the replaceAll once fixed with the lib myTransL.translate(statusToTranslate, myTransL.getLocale(), new Results() { @Override public void onSuccess(Translate translate) { - if( translate.getTranslatedContent() != null) { + if (translate.getTranslatedContent() != null) { status.setTranslated(true); status.setTranslationShown(true); status.setContentTranslated(translate.getTranslatedContent()); - Status.transformTranslation(context, status); + Status.transformTranslation(context, status); Status.makeEmojisTranslation(context, StatusListAdapter.this, status); notifyStatusChanged(status); - }else { + } else { Toasty.error(context, context.getString(R.string.toast_error_translate), Toast.LENGTH_LONG).show(); } } + @Override public void onFail(HttpsConnectionException e) { e.printStackTrace(); Toasty.error(context, context.getString(R.string.toast_error_translate), Toast.LENGTH_LONG).show(); } }); - }else { + } else { status.setTranslationShown(!status.isTranslationShown()); notifyStatusChanged(status); } } - public void setConversationPosition(int position){ + public void setConversationPosition(int position) { this.conversationPosition = position; } - public void storeToot(){ + public void storeToot() { //Nothing to store here.... if (tootReply == null || (toot_content.getText().toString().trim().length() == 0 && toot_cw_content.getText().toString().trim().length() == 0)) return; Status toot = new Status(); - if( toot_cw_content.getText().toString().trim().length() > 0) + if (toot_cw_content.getText().toString().trim().length() > 0) toot.setSpoiler_text(toot_cw_content.getText().toString().trim()); toot.setVisibility(visibility); toot.setContent(toot_content.getText().toString().trim()); toot.setIn_reply_to_id(tootReply.getId()); SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - try{ - if(currentToId == -1) { + try { + if (currentToId == -1) { currentToId = new StatusStoredDAO(context, db).insertStatus(toot, tootReply); - }else{ + } else { StoredStatus storedStatus = new StatusStoredDAO(context, db).getStatus(currentToId); - if( storedStatus != null ){ + if (storedStatus != null) { new StatusStoredDAO(context, db).updateStatus(currentToId, toot); - }else { //Might have been deleted, so it needs insertion + } else { //Might have been deleted, so it needs insertion new StatusStoredDAO(context, db).insertStatus(toot, tootReply); } } - }catch (Exception ignored){ } + } catch (Exception ignored) { + } } } \ No newline at end of file diff --git a/app/src/main/java/app/fedilab/android/drawers/StatusReportAdapter.java b/app/src/main/java/app/fedilab/android/drawers/StatusReportAdapter.java index 5b9c644ad..5cb54b60d 100644 --- a/app/src/main/java/app/fedilab/android/drawers/StatusReportAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/StatusReportAdapter.java @@ -30,7 +30,7 @@ import java.util.List; import app.fedilab.android.R; -public class StatusReportAdapter extends RecyclerView.Adapter { +public class StatusReportAdapter extends RecyclerView.Adapter { private List mData; private LayoutInflater mInflater; @@ -70,7 +70,6 @@ public class StatusReportAdapter extends RecyclerView.Adapter suggestions; - public SuggestionsAdapter(List suggestions){ + public SuggestionsAdapter(List suggestions) { this.suggestions = suggestions; } public Suggestion getItem(int position) { - return suggestions.get(position); + return suggestions.get(position); } @NonNull @@ -55,9 +58,10 @@ public class SuggestionsAdapter extends RecyclerView.Adapter { return new ViewHolder(layoutInflater.inflate(R.layout.drawer_suggestions, parent, false)); } - class ViewHolder extends RecyclerView.ViewHolder{ + class ViewHolder extends RecyclerView.ViewHolder { private TextView suggestion_content; private ImageView suggestion_image; + public ViewHolder(@NonNull View itemView) { super(itemView); suggestion_content = itemView.findViewById(R.id.suggestion_content); @@ -70,10 +74,10 @@ public class SuggestionsAdapter extends RecyclerView.Adapter { final ViewHolder holder = (ViewHolder) viewHolder; final Suggestion suggestion = getItem(i); - if( suggestion.getType() == Suggestion.suggestionType.TAG) { + if (suggestion.getType() == Suggestion.suggestionType.TAG) { holder.suggestion_content.setText(String.format("#%s", suggestion.getContent())); holder.suggestion_image.setVisibility(View.GONE); - }else{ + } else { holder.suggestion_content.setText(suggestion.getContent()); Helper.loadGiF(context, suggestion.getImageUrl(), holder.suggestion_image); } @@ -90,5 +94,4 @@ public class SuggestionsAdapter extends RecyclerView.Adapter { } - } \ No newline at end of file diff --git a/app/src/main/java/app/fedilab/android/drawers/TagsEditAdapter.java b/app/src/main/java/app/fedilab/android/drawers/TagsEditAdapter.java index db667cf56..15179dd53 100644 --- a/app/src/main/java/app/fedilab/android/drawers/TagsEditAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/TagsEditAdapter.java @@ -17,8 +17,10 @@ package app.fedilab.android.drawers; import android.content.Context; import android.database.sqlite.SQLiteDatabase; + import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -38,13 +40,13 @@ import app.fedilab.android.R; * Created by Thomas on 01/12/2018. * Adapter for tags when editing */ -public class TagsEditAdapter extends RecyclerView.Adapter { +public class TagsEditAdapter extends RecyclerView.Adapter { private Context context; private List tags; private TagsEditAdapter tagsEditAdapter; - public TagsEditAdapter(List tags){ + public TagsEditAdapter(List tags) { this.tags = tags; tagsEditAdapter = this; @@ -68,10 +70,10 @@ public class TagsEditAdapter extends RecyclerView.Adapter { holder.save_tag.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - if( holder.tag_name.getText() != null && holder.tag_name.getText().toString().trim().replaceAll("\\#","").length() > 0) { - String tagToInsert = holder.tag_name.getText().toString().trim().replaceAll("\\#",""); + if (holder.tag_name.getText() != null && holder.tag_name.getText().toString().trim().replaceAll("\\#", "").length() > 0) { + String tagToInsert = holder.tag_name.getText().toString().trim().replaceAll("\\#", ""); boolean isPresent = new TagsCacheDAO(context, db).isPresent(tagToInsert); - if( isPresent) + if (isPresent) Toasty.warning(context, context.getString(R.string.tags_already_stored), Toast.LENGTH_LONG).show(); else { new TagsCacheDAO(context, db).update(tag[0], tagToInsert); @@ -105,7 +107,7 @@ public class TagsEditAdapter extends RecyclerView.Adapter { } - class ViewHolder extends RecyclerView.ViewHolder{ + class ViewHolder extends RecyclerView.ViewHolder { TextView tag_name; ImageButton save_tag, delete_tag; diff --git a/app/src/main/java/app/fedilab/android/drawers/TagsSearchAdapter.java b/app/src/main/java/app/fedilab/android/drawers/TagsSearchAdapter.java index 2fe7f8a72..29b2bd872 100644 --- a/app/src/main/java/app/fedilab/android/drawers/TagsSearchAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/TagsSearchAdapter.java @@ -16,7 +16,9 @@ package app.fedilab.android.drawers; import android.content.Context; + import androidx.annotation.NonNull; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -37,10 +39,10 @@ import app.fedilab.android.R; */ public class TagsSearchAdapter extends ArrayAdapter implements Filterable { - private List tags, tempTags, suggestions ; + private List tags, tempTags, suggestions; private LayoutInflater layoutInflater; - public TagsSearchAdapter(Context context, List tags){ + public TagsSearchAdapter(Context context, List tags) { super(context, android.R.layout.simple_list_item_1, tags); this.tags = tags; this.tempTags = new ArrayList<>(tags); @@ -117,7 +119,7 @@ public class TagsSearchAdapter extends ArrayAdapter implements Filterabl clear(); addAll(c); notifyDataSetChanged(); - } else{ + } else { clear(); notifyDataSetChanged(); } diff --git a/app/src/main/java/app/fedilab/android/drawers/WhoToFollowAccountsAdapter.java b/app/src/main/java/app/fedilab/android/drawers/WhoToFollowAccountsAdapter.java index d39bd0160..623ab121f 100644 --- a/app/src/main/java/app/fedilab/android/drawers/WhoToFollowAccountsAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/WhoToFollowAccountsAdapter.java @@ -16,13 +16,16 @@ package app.fedilab.android.drawers; import android.content.Context; + import com.google.android.material.floatingactionbutton.FloatingActionButton; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.TextView; + import java.util.List; import app.fedilab.android.client.Entities.Account; @@ -40,7 +43,7 @@ public class WhoToFollowAccountsAdapter extends BaseAdapter { private List lists; private Context context; - public WhoToFollowAccountsAdapter(List lists){ + public WhoToFollowAccountsAdapter(List lists) { this.lists = lists; } @@ -93,7 +96,7 @@ public class WhoToFollowAccountsAdapter extends BaseAdapter { public void onClick(View v) { Account account = new Account(); String[] val = trunkAccount.getAcct().split("@"); - if( val.length > 1){ + if (val.length > 1) { account.setAcct(val[0]); account.setInstance(val[1]); CrossActions.doCrossProfile(context, account); diff --git a/app/src/main/java/app/fedilab/android/drawers/WhoToFollowAdapter.java b/app/src/main/java/app/fedilab/android/drawers/WhoToFollowAdapter.java index ff8f0bad7..5307efa93 100644 --- a/app/src/main/java/app/fedilab/android/drawers/WhoToFollowAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/WhoToFollowAdapter.java @@ -20,13 +20,16 @@ import android.content.Intent; import android.content.SharedPreferences; import android.graphics.drawable.Drawable; import android.os.Bundle; + import androidx.core.content.ContextCompat; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.TextView; + import java.util.List; import app.fedilab.android.helper.Helper; @@ -46,7 +49,7 @@ public class WhoToFollowAdapter extends BaseAdapter { private LayoutInflater layoutInflater; private Context context; - public WhoToFollowAdapter(List lists){ + public WhoToFollowAdapter(List lists) { this.lists = lists; } @@ -85,21 +88,21 @@ public class WhoToFollowAdapter extends BaseAdapter { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if( theme == Helper.THEME_LIGHT){ + if (theme == Helper.THEME_LIGHT) { holder.search_container.setBackgroundResource(R.color.mastodonC3__); - Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right,R.color.black); - }else if(theme == Helper.THEME_DARK){ + Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right, R.color.black); + } else if (theme == Helper.THEME_DARK) { holder.search_container.setBackgroundResource(R.color.mastodonC1_); - Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right,R.color.dark_text); - }else if(theme == Helper.THEME_BLACK) { + Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right, R.color.dark_text); + } else if (theme == Helper.THEME_BLACK) { holder.search_container.setBackgroundResource(R.color.black_2); - Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right,R.color.dark_text); + Helper.changeDrawableColor(context, R.drawable.ic_keyboard_arrow_right, R.color.dark_text); } Drawable next = ContextCompat.getDrawable(context, R.drawable.ic_keyboard_arrow_right); holder.search_title.setText(item); assert next != null; final float scale = context.getResources().getDisplayMetrics().density; - next.setBounds(0,0,(int) (30 * scale + 0.5f),(int) (30 * scale + 0.5f)); + next.setBounds(0, 0, (int) (30 * scale + 0.5f), (int) (30 * scale + 0.5f)); holder.search_title.setCompoundDrawables(null, null, next, null); holder.search_container.setOnClickListener(new View.OnClickListener() { diff --git a/app/src/main/java/app/fedilab/android/filelister/FileListerAdapter.java b/app/src/main/java/app/fedilab/android/filelister/FileListerAdapter.java index a0407b4ca..44e40d085 100644 --- a/app/src/main/java/app/fedilab/android/filelister/FileListerAdapter.java +++ b/app/src/main/java/app/fedilab/android/filelister/FileListerAdapter.java @@ -189,7 +189,7 @@ class FileListerAdapter extends RecyclerView.Adapter= android.os.Build.VERSION_CODES.LOLLIPOP) { docUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, DocumentsContract.getTreeDocumentId(treeUri)); } - try{ + try { String path = getPath(context, docUri); - if( path == null ) + if (path == null) path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(); final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(Helper.SET_FOLDER_RECORD, path); editor.apply(); set_folder.setText(path); - }catch (Exception e){ - Toasty.error(context, context.getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + } catch (Exception e) { + Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); } } - if (requestCode == ACTIVITY_CHOOSE_SOUND){ - try{ + if (requestCode == ACTIVITY_CHOOSE_SOUND) { + try { Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI); final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putString(Helper.SET_NOTIF_SOUND, uri.toString()); + editor.putString(Helper.SET_NOTIF_SOUND, uri.toString()); editor.apply(); - }catch (Exception e){ - Toasty.error(context, context.getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + } catch (Exception e) { + Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); } } } @@ -216,23 +216,22 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable Bundle bundle = this.getArguments(); if (bundle != null) { - type = (type)bundle.getSerializable("type"); + type = (type) bundle.getSerializable("type"); } - SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: containerFrame.setBackgroundColor(ContextCompat.getColor(context, R.color.white)); break; @@ -253,22 +252,22 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable LinearLayout settings_battery = rootView.findViewById(R.id.settings_battery); String title = ""; - if(type == null || type.equals(TIMELINES)){ + if (type == null || type.equals(TIMELINES)) { settings_timeline.setVisibility(View.VISIBLE); title = context.getString(R.string.timelines); - }else if( type == NOTIFICATIONS){ + } else if (type == NOTIFICATIONS) { settings_notifications.setVisibility(View.VISIBLE); title = context.getString(R.string.notifications); - }else if( type == ADMIN){ + } else if (type == ADMIN) { settings_admin.setVisibility(View.VISIBLE); title = context.getString(R.string.administration); - }else if(type == INTERFACE){ + } else if (type == INTERFACE) { settings_interface.setVisibility(View.VISIBLE); title = context.getString(R.string.u_interface); - }else if(type == BATTERY){ + } else if (type == BATTERY) { title = context.getString(R.string.battery); settings_battery.setVisibility(View.VISIBLE); - }else if(type == COMPOSE){ + } else if (type == COMPOSE) { settings_compose.setVisibility(View.VISIBLE); title = context.getString(R.string.compose); } @@ -312,14 +311,14 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(context)); - boolean auto_backup = sharedpreferences.getBoolean(Helper.SET_AUTO_BACKUP_STATUSES+userId+instance, false); + boolean auto_backup = sharedpreferences.getBoolean(Helper.SET_AUTO_BACKUP_STATUSES + userId + instance, false); final CheckBox set_auto_backup = rootView.findViewById(R.id.set_auto_backup); set_auto_backup.setChecked(auto_backup); set_auto_backup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_AUTO_BACKUP_STATUSES+userId+instance, set_auto_backup.isChecked()); + editor.putBoolean(Helper.SET_AUTO_BACKUP_STATUSES + userId + instance, set_auto_backup.isChecked()); editor.apply(); } }); @@ -337,14 +336,14 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable } }); - boolean auto_backup_notifications = sharedpreferences.getBoolean(Helper.SET_AUTO_BACKUP_NOTIFICATIONS+userId+instance, false); + boolean auto_backup_notifications = sharedpreferences.getBoolean(Helper.SET_AUTO_BACKUP_NOTIFICATIONS + userId + instance, false); final CheckBox set_auto_backup_notifications = rootView.findViewById(R.id.set_auto_backup_notifications); set_auto_backup_notifications.setChecked(auto_backup_notifications); set_auto_backup_notifications.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_AUTO_BACKUP_NOTIFICATIONS+userId+instance, set_auto_backup_notifications.isChecked()); + editor.putBoolean(Helper.SET_AUTO_BACKUP_NOTIFICATIONS + userId + instance, set_auto_backup_notifications.isChecked()); editor.apply(); } }); @@ -354,12 +353,12 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable TagsEditText set_featured_tags = rootView.findViewById(R.id.set_featured_tags); - if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON){ + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { Set featuredTagsSet = sharedpreferences.getStringSet(Helper.SET_FEATURED_TAGS, null); List tags = new ArrayList<>(); - if( featuredTagsSet != null){ + if (featuredTagsSet != null) { tags = new ArrayList<>(featuredTagsSet); } String[] tagsString = tags.toArray(new String[tags.size()]); @@ -379,13 +378,11 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable } }); - }else{ + } else { set_featured_tags.setVisibility(View.GONE); } - - Button update_tracking_domains = rootView.findViewById(R.id.update_tracking_domains); update_tracking_domains.setOnClickListener(v -> { new DownloadTrackingDomainsAsyncTask(getActivity().getApplicationContext(), update_tracking_domains).execute(); @@ -394,7 +391,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable //Manage download of attachments RadioGroup radioGroup = rootView.findViewById(R.id.set_attachment_group); int attachmentAction = sharedpreferences.getInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ALWAYS); - switch (attachmentAction){ + switch (attachmentAction) { case Helper.ATTACHMENT_ALWAYS: radioGroup.check(R.id.set_attachment_always); break; @@ -408,7 +405,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { - switch(checkedId) { + switch (checkedId) { case R.id.set_attachment_always: SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ALWAYS); @@ -429,7 +426,6 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable }); - int videoMode = sharedpreferences.getInt(Helper.SET_VIDEO_MODE, Helper.VIDEO_MODE_DIRECT); @@ -441,13 +437,13 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable if (videoMode == Helper.VIDEO_MODE_TORRENT) videoMode = Helper.VIDEO_MODE_DIRECT; int positionVideoMode = 0; - if( videoMode == Helper.VIDEO_MODE_DIRECT) + if (videoMode == Helper.VIDEO_MODE_DIRECT) positionVideoMode = 1; video_mode_spinner.setSelection(positionVideoMode); video_mode_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { - if( count5 > 0 ) { + if (count5 > 0) { SharedPreferences.Editor editor = sharedpreferences.edit(); switch (position) { /*case 0: @@ -466,6 +462,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable } count5++; } + @Override public void onNothingSelected(AdapterView parent) { @@ -513,9 +510,9 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable editor.putBoolean(Helper.SET_DISPLAY_ADMIN_MENU + userId + instance, set_display_admin_menu.isChecked()); editor.apply(); Bundle b = new Bundle(); - if( set_display_admin_menu.isChecked()){ + if (set_display_admin_menu.isChecked()) { b.putString("menu", "show_admin"); - }else{ + } else { b.putString("menu", "hide_admin"); } Intent intentBC = new Intent(Helper.RECEIVE_HIDE_ITEM); @@ -595,12 +592,12 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable SharedPreferences.Editor editor = sharedpreferences.edit(); int translatore = sharedpreferences.getInt(Helper.SET_TRANSLATOR, Helper.TRANS_YANDEX); String store = null; - if( translatore == Helper.TRANS_YANDEX) + if (translatore == Helper.TRANS_YANDEX) store = Helper.SET_YANDEX_API_KEY; - else if( translatore == Helper.TRANS_DEEPL) + else if (translatore == Helper.TRANS_DEEPL) store = Helper.SET_DEEPL_API_KEY; - if( store != null) - if( s != null && s.length() > 0) + if (store != null) + if (s != null && s.length() > 0) editor.putString(store, s.toString().trim()); else editor.putString(store, null); @@ -681,8 +678,14 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable max_times_bar.setProgress(upload_img_max_retry_times); max_times_value.setText(String.valueOf(upload_img_max_retry_times)); max_times_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override public void onStartTrackingTouch(SeekBar seekBar) {} - @Override public void onStopTrackingTouch(SeekBar seekBar) {} + @Override + public void onStartTrackingTouch(SeekBar seekBar) { + } + + @Override + public void onStopTrackingTouch(SeekBar seekBar) { + } + @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { max_times_value.setText(String.valueOf(progress)); @@ -707,7 +710,6 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable set_remember_position_text.setOnClickListener(v -> set_remember_position.performClick()); - boolean hide_delete_notification_on_tab = sharedpreferences.getBoolean(Helper.SET_HIDE_DELETE_BUTTON_ON_TAB, false); final CheckBox set_hide_delete_notification_on_tab = rootView.findViewById(R.id.set_hide_delete_notification_on_tab); set_hide_delete_notification_on_tab.setChecked(hide_delete_notification_on_tab); @@ -718,10 +720,10 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putBoolean(Helper.SET_HIDE_DELETE_BUTTON_ON_TAB, set_hide_delete_notification_on_tab.isChecked()); editor.apply(); - if( getActivity() != null) + if (getActivity() != null) getActivity().recreate(); Intent intent = new Intent(context, MainActivity.class); - if(getActivity() != null) + if (getActivity() != null) getActivity().finish(); startActivity(intent); } @@ -744,7 +746,6 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable set_blur_sensitive_text.setOnClickListener(v -> set_blur_sensitive.performClick()); - TextView set_invidious_host = rootView.findViewById(R.id.set_invidious_host); @@ -758,21 +759,21 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putBoolean(Helper.SET_INVIDIOUS, set_invidious.isChecked()); editor.apply(); - if( set_invidious.isChecked() ){ + if (set_invidious.isChecked()) { set_invidious_host.setVisibility(View.VISIBLE); - }else{ + } else { set_invidious_host.setVisibility(View.GONE); } } }); - if( invidious ){ + if (invidious) { set_invidious_host.setVisibility(View.VISIBLE); - }else{ + } else { set_invidious_host.setVisibility(View.GONE); } String invidiousHost = sharedpreferences.getString(Helper.SET_INVIDIOUS_HOST, null); - if( invidiousHost != null){ + if (invidiousHost != null) { set_invidious_host.setText(invidiousHost); } set_invidious_host.addTextChangedListener(new TextWatcher() { @@ -780,10 +781,12 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable public void beforeTextChanged(CharSequence s, int start, int count, int after) { } + @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } + @Override public void afterTextChanged(Editable s) { SharedPreferences.Editor editor = sharedpreferences.edit(); @@ -819,9 +822,9 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable editor.putBoolean(Helper.SET_DISPLAY_TIMELINE_IN_LIST, set_display_timeline_in_list.isChecked()); editor.apply(); Bundle b = new Bundle(); - if( set_display_timeline_in_list.isChecked()){ + if (set_display_timeline_in_list.isChecked()) { b.putString("menu", "show_list_button"); - }else{ + } else { b.putString("menu", "hide_list_button"); } Intent intentBC = new Intent(Helper.RECEIVE_HIDE_ITEM); @@ -857,7 +860,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putBoolean(Helper.SET_SEND_CRASH_REPORTS, set_enable_crash_report.isChecked()); editor.apply(); - if( getActivity() != null) + if (getActivity() != null) getActivity().recreate(); } }); @@ -872,9 +875,13 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable set_truncate_toots.setText(String.valueOf(truncate_toots_size)); set_truncate_size.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override - public void onStopTrackingTouch(SeekBar seekBar) {} + public void onStopTrackingTouch(SeekBar seekBar) { + } + @Override - public void onStartTrackingTouch(SeekBar seekBar) {} + public void onStartTrackingTouch(SeekBar seekBar) { + } + @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { set_truncate_toots.setText(String.valueOf(progress)); @@ -885,7 +892,6 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable }); - boolean new_badge = sharedpreferences.getBoolean(Helper.SET_DISPLAY_NEW_BADGE, true); final CheckBox set_new_badge = rootView.findViewById(R.id.set_display_new_badge); set_new_badge.setChecked(new_badge); @@ -973,17 +979,17 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable boolean compact_mode = sharedpreferences.getBoolean(Helper.SET_COMPACT_MODE, false); boolean console_mode = sharedpreferences.getBoolean(Helper.SET_CONSOLE_MODE, false); RadioGroup set_mode = rootView.findViewById(R.id.set_mode); - if( compact_mode){ + if (compact_mode) { set_mode.check(R.id.set_compact_mode); - }else if(console_mode){ + } else if (console_mode) { set_mode.check(R.id.set_console_mode); - }else { + } else { set_mode.check(R.id.set_normal_mode); } set_mode.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { - switch(checkedId) { + switch (checkedId) { case R.id.set_compact_mode: SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putBoolean(Helper.SET_COMPACT_MODE, true); @@ -1038,7 +1044,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable boolean custom_sharing = sharedpreferences.getBoolean(Helper.SET_CUSTOM_SHARING, false); final CheckBox set_custom_sharing = rootView.findViewById(R.id.set_custom_sharing); set_custom_sharing.setChecked(custom_sharing); - if( custom_sharing) + if (custom_sharing) edit_custom_sharing_url.setVisibility(View.VISIBLE); else edit_custom_sharing_url.setVisibility(View.GONE); @@ -1048,7 +1054,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putBoolean(Helper.SET_CUSTOM_SHARING, set_custom_sharing.isChecked()); editor.apply(); - if( set_custom_sharing.isChecked()) + if (set_custom_sharing.isChecked()) edit_custom_sharing_url.setVisibility(View.VISIBLE); else edit_custom_sharing_url.setVisibility(View.GONE); @@ -1070,7 +1076,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable } }); - String custom_sharing_url = sharedpreferences.getString(Helper.SET_CUSTOM_SHARING_URL,""); + String custom_sharing_url = sharedpreferences.getString(Helper.SET_CUSTOM_SHARING_URL, ""); if (custom_sharing_url.equals("")) { custom_sharing_url = "http://cs.example.net/add?token=umVe1zurZk47ihElSOQcBG05KUSA2v-GSet4_fFnJ4M&url=${url}&title=${title}&source=${source}&id=${id}&description=${description}&keywords=${keywords}&creator=${creator}&thumbnailurl=${thumbnailurl}"; } @@ -1105,7 +1111,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putBoolean(Helper.SET_DISABLE_GIF, set_disable_gif.isChecked()); editor.apply(); - if( getActivity() != null) + if (getActivity() != null) getActivity().recreate(); } }); @@ -1133,16 +1139,18 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable editor.putBoolean(Helper.SET_LIVE_NOTIFICATIONS, set_live_notif.isChecked()); editor.putBoolean(Helper.SHOULD_CONTINUE_STREAMING, set_live_notif.isChecked()); editor.apply(); - if( set_live_notif.isChecked() ){ + if (set_live_notif.isChecked()) { try { Intent streamingIntent = new Intent(context, LiveNotificationService.class); context.startService(streamingIntent); - }catch (Exception ignored){ignored.printStackTrace();} - }else{ + } catch (Exception ignored) { + ignored.printStackTrace(); + } + } else { context.sendBroadcast(new Intent(context, StopLiveNotificationReceiver.class)); if (Build.VERSION.SDK_INT >= 26) { NotificationManager notif = ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)); - if( notif != null) { + if (notif != null) { notif.deleteNotificationChannel(LiveNotificationService.CHANNEL_ID); } } @@ -1204,16 +1212,16 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable final CheckBox set_embedded_browser = rootView.findViewById(R.id.set_embedded_browser); final LinearLayout set_javascript_container = rootView.findViewById(R.id.set_javascript_container); - final CheckBox set_custom_tabs = rootView.findViewById(R.id.set_custom_tabs); - final LinearLayout custom_tabs_container = rootView.findViewById(R.id.custom_tabs_container); + final CheckBox set_custom_tabs = rootView.findViewById(R.id.set_custom_tabs); + final LinearLayout custom_tabs_container = rootView.findViewById(R.id.custom_tabs_container); final SwitchCompat set_javascript = rootView.findViewById(R.id.set_javascript); boolean javascript = sharedpreferences.getBoolean(Helper.SET_JAVASCRIPT, true); boolean embedded_browser = sharedpreferences.getBoolean(Helper.SET_EMBEDDED_BROWSER, true); boolean custom_tabs = sharedpreferences.getBoolean(Helper.SET_CUSTOM_TABS, true); - if( !embedded_browser){ + if (!embedded_browser) { set_javascript_container.setVisibility(View.GONE); custom_tabs_container.setVisibility(View.VISIBLE); - }else{ + } else { set_javascript_container.setVisibility(View.VISIBLE); custom_tabs_container.setVisibility(View.GONE); } @@ -1224,10 +1232,10 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putBoolean(Helper.SET_EMBEDDED_BROWSER, set_embedded_browser.isChecked()); editor.apply(); - if( !set_embedded_browser.isChecked()){ + if (!set_embedded_browser.isChecked()) { set_javascript_container.setVisibility(View.GONE); custom_tabs_container.setVisibility(View.VISIBLE); - }else{ + } else { set_javascript_container.setVisibility(View.VISIBLE); custom_tabs_container.setVisibility(View.GONE); } @@ -1271,7 +1279,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable }); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { set_cookies_container.setVisibility(View.VISIBLE); - }else { + } else { set_cookies_container.setVisibility(View.GONE); } final String targeted_folder = sharedpreferences.getString(Helper.SET_FOLDER_RECORD, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()); @@ -1291,14 +1299,14 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable LinearLayout file_chooser = rootView.findViewById(R.id.file_chooser); file_chooser.setVisibility(View.GONE); }*/ - set_folder.setOnClickListener(view ->{ + set_folder.setOnClickListener(view -> { FileListerDialog fileListerDialog = FileListerDialog.createFileListerDialog(context, style); fileListerDialog.setDefaultDir(targeted_folder); fileListerDialog.setFileFilter(FileListerDialog.FILE_FILTER.DIRECTORY_ONLY); fileListerDialog.setOnFileSelectedListener(new OnFileSelectedListener() { @Override public void onFileSelected(File file, String path) { - if( path == null ) + if (path == null) path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(); final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedpreferences.edit(); @@ -1316,7 +1324,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable set_night_mode.setAdapter(adapterTheme); int positionSpinnerTheme; - switch (sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK)){ + switch (sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK)) { case Helper.THEME_DARK: positionSpinnerTheme = 0; break; @@ -1333,7 +1341,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable set_night_mode.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { - if( count1 > 0 ) { + if (count1 > 0) { SharedPreferences.Editor editor = sharedpreferences.edit(); switch (position) { @@ -1359,6 +1367,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable } count1++; } + @Override public void onNothingSelected(AdapterView parent) { @@ -1367,17 +1376,22 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable SeekBar toot_per_page = rootView.findViewById(R.id.set_toot_per_page); - final TextView set_toot_per_page_count = rootView.findViewById(R.id.set_toot_per_page_count);; + final TextView set_toot_per_page_count = rootView.findViewById(R.id.set_toot_per_page_count); + ; toot_per_page.setMax(20); int tootperpage = sharedpreferences.getInt(Helper.SET_TOOT_PER_PAGE, Helper.TOOTS_PER_PAGE); - toot_per_page.setProgress(tootperpage-Helper.TOOTS_PER_PAGE); + toot_per_page.setProgress(tootperpage - Helper.TOOTS_PER_PAGE); set_toot_per_page_count.setText(String.valueOf(tootperpage)); toot_per_page.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override - public void onStopTrackingTouch(SeekBar seekBar) {} + public void onStopTrackingTouch(SeekBar seekBar) { + } + @Override - public void onStartTrackingTouch(SeekBar seekBar) {} + public void onStartTrackingTouch(SeekBar seekBar) { + } + @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { @@ -1404,9 +1418,13 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable nsfwTimeoutSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override - public void onStopTrackingTouch(SeekBar seekBar) {} + public void onStopTrackingTouch(SeekBar seekBar) { + } + @Override - public void onStartTrackingTouch(SeekBar seekBar) {} + public void onStartTrackingTouch(SeekBar seekBar) { + } + @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { @@ -1419,22 +1437,19 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable }); - - - LinearLayout toot_visibility_container = rootView.findViewById(R.id.toot_visibility_container); SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); final Account account = new AccountDAO(context, db).getUniqAccount(userId, instance); final ImageView set_toot_visibility = rootView.findViewById(R.id.set_toot_visibility); - if( theme == Helper.THEME_DARK){ + if (theme == Helper.THEME_DARK) { Helper.changeDrawableColor(context, set_toot_visibility, R.color.dark_text); - }else { + } else { Helper.changeDrawableColor(context, set_toot_visibility, R.color.white); } //Only displayed for non locked accounts - if (account != null ) { - String defaultVisibility = account.isLocked()?"private":"public"; + if (account != null) { + String defaultVisibility = account.isLocked() ? "private" : "public"; String tootVisibility = sharedpreferences.getString(Helper.SET_TOOT_VISIBILITY + "@" + account.getAcct() + "@" + account.getInstance(), defaultVisibility); switch (tootVisibility) { case "public": @@ -1450,7 +1465,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable set_toot_visibility.setImageResource(R.drawable.ic_mail_outline); break; } - }else { + } else { toot_visibility_container.setVisibility(View.GONE); } @@ -1475,7 +1490,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable public void onClick(DialogInterface dialog, int position) { String visibility = "public"; - switch (position){ + switch (position) { case 0: visibility = "public"; set_toot_visibility.setImageResource(R.drawable.ic_public); @@ -1493,13 +1508,13 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable set_toot_visibility.setImageResource(R.drawable.ic_mail_outline); break; } - if( account != null) { + if (account != null) { SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(Helper.SET_TOOT_VISIBILITY + "@" + account.getAcct() + "@" + account.getInstance(), visibility); editor.apply(); Toasty.info(context, context.getString(R.string.toast_visibility_changed, "@" + account.getAcct() + "@" + account.getInstance()), Toast.LENGTH_SHORT).show(); - }else { - Toasty.error(context, context.getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + } else { + Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); } dialog.dismiss(); @@ -1510,28 +1525,29 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable }); - boolean allow_live_notifications = sharedpreferences.getBoolean(Helper.SET_ALLOW_STREAM+userId+instance, true); + boolean allow_live_notifications = sharedpreferences.getBoolean(Helper.SET_ALLOW_STREAM + userId + instance, true); TextView set_allow_live_notifications_title = rootView.findViewById(R.id.set_allow_live_notifications_title); - set_allow_live_notifications_title.setText(context.getString(R.string.set_allow_live_notifications, account.getAcct() + "@"+account.getInstance())); + set_allow_live_notifications_title.setText(context.getString(R.string.set_allow_live_notifications, account.getAcct() + "@" + account.getInstance())); final CheckBox set_allow_live_notifications = rootView.findViewById(R.id.set_allow_live_notifications); set_allow_live_notifications.setChecked(allow_live_notifications); set_allow_live_notifications.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_ALLOW_STREAM+userId+instance, set_allow_live_notifications.isChecked()); + editor.putBoolean(Helper.SET_ALLOW_STREAM + userId + instance, set_allow_live_notifications.isChecked()); editor.apply(); - if( set_allow_live_notifications.isChecked()){ + if (set_allow_live_notifications.isChecked()) { LiveNotificationService.totalAccount++; - }else{ + } else { LiveNotificationService.totalAccount--; } boolean liveNotifications = sharedpreferences.getBoolean(Helper.SET_LIVE_NOTIFICATIONS, true); - if( liveNotifications) { + if (liveNotifications) { Intent streamingServiceIntent = new Intent(context.getApplicationContext(), LiveNotificationService.class); try { context.startService(streamingServiceIntent); - }catch (Exception ignored){} + } catch (Exception ignored) { + } } } }); @@ -1548,7 +1564,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable } }); - int split_size_val = sharedpreferences.getInt(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS_SIZE+userId+instance, Helper.SPLIT_TOOT_SIZE); + int split_size_val = sharedpreferences.getInt(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS_SIZE + userId + instance, Helper.SPLIT_TOOT_SIZE); LinearLayout set_split_container = rootView.findViewById(R.id.set_split_container); //split size @@ -1560,21 +1576,25 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable split_size.setMax(5); split_size.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override - public void onStopTrackingTouch(SeekBar seekBar) {} + public void onStopTrackingTouch(SeekBar seekBar) { + } + @Override - public void onStartTrackingTouch(SeekBar seekBar) {} + public void onStartTrackingTouch(SeekBar seekBar) { + } + @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int newProgress = (progress + 1) * Helper.SPLIT_TOOT_SIZE; split_text.setText(String.valueOf(newProgress)); SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putInt(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS_SIZE+userId+instance, newProgress); + editor.putInt(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS_SIZE + userId + instance, newProgress); editor.apply(); } }); - boolean split_toot = sharedpreferences.getBoolean(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS+userId+instance, false); - if( !split_toot){ + boolean split_toot = sharedpreferences.getBoolean(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS + userId + instance, false); + if (!split_toot) { set_split_container.setVisibility(View.GONE); } final CheckBox set_split_toot = rootView.findViewById(R.id.set_automatically_split_toot); @@ -1583,11 +1603,11 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable @Override public void onClick(View v) { SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS+userId+instance, set_split_toot.isChecked()); + editor.putBoolean(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS + userId + instance, set_split_toot.isChecked()); editor.apply(); - if( set_split_toot.isChecked()){ + if (set_split_toot.isChecked()) { set_split_container.setVisibility(View.VISIBLE); - }else{ + } else { set_split_container.setVisibility(View.GONE); } } @@ -1600,7 +1620,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable translation_layout_spinner.setAdapter(adapterTrans); int positionSpinnerTrans; - switch (sharedpreferences.getInt(Helper.SET_TRANSLATOR, Helper.TRANS_YANDEX)){ + switch (sharedpreferences.getInt(Helper.SET_TRANSLATOR, Helper.TRANS_YANDEX)) { case Helper.TRANS_YANDEX: positionSpinnerTrans = 0; your_api_key.setVisibility(View.VISIBLE); @@ -1623,7 +1643,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable translation_layout_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { - if( count3 > 0 ) { + if (count3 > 0) { SharedPreferences.Editor editor = sharedpreferences.edit(); switch (position) { case 0: @@ -1648,7 +1668,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable editor.apply(); break; } - if( getActivity() != null) + if (getActivity() != null) getActivity().recreate(); Intent intent = new Intent(context, MainActivity.class); intent.putExtra(Helper.INTENT_ACTION, Helper.BACK_TO_SETTINGS); @@ -1656,6 +1676,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable } count3++; } + @Override public void onNothingSelected(AdapterView parent) { @@ -1672,34 +1693,25 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable resize_layout_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { - if( count4 > 0) { + if (count4 > 0) { SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putInt(Helper.SET_PICTURE_RESIZE, position); editor.apply(); } count4++; } + @Override public void onNothingSelected(AdapterView parent) { } }); - - - - - - - - - - boolean notify = sharedpreferences.getBoolean(Helper.SET_NOTIFY, true); final SwitchCompat switchCompatNotify = rootView.findViewById(R.id.set_notify); switchCompatNotify.setChecked(notify); final LinearLayout notification_settings = rootView.findViewById(R.id.notification_settings); - if( notify) + if (notify) notification_settings.setVisibility(View.VISIBLE); else notification_settings.setVisibility(View.GONE); @@ -1710,7 +1722,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putBoolean(Helper.SET_NOTIFY, isChecked); editor.apply(); - if( isChecked) + if (isChecked) notification_settings.setVisibility(View.VISIBLE); else notification_settings.setVisibility(View.GONE); @@ -1718,7 +1730,6 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable }); - boolean notif_follow = sharedpreferences.getBoolean(Helper.SET_NOTIF_FOLLOW, true); boolean notif_add = sharedpreferences.getBoolean(Helper.SET_NOTIF_ADD, true); boolean notif_mention = sharedpreferences.getBoolean(Helper.SET_NOTIF_MENTION, true); @@ -1843,7 +1854,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable startActivity(intent); } }); - }else{ + } else { set_notif_sound.setVisibility(View.VISIBLE); channels_container.setVisibility(View.GONE); set_notif_sound.setOnClickListener(new View.OnClickListener() { @@ -1881,14 +1892,14 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { SharedPreferences.Editor editor = sharedpreferences.edit(); - String hours = (String.valueOf(hourOfDay).length() == 1) ? "0"+String.valueOf(hourOfDay):String.valueOf(hourOfDay); - String minutes = (String.valueOf(minute).length() == 1) ? "0"+String.valueOf(minute):String.valueOf(minute); + String hours = (String.valueOf(hourOfDay).length() == 1) ? "0" + String.valueOf(hourOfDay) : String.valueOf(hourOfDay); + String minutes = (String.valueOf(minute).length() == 1) ? "0" + String.valueOf(minute) : String.valueOf(minute); String newDate = hours + ":" + minutes; - if( Helper.compareDate(context, newDate, false) ) { + if (Helper.compareDate(context, newDate, false)) { editor.putString(Helper.SET_TIME_FROM, newDate); editor.apply(); settings_time_from.setText(newDate); - }else { + } else { String ateRef = sharedpreferences.getString(Helper.SET_TIME_TO, "22:00"); Toasty.error(context, context.getString(R.string.settings_time_lower, ateRef), Toast.LENGTH_LONG).show(); } @@ -1903,7 +1914,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable @Override public void onClick(View v) { String[] datetime = time_to.split(":"); - TimePickerDialog timePickerDialog = new TimePickerDialog(getActivity(),style, new TimePickerDialog.OnTimeSetListener() { + TimePickerDialog timePickerDialog = new TimePickerDialog(getActivity(), style, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { SharedPreferences.Editor editor = sharedpreferences.edit(); @@ -1931,7 +1942,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable R.array.action_notification, android.R.layout.simple_spinner_item); action_notification.setAdapter(adapterAction); int positionNotificationAntion; - switch (sharedpreferences.getInt(Helper.SET_NOTIFICATION_ACTION, Helper.ACTION_ACTIVE)){ + switch (sharedpreferences.getInt(Helper.SET_NOTIFICATION_ACTION, Helper.ACTION_ACTIVE)) { case Helper.ACTION_ACTIVE: positionNotificationAntion = 0; break; @@ -1945,7 +1956,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable action_notification.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { - if( count7 > 0 ) { + if (count7 > 0) { SharedPreferences.Editor editor = sharedpreferences.edit(); switch (position) { @@ -1961,6 +1972,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable } count7++; } + @Override public void onNothingSelected(AdapterView parent) { @@ -2080,9 +2092,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable public void onNothingSelected(AdapterView parent) { } }); - } - - else { + } else { ledLabel.setEnabled(false); for (View lol : led_colour_spinner.getTouchables()) { lol.setEnabled(false); @@ -2108,7 +2118,8 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable Canvas canvas = new Canvas(bitmap); containerView.draw(canvas); ContentSettingsFragment.this.bitmap = bitmap; - }catch (Exception e){} + } catch (Exception e) { + } } }; @@ -2163,7 +2174,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable } final String selection = "_id=?"; - final String[] selectionArgs = new String[] { + final String[] selectionArgs = new String[]{ split[1] }; return getDataColumn(context, contentUri, selection, selectionArgs); @@ -2185,6 +2196,7 @@ public class ContentSettingsFragment extends Fragment implements ScreenShotable return null; } + public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { diff --git a/app/src/main/java/app/fedilab/android/fragments/DisplayAccountsFragment.java b/app/src/main/java/app/fedilab/android/fragments/DisplayAccountsFragment.java index ef5bafceb..03a98fcf4 100644 --- a/app/src/main/java/app/fedilab/android/fragments/DisplayAccountsFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/DisplayAccountsFragment.java @@ -243,10 +243,10 @@ public class DisplayAccountsFragment extends Fragment implements OnRetrieveAccou this.accounts.addAll(accounts); accountsListAdapter.notifyItemRangeChanged(currentPosition, accounts.size()); } - if( context instanceof TootInfoActivity && this.accounts != null){ - if( type == RetrieveAccountsAsyncTask.Type.REBLOGGED) { + if (context instanceof TootInfoActivity && this.accounts != null) { + if (type == RetrieveAccountsAsyncTask.Type.REBLOGGED) { ((TootInfoActivity) context).updateBoostCount(this.accounts.size()); - }else if( type == RetrieveAccountsAsyncTask.Type.FAVOURITED) { + } else if (type == RetrieveAccountsAsyncTask.Type.FAVOURITED) { ((TootInfoActivity) context).updateFavCount(this.accounts.size()); } } @@ -292,7 +292,7 @@ public class DisplayAccountsFragment extends Fragment implements OnRetrieveAccou } } - public void pullToRefresh(){ + public void pullToRefresh() { max_id = null; accounts = new ArrayList<>(); firstLoad = true; diff --git a/app/src/main/java/app/fedilab/android/fragments/DisplayAdminAccountsFragment.java b/app/src/main/java/app/fedilab/android/fragments/DisplayAdminAccountsFragment.java index 852bb8e72..0682e7f6d 100644 --- a/app/src/main/java/app/fedilab/android/fragments/DisplayAdminAccountsFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/DisplayAdminAccountsFragment.java @@ -109,9 +109,8 @@ public class DisplayAdminAccountsFragment extends Fragment implements OnAdminAct mLayoutManager = new LinearLayoutManager(context); lv_admin_accounts.setLayoutManager(mLayoutManager); lv_admin_accounts.addOnScrollListener(new RecyclerView.OnScrollListener() { - public void onScrolled(RecyclerView recyclerView, int dx, int dy) - { - if(dy > 0) { + public void onScrolled(RecyclerView recyclerView, int dx, int dy) { + if (dy > 0) { int visibleItemCount = mLayoutManager.getChildCount(); int totalItemCount = mLayoutManager.getItemCount(); int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition(); @@ -157,7 +156,7 @@ public class DisplayAdminAccountsFragment extends Fragment implements OnAdminAct }); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: swipeRefreshLayout.setColorSchemeResources(R.color.mastodonC4, R.color.mastodonC2, @@ -190,17 +189,15 @@ public class DisplayAdminAccountsFragment extends Fragment implements OnAdminAct } @Override - public void onCreate(Bundle saveInstance) - { + public void onCreate(Bundle saveInstance) { super.onCreate(saveInstance); } - /** * Refresh accounts in list */ - public void refreshFilter(){ + public void refreshFilter() { accountsAdminListAdapter.notifyDataSetChanged(); } @@ -212,12 +209,12 @@ public class DisplayAdminAccountsFragment extends Fragment implements OnAdminAct public void onDestroy() { super.onDestroy(); - if(asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) + if (asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) asyncTask.cancel(true); } - public void scrollToTop(){ - if( lv_admin_accounts != null) + public void scrollToTop() { + if (lv_admin_accounts != null) lv_admin_accounts.setAdapter(accountsAdminListAdapter); } @@ -226,32 +223,32 @@ public class DisplayAdminAccountsFragment extends Fragment implements OnAdminAct public void onAdminAction(APIResponse apiResponse) { mainLoader.setVisibility(View.GONE); nextElementLoader.setVisibility(View.GONE); - if( apiResponse.getError() != null){ - Toasty.error(context, apiResponse.getError().getError(),Toast.LENGTH_LONG).show(); + if (apiResponse.getError() != null) { + Toasty.error(context, apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); swipeRefreshLayout.setRefreshing(false); swiped = false; flag_loading = false; return; } - flag_loading = (apiResponse.getMax_id() == null ); + flag_loading = (apiResponse.getMax_id() == null); List accountAdmins = apiResponse.getAccountAdmins(); - if( !swiped && firstLoad && (accountAdmins == null || accountAdmins.size() == 0)) + if (!swiped && firstLoad && (accountAdmins == null || accountAdmins.size() == 0)) textviewNoAction.setVisibility(View.VISIBLE); else textviewNoAction.setVisibility(View.GONE); max_id = apiResponse.getMax_id(); - if( swiped ){ + if (swiped) { accountsAdminListAdapter = new AccountsAdminListAdapter(this.accountAdmins); lv_admin_accounts.setAdapter(accountsAdminListAdapter); swiped = false; } - if( accountAdmins != null && accountAdmins.size() > 0) { + if (accountAdmins != null && accountAdmins.size() > 0) { int currentPosition = this.accountAdmins.size(); this.accountAdmins.addAll(accountAdmins); - accountsAdminListAdapter.notifyItemRangeChanged(currentPosition,accountAdmins.size()); + accountsAdminListAdapter.notifyItemRangeChanged(currentPosition, accountAdmins.size()); } swipeRefreshLayout.setRefreshing(false); firstLoad = false; diff --git a/app/src/main/java/app/fedilab/android/fragments/DisplayAdminReportsFragment.java b/app/src/main/java/app/fedilab/android/fragments/DisplayAdminReportsFragment.java index 30fed9a9d..575a2da3b 100644 --- a/app/src/main/java/app/fedilab/android/fragments/DisplayAdminReportsFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/DisplayAdminReportsFragment.java @@ -75,6 +75,7 @@ public class DisplayAdminReportsFragment extends Fragment implements OnAdminActi private boolean swiped; private RecyclerView lv_reports; private boolean unresolved; + @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { @@ -108,9 +109,8 @@ public class DisplayAdminReportsFragment extends Fragment implements OnAdminActi mLayoutManager = new LinearLayoutManager(context); lv_reports.setLayoutManager(mLayoutManager); lv_reports.addOnScrollListener(new RecyclerView.OnScrollListener() { - public void onScrolled(RecyclerView recyclerView, int dx, int dy) - { - if(dy > 0) { + public void onScrolled(RecyclerView recyclerView, int dx, int dy) { + if (dy > 0) { int visibleItemCount = mLayoutManager.getChildCount(); int totalItemCount = mLayoutManager.getItemCount(); int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition(); @@ -144,7 +144,7 @@ public class DisplayAdminReportsFragment extends Fragment implements OnAdminActi }); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: swipeRefreshLayout.setColorSchemeResources(R.color.mastodonC4, R.color.mastodonC2, @@ -171,8 +171,7 @@ public class DisplayAdminReportsFragment extends Fragment implements OnAdminActi } @Override - public void onCreate(Bundle saveInstance) - { + public void onCreate(Bundle saveInstance) { super.onCreate(saveInstance); } @@ -180,7 +179,7 @@ public class DisplayAdminReportsFragment extends Fragment implements OnAdminActi /** * Refresh report in list */ - public void refreshFilter(){ + public void refreshFilter() { reportsListAdapter.notifyDataSetChanged(); } @@ -192,12 +191,12 @@ public class DisplayAdminReportsFragment extends Fragment implements OnAdminActi public void onDestroy() { super.onDestroy(); - if(asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) + if (asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) asyncTask.cancel(true); } - public void scrollToTop(){ - if( lv_reports != null) + public void scrollToTop() { + if (lv_reports != null) lv_reports.setAdapter(reportsListAdapter); } @@ -206,55 +205,55 @@ public class DisplayAdminReportsFragment extends Fragment implements OnAdminActi public void onAdminAction(APIResponse apiResponse) { mainLoader.setVisibility(View.GONE); nextElementLoader.setVisibility(View.GONE); - if( apiResponse.getError() != null){ + if (apiResponse.getError() != null) { swipeRefreshLayout.setRefreshing(false); swiped = false; flag_loading = false; //Admin right not granted through the API? - if( apiResponse.getError().getStatusCode() == 403){ + if (apiResponse.getError().getStatusCode() == 403) { AlertDialog.Builder builderInner; builderInner = new AlertDialog.Builder(context, R.style.AdminDialog); builderInner.setTitle(R.string.reconnect_account); builderInner.setMessage(R.string.reconnect_account_message); builderInner.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog,int which) { + public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builderInner.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog,int which) { + public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(context, LoginActivity.class); intent.putExtra("admin", true); context.startActivity(intent); } }); builderInner.show(); - }else{ - Toasty.error(context, apiResponse.getError().getError(),Toast.LENGTH_LONG).show(); + } else { + Toasty.error(context, apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); } return; } - flag_loading = (apiResponse.getMax_id() == null ); + flag_loading = (apiResponse.getMax_id() == null); List reports = apiResponse.getReports(); - if( !swiped && firstLoad && (reports == null || reports.size() == 0)) + if (!swiped && firstLoad && (reports == null || reports.size() == 0)) textviewNoAction.setVisibility(View.VISIBLE); else textviewNoAction.setVisibility(View.GONE); max_id = apiResponse.getMax_id(); - if( swiped ){ + if (swiped) { reportsListAdapter = new ReportsListAdapter(this.reports); lv_reports.setAdapter(reportsListAdapter); swiped = false; } - if( reports != null && reports.size() > 0) { + if (reports != null && reports.size() > 0) { int currentPosition = this.reports.size(); this.reports.addAll(reports); - reportsListAdapter.notifyItemRangeChanged(currentPosition,reports.size()); + reportsListAdapter.notifyItemRangeChanged(currentPosition, reports.size()); } swipeRefreshLayout.setRefreshing(false); firstLoad = false; diff --git a/app/src/main/java/app/fedilab/android/fragments/DisplayBookmarksFragment.java b/app/src/main/java/app/fedilab/android/fragments/DisplayBookmarksFragment.java index a9dcfbbb0..9a77a7e8b 100644 --- a/app/src/main/java/app/fedilab/android/fragments/DisplayBookmarksFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/DisplayBookmarksFragment.java @@ -20,12 +20,16 @@ import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.os.Bundle; + import androidx.annotation.NonNull; + import com.google.android.material.floatingactionbutton.FloatingActionButton; + import androidx.fragment.app.Fragment; import androidx.appcompat.app.AlertDialog; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -66,7 +70,7 @@ public class DisplayBookmarksFragment extends Fragment implements OnRetrieveFeed View rootView = inflater.inflate(R.layout.fragment_bookmarks, container, false); context = getContext(); - lv_status = rootView.findViewById(R.id.lv_status); + lv_status = rootView.findViewById(R.id.lv_status); mainLoader = rootView.findViewById(R.id.loader); textviewNoAction = rootView.findViewById(R.id.no_action); @@ -78,8 +82,7 @@ public class DisplayBookmarksFragment extends Fragment implements OnRetrieveFeed @Override - public void onCreate(Bundle saveInstance) - { + public void onCreate(Bundle saveInstance) { super.onCreate(saveInstance); } @@ -99,20 +102,21 @@ public class DisplayBookmarksFragment extends Fragment implements OnRetrieveFeed FloatingActionButton delete_all = null; try { delete_all = ((MainActivity) context).findViewById(R.id.delete_all); - }catch (Exception ignored){} + } catch (Exception ignored) { + } final boolean isOnWifi = Helper.isOnWIFI(context); final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); statuses = apiResponse.getStatuses(); - if( statuses != null && statuses.size() > 0) { + if (statuses != null && statuses.size() > 0) { LinearLayoutManager mLayoutManager = new LinearLayoutManager(context); statusListAdapter = new StatusListAdapter(RetrieveFeedsAsyncTask.Type.CACHE_BOOKMARKS, null, isOnWifi, this.statuses); lv_status.setAdapter(statusListAdapter); lv_status.setLayoutManager(mLayoutManager); - }else { + } else { textviewNoAction.setVisibility(View.VISIBLE); } - if( delete_all != null) + if (delete_all != null) delete_all.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { @@ -121,9 +125,9 @@ public class DisplayBookmarksFragment extends Fragment implements OnRetrieveFeed int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } AlertDialog.Builder builder = new AlertDialog.Builder(context, style); diff --git a/app/src/main/java/app/fedilab/android/fragments/DisplayDraftsFragment.java b/app/src/main/java/app/fedilab/android/fragments/DisplayDraftsFragment.java index df9c9abbb..883ddfb47 100644 --- a/app/src/main/java/app/fedilab/android/fragments/DisplayDraftsFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/DisplayDraftsFragment.java @@ -19,10 +19,14 @@ import android.content.DialogInterface; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; + import androidx.annotation.NonNull; + import com.google.android.material.floatingactionbutton.FloatingActionButton; + import androidx.fragment.app.Fragment; import androidx.appcompat.app.AlertDialog; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -54,6 +58,7 @@ public class DisplayDraftsFragment extends Fragment { private List drafts; private DraftsListAdapter draftsListAdapter; private RelativeLayout textviewNoAction; + @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { @@ -67,28 +72,29 @@ public class DisplayDraftsFragment extends Fragment { mainLoader.setVisibility(View.VISIBLE); final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); final int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if( theme == Helper.THEME_DARK){ - Helper.changeDrawableColor(context, R.drawable.ic_cancel,R.color.dark_text); - }else { - Helper.changeDrawableColor(context, R.drawable.ic_cancel,R.color.black); + if (theme == Helper.THEME_DARK) { + Helper.changeDrawableColor(context, R.drawable.ic_cancel, R.color.dark_text); + } else { + Helper.changeDrawableColor(context, R.drawable.ic_cancel, R.color.black); } final SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); //Removes all scheduled toots that have sent new StatusStoredDAO(context, db).removeAllSent(); drafts = new StatusStoredDAO(context, db).getAllDrafts(); - if( drafts != null && drafts.size() > 0) { + if (drafts != null && drafts.size() > 0) { draftsListAdapter = new DraftsListAdapter(drafts, true, textviewNoAction); lv_draft_toots.setAdapter(draftsListAdapter); draftsListAdapter.notifyDataSetChanged(); - }else { + } else { textviewNoAction.setVisibility(View.VISIBLE); } mainLoader.setVisibility(View.GONE); FloatingActionButton delete_all = null; try { delete_all = ((MainActivity) context).findViewById(R.id.delete_all); - }catch (Exception ignored){} - if( delete_all != null) + } catch (Exception ignored) { + } + if (delete_all != null) delete_all.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { @@ -97,9 +103,9 @@ public class DisplayDraftsFragment extends Fragment { int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } AlertDialog.Builder builder = new AlertDialog.Builder(context, style); @@ -132,8 +138,7 @@ public class DisplayDraftsFragment extends Fragment { @Override - public void onCreate(Bundle saveInstance) - { + public void onCreate(Bundle saveInstance) { super.onCreate(saveInstance); } diff --git a/app/src/main/java/app/fedilab/android/fragments/DisplayFavoritesPeertubeFragment.java b/app/src/main/java/app/fedilab/android/fragments/DisplayFavoritesPeertubeFragment.java index aed4dc90a..fde074e28 100644 --- a/app/src/main/java/app/fedilab/android/fragments/DisplayFavoritesPeertubeFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/DisplayFavoritesPeertubeFragment.java @@ -20,12 +20,16 @@ import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.os.Bundle; + import androidx.annotation.NonNull; + import com.google.android.material.floatingactionbutton.FloatingActionButton; + import androidx.fragment.app.Fragment; import androidx.appcompat.app.AlertDialog; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -66,7 +70,7 @@ public class DisplayFavoritesPeertubeFragment extends Fragment implements OnRetr View rootView = inflater.inflate(R.layout.fragment_peertube_favourites, container, false); context = getContext(); - lv_status = rootView.findViewById(R.id.lv_status); + lv_status = rootView.findViewById(R.id.lv_status); mainLoader = rootView.findViewById(R.id.loader); textviewNoAction = rootView.findViewById(R.id.no_action); @@ -76,8 +80,7 @@ public class DisplayFavoritesPeertubeFragment extends Fragment implements OnRetr @Override - public void onCreate(Bundle saveInstance) - { + public void onCreate(Bundle saveInstance) { super.onCreate(saveInstance); } @@ -102,21 +105,22 @@ public class DisplayFavoritesPeertubeFragment extends Fragment implements OnRetr FloatingActionButton delete_all = null; try { delete_all = ((MainActivity) context).findViewById(R.id.delete_all); - }catch (Exception ignored){} + } catch (Exception ignored) { + } peertubes = apiResponse.getPeertubes(); - if( peertubes != null && peertubes.size() > 0) { + if (peertubes != null && peertubes.size() > 0) { LinearLayoutManager mLayoutManager = new LinearLayoutManager(context); peertubeAdapter = new PeertubeAdapter(peertubes.get(0).getInstance(), this.peertubes); lv_status.setAdapter(peertubeAdapter); lv_status.setLayoutManager(mLayoutManager); textviewNoAction.setVisibility(View.GONE); lv_status.setVisibility(View.VISIBLE); - }else { + } else { textviewNoAction.setVisibility(View.VISIBLE); lv_status.setVisibility(View.GONE); } - if( delete_all != null) + if (delete_all != null) delete_all.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { @@ -125,9 +129,9 @@ public class DisplayFavoritesPeertubeFragment extends Fragment implements OnRetr int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } AlertDialog.Builder builder = new AlertDialog.Builder(context, style); diff --git a/app/src/main/java/app/fedilab/android/fragments/DisplayFiltersFragment.java b/app/src/main/java/app/fedilab/android/fragments/DisplayFiltersFragment.java index c3c98fc43..6ba082852 100644 --- a/app/src/main/java/app/fedilab/android/fragments/DisplayFiltersFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/DisplayFiltersFragment.java @@ -21,10 +21,14 @@ import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.os.Bundle; + import androidx.annotation.NonNull; + import com.google.android.material.floatingactionbutton.FloatingActionButton; + import androidx.fragment.app.Fragment; import androidx.appcompat.app.AlertDialog; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -97,124 +101,124 @@ public class DisplayFiltersFragment extends Fragment implements OnFilterActionIn asyncTask = new ManageFiltersAsyncTask(context, ManageFiltersAsyncTask.action.GET_ALL_FILTER, null, DisplayFiltersFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); try { add_new = ((MainActivity) context).findViewById(R.id.add_new); - }catch (Exception ignored){} - if( add_new != null) - add_new.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - int style; - if (theme == Helper.THEME_DARK) { - style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ - style = R.style.DialogBlack; - }else { - style = R.style.Dialog; - } - AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, style); - LayoutInflater inflater = getLayoutInflater(); - View dialogView = inflater.inflate(R.layout.add_filter, new LinearLayout(context), false); - dialogBuilder.setView(dialogView); - - EditText add_phrase = dialogView.findViewById(R.id.add_phrase); - CheckBox context_home = dialogView.findViewById(R.id.context_home); - CheckBox context_public = dialogView.findViewById(R.id.context_public); - CheckBox context_notification = dialogView.findViewById(R.id.context_notification); - CheckBox context_conversation = dialogView.findViewById(R.id.context_conversation); - CheckBox context_whole_word = dialogView.findViewById(R.id.context_whole_word); - CheckBox context_drop = dialogView.findViewById(R.id.context_drop); - Spinner filter_expire = dialogView.findViewById(R.id.filter_expire); - ArrayAdapter adapterResize = ArrayAdapter.createFromResource(Objects.requireNonNull(getContext()), - R.array.filter_expire, android.R.layout.simple_spinner_item); - filter_expire.setAdapter(adapterResize); - final int[] expire = {-1}; - filter_expire.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - switch (position){ - case 0: - expire[0] = -1; - break; - case 1: - expire[0] = 3600; - break; - case 2: - expire[0] = 21600; - break; - case 3: - expire[0] = 43200; - break; - case 4: - expire[0] = 86400; - break; - case 5: - expire[0] = 604800; - break; - } + } catch (Exception ignored) { + } + if (add_new != null) + add_new.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); + int style; + if (theme == Helper.THEME_DARK) { + style = R.style.DialogDark; + } else if (theme == Helper.THEME_BLACK) { + style = R.style.DialogBlack; + } else { + style = R.style.Dialog; } - @Override - public void onNothingSelected(AdapterView parent) { - } - }); - dialogBuilder.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int id) { + AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, style); + LayoutInflater inflater = getLayoutInflater(); + View dialogView = inflater.inflate(R.layout.add_filter, new LinearLayout(context), false); + dialogBuilder.setView(dialogView); - if( add_phrase.getText() != null && add_phrase.getText().toString().trim().length() > 0 ) { - Filters filter = new Filters(); - ArrayList contextFilter = new ArrayList<>(); - if( context_home.isChecked()) - contextFilter.add("home"); - if( context_public.isChecked()) - contextFilter.add("public"); - if( context_notification.isChecked()) - contextFilter.add("notifications"); - if( context_conversation.isChecked()) - contextFilter.add("thread"); - filter.setContext(contextFilter); - filter.setPhrase(add_phrase.getText().toString()); - filter.setExpires_in(expire[0]); - filter.setWhole_word(context_whole_word.isChecked()); - filter.setIrreversible(context_drop.isChecked()); - new ManageFiltersAsyncTask(context, ManageFiltersAsyncTask.action.CREATE_FILTER, filter, DisplayFiltersFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + EditText add_phrase = dialogView.findViewById(R.id.add_phrase); + CheckBox context_home = dialogView.findViewById(R.id.context_home); + CheckBox context_public = dialogView.findViewById(R.id.context_public); + CheckBox context_notification = dialogView.findViewById(R.id.context_notification); + CheckBox context_conversation = dialogView.findViewById(R.id.context_conversation); + CheckBox context_whole_word = dialogView.findViewById(R.id.context_whole_word); + CheckBox context_drop = dialogView.findViewById(R.id.context_drop); + Spinner filter_expire = dialogView.findViewById(R.id.filter_expire); + ArrayAdapter adapterResize = ArrayAdapter.createFromResource(Objects.requireNonNull(getContext()), + R.array.filter_expire, android.R.layout.simple_spinner_item); + filter_expire.setAdapter(adapterResize); + final int[] expire = {-1}; + filter_expire.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + switch (position) { + case 0: + expire[0] = -1; + break; + case 1: + expire[0] = 3600; + break; + case 2: + expire[0] = 21600; + break; + case 3: + expire[0] = 43200; + break; + case 4: + expire[0] = 86400; + break; + case 5: + expire[0] = 604800; + break; + } } - dialog.dismiss(); - add_new.setEnabled(false); - } - }); - dialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int id) { - dialog.dismiss(); - } - }); + + @Override + public void onNothingSelected(AdapterView parent) { + } + }); + dialogBuilder.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + + if (add_phrase.getText() != null && add_phrase.getText().toString().trim().length() > 0) { + Filters filter = new Filters(); + ArrayList contextFilter = new ArrayList<>(); + if (context_home.isChecked()) + contextFilter.add("home"); + if (context_public.isChecked()) + contextFilter.add("public"); + if (context_notification.isChecked()) + contextFilter.add("notifications"); + if (context_conversation.isChecked()) + contextFilter.add("thread"); + filter.setContext(contextFilter); + filter.setPhrase(add_phrase.getText().toString()); + filter.setExpires_in(expire[0]); + filter.setWhole_word(context_whole_word.isChecked()); + filter.setIrreversible(context_drop.isChecked()); + new ManageFiltersAsyncTask(context, ManageFiltersAsyncTask.action.CREATE_FILTER, filter, DisplayFiltersFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + } + dialog.dismiss(); + add_new.setEnabled(false); + } + }); + dialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + dialog.dismiss(); + } + }); - AlertDialog alertDialog = dialogBuilder.create(); - alertDialog.setTitle(getString(R.string.action_filter_create)); - alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() { - @Override - public void onDismiss(DialogInterface dialogInterface) { - //Hide keyboard - InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); - assert imm != null; - imm.hideSoftInputFromWindow(add_phrase.getWindowToken(), 0); - } - }); - if( alertDialog.getWindow() != null ) - alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); - alertDialog.show(); - } - }); + AlertDialog alertDialog = dialogBuilder.create(); + alertDialog.setTitle(getString(R.string.action_filter_create)); + alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() { + @Override + public void onDismiss(DialogInterface dialogInterface) { + //Hide keyboard + InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); + assert imm != null; + imm.hideSoftInputFromWindow(add_phrase.getWindowToken(), 0); + } + }); + if (alertDialog.getWindow() != null) + alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); + alertDialog.show(); + } + }); return rootView; } - @Override - public void onCreate(Bundle saveInstance) - { + public void onCreate(Bundle saveInstance) { super.onCreate(saveInstance); } @@ -227,22 +231,20 @@ public class DisplayFiltersFragment extends Fragment implements OnFilterActionIn public void onDestroy() { super.onDestroy(); - if(asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) + if (asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) asyncTask.cancel(true); } - - @Override public void onActionDone(ManageFiltersAsyncTask.action actionType, APIResponse apiResponse, int statusCode) { mainLoader.setVisibility(View.GONE); add_new.setEnabled(true); - if( apiResponse.getError() != null){ - Toasty.error(context, apiResponse.getError().getError(),Toast.LENGTH_LONG).show(); + if (apiResponse.getError() != null) { + Toasty.error(context, apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); return; } - if( actionType == ManageFiltersAsyncTask.action.GET_ALL_FILTER) { + if (actionType == ManageFiltersAsyncTask.action.GET_ALL_FILTER) { if (apiResponse.getFilters() != null && apiResponse.getFilters().size() > 0) { this.filters.addAll(apiResponse.getFilters()); filterAdapter.notifyDataSetChanged(); @@ -252,24 +254,24 @@ public class DisplayFiltersFragment extends Fragment implements OnFilterActionIn textviewNoAction.setVisibility(View.VISIBLE); lv_filters.setVisibility(View.GONE); } - }else if( actionType == ManageFiltersAsyncTask.action.CREATE_FILTER){ + } else if (actionType == ManageFiltersAsyncTask.action.CREATE_FILTER) { if (apiResponse.getFilters() != null && apiResponse.getFilters().size() > 0) { this.filters.add(0, apiResponse.getFilters().get(0)); filterAdapter.notifyDataSetChanged(); textviewNoAction.setVisibility(View.GONE); lv_filters.setVisibility(View.VISIBLE); - }else{ - Toasty.error(context, context.getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + } else { + Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); } } MainActivity.filters = apiResponse.getFilters(); SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); List timelines = new TimelinesDAO(context, db).getDisplayedTimelines(); - if( mPageReferenceMap == null) { + if (mPageReferenceMap == null) { return; } - for(ManageTimelines tl: timelines) { - if( tl.getType() == ManageTimelines.Type.HOME || tl.getType() == ManageTimelines.Type.LOCAL || tl.getType() == ManageTimelines.Type.PUBLIC) { + for (ManageTimelines tl : timelines) { + if (tl.getType() == ManageTimelines.Type.HOME || tl.getType() == ManageTimelines.Type.LOCAL || tl.getType() == ManageTimelines.Type.PUBLIC) { DisplayStatusFragment displayStatusFragment = (DisplayStatusFragment) mPageReferenceMap.get(tl.getPosition()); if (displayStatusFragment != null) displayStatusFragment.refreshFilter(); diff --git a/app/src/main/java/app/fedilab/android/fragments/DisplayFollowRequestSentFragment.java b/app/src/main/java/app/fedilab/android/fragments/DisplayFollowRequestSentFragment.java index 5b7fe98a7..6f628b687 100644 --- a/app/src/main/java/app/fedilab/android/fragments/DisplayFollowRequestSentFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/DisplayFollowRequestSentFragment.java @@ -18,6 +18,7 @@ import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; + import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.core.content.ContextCompat; @@ -25,6 +26,7 @@ import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -65,6 +67,7 @@ public class DisplayFollowRequestSentFragment extends Fragment implements OnRetr private TextView no_action_text; private boolean swiped; private RecyclerView lv_accounts; + @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { @@ -95,9 +98,8 @@ public class DisplayFollowRequestSentFragment extends Fragment implements OnRetr mLayoutManager = new LinearLayoutManager(context); lv_accounts.setLayoutManager(mLayoutManager); lv_accounts.addOnScrollListener(new RecyclerView.OnScrollListener() { - public void onScrolled(RecyclerView recyclerView, int dx, int dy) - { - if(dy > 0) { + public void onScrolled(RecyclerView recyclerView, int dx, int dy) { + if (dy > 0) { int visibleItemCount = mLayoutManager.getChildCount(); int totalItemCount = mLayoutManager.getItemCount(); int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition(); @@ -126,7 +128,7 @@ public class DisplayFollowRequestSentFragment extends Fragment implements OnRetr } }); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: swipeRefreshLayout.setColorSchemeResources(R.color.mastodonC4, R.color.mastodonC2, @@ -152,15 +154,12 @@ public class DisplayFollowRequestSentFragment extends Fragment implements OnRetr } - @Override - public void onCreate(Bundle saveInstance) - { + public void onCreate(Bundle saveInstance) { super.onCreate(saveInstance); } - @Override public void onAttach(Context context) { super.onAttach(context); @@ -169,7 +168,7 @@ public class DisplayFollowRequestSentFragment extends Fragment implements OnRetr public void onDestroy() { super.onDestroy(); - if(asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) + if (asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) asyncTask.cancel(true); } @@ -179,26 +178,26 @@ public class DisplayFollowRequestSentFragment extends Fragment implements OnRetr mainLoader.setVisibility(View.GONE); nextElementLoader.setVisibility(View.GONE); - if( apiResponse.getError() != null){ - Toasty.error(context, apiResponse.getError().getError(),Toast.LENGTH_LONG).show(); + if (apiResponse.getError() != null) { + Toasty.error(context, apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); flag_loading = false; swipeRefreshLayout.setRefreshing(false); swiped = false; return; } List accounts = apiResponse.getAccounts(); - if( !swiped && firstLoad && (accounts == null || accounts.size() == 0)) { + if (!swiped && firstLoad && (accounts == null || accounts.size() == 0)) { no_action_text.setText(context.getString(R.string.no_follow_request)); textviewNoAction.setVisibility(View.VISIBLE); - }else + } else textviewNoAction.setVisibility(View.GONE); max_id = apiResponse.getMax_id(); - if( swiped ){ + if (swiped) { accountsFollowRequestAdapter = new AccountsFollowRequestAdapter(this.accounts); lv_accounts.setAdapter(accountsFollowRequestAdapter); swiped = false; } - if( accounts != null && accounts.size() > 0) { + if (accounts != null && accounts.size() > 0) { this.accounts.addAll(accounts); accountsFollowRequestAdapter.notifyDataSetChanged(); } diff --git a/app/src/main/java/app/fedilab/android/fragments/DisplayHowToFragment.java b/app/src/main/java/app/fedilab/android/fragments/DisplayHowToFragment.java index 3efcf6e50..a15247561 100644 --- a/app/src/main/java/app/fedilab/android/fragments/DisplayHowToFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/DisplayHowToFragment.java @@ -17,8 +17,10 @@ package app.fedilab.android.fragments; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; + import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -62,18 +64,15 @@ public class DisplayHowToFragment extends Fragment implements OnRetrieveHowToInt mainLoader.setVisibility(View.VISIBLE); - - asyncTask = new RetrieveHowToAsyncTask(context, DisplayHowToFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + asyncTask = new RetrieveHowToAsyncTask(context, DisplayHowToFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); return rootView; } - @Override - public void onCreate(Bundle saveInstance) - { + public void onCreate(Bundle saveInstance) { super.onCreate(saveInstance); } @@ -86,22 +85,21 @@ public class DisplayHowToFragment extends Fragment implements OnRetrieveHowToInt public void onDestroy() { super.onDestroy(); - if(asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) + if (asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) asyncTask.cancel(true); } - @Override public void onRetrieveHowTo(APIResponse apiResponse) { mainLoader.setVisibility(View.GONE); - if( apiResponse.getError() != null){ - Toasty.error(context, apiResponse.getError().getError(),Toast.LENGTH_LONG).show(); + if (apiResponse.getError() != null) { + Toasty.error(context, apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); return; } List howToVideos = apiResponse.getHowToVideos(); - if( howToVideos == null || howToVideos.size() == 0 ){ - Toasty.error(context, context.getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + if (howToVideos == null || howToVideos.size() == 0) { + Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); return; } HowToVideosAdapter howToVideosAdapter = new HowToVideosAdapter(howToVideos); diff --git a/app/src/main/java/app/fedilab/android/fragments/DisplayListsFragment.java b/app/src/main/java/app/fedilab/android/fragments/DisplayListsFragment.java index e1de80336..8dfe0b94d 100644 --- a/app/src/main/java/app/fedilab/android/fragments/DisplayListsFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/DisplayListsFragment.java @@ -22,8 +22,11 @@ import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; + import androidx.annotation.NonNull; + import com.google.android.material.floatingactionbutton.FloatingActionButton; + import androidx.fragment.app.Fragment; import androidx.appcompat.app.AlertDialog; import androidx.localbroadcastmanager.content.LocalBroadcastManager; @@ -91,68 +94,67 @@ public class DisplayListsFragment extends Fragment implements OnListActionInterf asyncTask = new ManageListsAsyncTask(context, ManageListsAsyncTask.action.GET_LIST, null, null, null, null, DisplayListsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); try { add_new = ((MainActivity) context).findViewById(R.id.add_new); - }catch (Exception ignored){} - if( add_new != null) - add_new.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - int style; - if (theme == Helper.THEME_DARK) { - style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ - style = R.style.DialogBlack; - }else { - style = R.style.Dialog; + } catch (Exception ignored) { + } + if (add_new != null) + add_new.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); + int style; + if (theme == Helper.THEME_DARK) { + style = R.style.DialogDark; + } else if (theme == Helper.THEME_BLACK) { + style = R.style.DialogBlack; + } else { + style = R.style.Dialog; + } + AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, style); + LayoutInflater inflater = ((Activity) context).getLayoutInflater(); + View dialogView = inflater.inflate(R.layout.add_list, new LinearLayout(context), false); + dialogBuilder.setView(dialogView); + final EditText editText = dialogView.findViewById(R.id.add_list); + editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(255)}); + dialogBuilder.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + if (editText.getText() != null && editText.getText().toString().trim().length() > 0) + new ManageListsAsyncTask(context, ManageListsAsyncTask.action.CREATE_LIST, null, null, null, editText.getText().toString().trim(), DisplayListsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + dialog.dismiss(); + add_new.setEnabled(false); + } + }); + dialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + dialog.dismiss(); + } + }); + + + AlertDialog alertDialog = dialogBuilder.create(); + alertDialog.setTitle(getString(R.string.action_lists_create)); + alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() { + @Override + public void onDismiss(DialogInterface dialogInterface) { + //Hide keyboard + InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); + assert imm != null; + imm.hideSoftInputFromWindow(editText.getWindowToken(), 0); + } + }); + if (alertDialog.getWindow() != null) + alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); + alertDialog.show(); } - AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, style); - LayoutInflater inflater = ((Activity)context).getLayoutInflater(); - View dialogView = inflater.inflate(R.layout.add_list, new LinearLayout(context), false); - dialogBuilder.setView(dialogView); - final EditText editText = dialogView.findViewById(R.id.add_list); - editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(255)}); - dialogBuilder.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int id) { - if( editText.getText() != null && editText.getText().toString().trim().length() > 0 ) - new ManageListsAsyncTask(context, ManageListsAsyncTask.action.CREATE_LIST, null, null, null, editText.getText().toString().trim(), DisplayListsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - dialog.dismiss(); - add_new.setEnabled(false); - } - }); - dialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int id) { - dialog.dismiss(); - } - }); - - - AlertDialog alertDialog = dialogBuilder.create(); - alertDialog.setTitle(getString(R.string.action_lists_create)); - alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() { - @Override - public void onDismiss(DialogInterface dialogInterface) { - //Hide keyboard - InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); - assert imm != null; - imm.hideSoftInputFromWindow(editText.getWindowToken(), 0); - } - }); - if( alertDialog.getWindow() != null ) - alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); - alertDialog.show(); - } - }); + }); return rootView; } - @Override - public void onCreate(Bundle saveInstance) - { + public void onCreate(Bundle saveInstance) { super.onCreate(saveInstance); } @@ -165,7 +167,7 @@ public class DisplayListsFragment extends Fragment implements OnListActionInterf public void onDestroy() { super.onDestroy(); - if(asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) + if (asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) asyncTask.cancel(true); } @@ -174,11 +176,11 @@ public class DisplayListsFragment extends Fragment implements OnListActionInterf public void onActionDone(ManageListsAsyncTask.action actionType, APIResponse apiResponse, int statusCode) { mainLoader.setVisibility(View.GONE); add_new.setEnabled(true); - if( apiResponse.getError() != null){ - Toasty.error(context, apiResponse.getError().getError(),Toast.LENGTH_LONG).show(); + if (apiResponse.getError() != null) { + Toasty.error(context, apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); return; } - if( actionType == ManageListsAsyncTask.action.GET_LIST) { + if (actionType == ManageListsAsyncTask.action.GET_LIST) { if (apiResponse.getLists() != null && apiResponse.getLists().size() > 0) { this.lists.addAll(apiResponse.getLists()); listAdapter.notifyDataSetChanged(); @@ -186,7 +188,7 @@ public class DisplayListsFragment extends Fragment implements OnListActionInterf } else { textviewNoAction.setVisibility(View.VISIBLE); } - }else if( actionType == ManageListsAsyncTask.action.CREATE_LIST){ + } else if (actionType == ManageListsAsyncTask.action.CREATE_LIST) { if (apiResponse.getLists() != null && apiResponse.getLists().size() > 0) { String listId = apiResponse.getLists().get(0).getId(); String title = apiResponse.getLists().get(0).getTitle(); @@ -201,11 +203,11 @@ public class DisplayListsFragment extends Fragment implements OnListActionInterf textviewNoAction.setVisibility(View.GONE); Intent intentUP = new Intent(Helper.RECEIVE_UPDATE_TOPBAR); LocalBroadcastManager.getInstance(context).sendBroadcast(intentUP); - }else{ - Toasty.error(context, apiResponse.getError().getError(),Toast.LENGTH_LONG).show(); + } else { + Toasty.error(context, apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); } - }else if( actionType == ManageListsAsyncTask.action.DELETE_LIST){ - if( this.lists.size() == 0) + } else if (actionType == ManageListsAsyncTask.action.DELETE_LIST) { + if (this.lists.size() == 0) textviewNoAction.setVisibility(View.VISIBLE); Intent intentUP = new Intent(Helper.RECEIVE_UPDATE_TOPBAR); LocalBroadcastManager.getInstance(context).sendBroadcast(intentUP); diff --git a/app/src/main/java/app/fedilab/android/fragments/DisplayMediaFragment.java b/app/src/main/java/app/fedilab/android/fragments/DisplayMediaFragment.java index 690308d45..2eba27912 100644 --- a/app/src/main/java/app/fedilab/android/fragments/DisplayMediaFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/DisplayMediaFragment.java @@ -20,10 +20,12 @@ import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Looper; + import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -44,7 +46,6 @@ import app.fedilab.android.asynctasks.RetrieveFeedsAsyncTask; import app.fedilab.android.interfaces.OnRetrieveFeedsInterface; - /** * Created by Thomas on 05/09/2018. * Fragment to display media related to status @@ -66,7 +67,7 @@ public class DisplayMediaFragment extends Fragment implements OnRetrieveFeedsInt private ImageAdapter gridAdaper; private RecyclerView gridview; - public DisplayMediaFragment(){ + public DisplayMediaFragment() { } @Override @@ -85,9 +86,9 @@ public class DisplayMediaFragment extends Fragment implements OnRetrieveFeedsInt firstLoad = true; assert context != null; sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - mainLoader = rootView.findViewById(R.id.loader); + mainLoader = rootView.findViewById(R.id.loader); nextElementLoader = rootView.findViewById(R.id.loading_next_status); - textviewNoAction = rootView.findViewById(R.id.no_action); + textviewNoAction = rootView.findViewById(R.id.no_action); mainLoader.setVisibility(View.VISIBLE); nextElementLoader.setVisibility(View.GONE); if (bundle != null) { @@ -126,14 +127,14 @@ public class DisplayMediaFragment extends Fragment implements OnRetrieveFeedsInt }); - if( context != null) { - asyncTask = new RetrieveFeedsAsyncTask(context, RetrieveFeedsAsyncTask.Type.USER, targetedId, max_id, showMediaOnly, showPinned, showReply,DisplayMediaFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else { + if (context != null) { + asyncTask = new RetrieveFeedsAsyncTask(context, RetrieveFeedsAsyncTask.Type.USER, targetedId, max_id, showMediaOnly, showPinned, showReply, DisplayMediaFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + } else { new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { - if( context != null){ - asyncTask = new RetrieveFeedsAsyncTask(context, RetrieveFeedsAsyncTask.Type.USER, targetedId, max_id, showMediaOnly, showPinned, showReply,DisplayMediaFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + if (context != null) { + asyncTask = new RetrieveFeedsAsyncTask(context, RetrieveFeedsAsyncTask.Type.USER, targetedId, max_id, showMediaOnly, showPinned, showReply, DisplayMediaFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } }, 500); @@ -144,16 +145,14 @@ public class DisplayMediaFragment extends Fragment implements OnRetrieveFeedsInt @Override - public void onCreate(Bundle saveInstance) - { + public void onCreate(Bundle saveInstance) { super.onCreate(saveInstance); } - @Override public void onDestroyView() { - if(gridview != null) { + if (gridview != null) { gridview.setAdapter(null); } super.onDestroyView(); @@ -166,42 +165,41 @@ public class DisplayMediaFragment extends Fragment implements OnRetrieveFeedsInt } @Override - public void onDestroy (){ + public void onDestroy() { super.onDestroy(); - if(asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) + if (asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) asyncTask.cancel(true); } - @Override public void onRetrieveFeeds(APIResponse apiResponse) { mainLoader.setVisibility(View.GONE); nextElementLoader.setVisibility(View.GONE); //Discards 404 - error which can often happen due to toots which have been deleted - if(apiResponse == null || apiResponse.getError() != null && apiResponse.getError().getStatusCode() != 404 ){ - if( apiResponse != null && apiResponse.getError() != null && apiResponse.getError().getError() != null) - Toasty.error(context, apiResponse.getError().getError(),Toast.LENGTH_LONG).show(); + if (apiResponse == null || apiResponse.getError() != null && apiResponse.getError().getStatusCode() != 404) { + if (apiResponse != null && apiResponse.getError() != null && apiResponse.getError().getError() != null) + Toasty.error(context, apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); else - Toasty.error(context, context.getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); flag_loading = false; return; } List statuses = apiResponse.getStatuses(); max_id = apiResponse.getMax_id(); - if( this.statuses == null) + if (this.statuses == null) this.statuses = new ArrayList<>(); int previousPosition = this.statuses.size(); - flag_loading = (max_id == null ); - if( firstLoad && (statuses == null || statuses.size() == 0)) + flag_loading = (max_id == null); + if (firstLoad && (statuses == null || statuses.size() == 0)) textviewNoAction.setVisibility(View.VISIBLE); else textviewNoAction.setVisibility(View.GONE); List convertedStatuses = new ArrayList<>(); - if( apiResponse.getStatuses() != null && apiResponse.getStatuses().size() > 0){ - for( Status status: apiResponse.getStatuses()){ - if( status.getMedia_attachments() != null ) { + if (apiResponse.getStatuses() != null && apiResponse.getStatuses().size() > 0) { + for (Status status : apiResponse.getStatuses()) { + if (status.getMedia_attachments() != null) { String statusSerialized = Helper.statusToStringStorage(status); for (Attachment attachment : status.getMedia_attachments()) { Status newStatus = Helper.restoreStatusFromString(statusSerialized); @@ -213,7 +211,7 @@ public class DisplayMediaFragment extends Fragment implements OnRetrieveFeedsInt } } } - if( convertedStatuses.size() > 0) { + if (convertedStatuses.size() > 0) { this.statuses.addAll(convertedStatuses); gridAdaper.notifyItemRangeInserted(previousPosition, this.statuses.size()); } diff --git a/app/src/main/java/app/fedilab/android/fragments/DisplayMutedInstanceFragment.java b/app/src/main/java/app/fedilab/android/fragments/DisplayMutedInstanceFragment.java index 741b25b93..ebb83ab29 100644 --- a/app/src/main/java/app/fedilab/android/fragments/DisplayMutedInstanceFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/DisplayMutedInstanceFragment.java @@ -20,6 +20,7 @@ import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; + import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.Fragment; @@ -37,9 +38,12 @@ import android.widget.EditText; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Toast; + import com.google.android.material.floatingactionbutton.FloatingActionButton; + import java.util.ArrayList; import java.util.List; + import app.fedilab.android.activities.MainActivity; import app.fedilab.android.asynctasks.PostActionAsyncTask; import app.fedilab.android.client.API; @@ -101,16 +105,16 @@ public class DisplayMutedInstanceFragment extends Fragment implements OnRetrieve mLayoutManager = new LinearLayoutManager(context); lv_domains.setLayoutManager(mLayoutManager); lv_domains.addOnScrollListener(new RecyclerView.OnScrollListener() { - public void onScrolled(RecyclerView recyclerView, int dx, int dy) - { - if(dy > 0) { + public void onScrolled(RecyclerView recyclerView, int dx, int dy) { + if (dy > 0) { int visibleItemCount = mLayoutManager.getChildCount(); int totalItemCount = mLayoutManager.getItemCount(); int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition(); if (firstVisibleItem + visibleItemCount == totalItemCount) { if (!flag_loading) { flag_loading = true; - asyncTask = new RetrieveDomainsAsyncTask(context, max_id, DisplayMutedInstanceFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); nextElementLoader.setVisibility(View.VISIBLE); + asyncTask = new RetrieveDomainsAsyncTask(context, max_id, DisplayMutedInstanceFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + nextElementLoader.setVisibility(View.VISIBLE); } } else { nextElementLoader.setVisibility(View.GONE); @@ -126,11 +130,12 @@ public class DisplayMutedInstanceFragment extends Fragment implements OnRetrieve firstLoad = true; flag_loading = true; swiped = true; - asyncTask = new RetrieveDomainsAsyncTask(context, max_id, DisplayMutedInstanceFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } + asyncTask = new RetrieveDomainsAsyncTask(context, max_id, DisplayMutedInstanceFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + } }); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: swipeRefreshLayout.setColorSchemeResources(R.color.mastodonC4, R.color.mastodonC2, @@ -154,11 +159,11 @@ public class DisplayMutedInstanceFragment extends Fragment implements OnRetrieve asyncTask = new RetrieveDomainsAsyncTask(context, max_id, DisplayMutedInstanceFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - try { add_new = ((MainActivity) context).findViewById(R.id.add_new); - }catch (Exception ignored){} - if( add_new != null) + } catch (Exception ignored) { + } + if (add_new != null) add_new.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { @@ -167,24 +172,24 @@ public class DisplayMutedInstanceFragment extends Fragment implements OnRetrieve int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, style); LayoutInflater inflater = getLayoutInflater(); - View dialogView = inflater.inflate(R.layout.add_blocked_instance, new LinearLayout(context), false); + View dialogView = inflater.inflate(R.layout.add_blocked_instance, new LinearLayout(context), false); dialogBuilder.setView(dialogView); EditText add_domain = dialogView.findViewById(R.id.add_domain); dialogBuilder.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { - if(add_domain.getText() != null && add_domain.getText().toString().trim().matches("^[\\da-zA-Z.-]+\\.[a-zA-Z.]{2,10}$")){ + if (add_domain.getText() != null && add_domain.getText().toString().trim().matches("^[\\da-zA-Z.-]+\\.[a-zA-Z.]{2,10}$")) { new PostActionAsyncTask(context, API.StatusAction.BLOCK_DOMAIN, add_domain.getText().toString().trim(), DisplayMutedInstanceFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); dialog.dismiss(); - }else{ + } else { Toasty.error(context, context.getString(R.string.toast_empty_content)).show(); } } @@ -197,7 +202,7 @@ public class DisplayMutedInstanceFragment extends Fragment implements OnRetrieve }); AlertDialog alertDialog = dialogBuilder.create(); alertDialog.setTitle(getString(R.string.block_domain)); - if( alertDialog.getWindow() != null ) + if (alertDialog.getWindow() != null) alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); alertDialog.show(); } @@ -207,13 +212,11 @@ public class DisplayMutedInstanceFragment extends Fragment implements OnRetrieve } @Override - public void onCreate(Bundle saveInstance) - { + public void onCreate(Bundle saveInstance) { super.onCreate(saveInstance); } - @Override public void onAttach(Context context) { super.onAttach(context); @@ -222,12 +225,12 @@ public class DisplayMutedInstanceFragment extends Fragment implements OnRetrieve public void onDestroy() { super.onDestroy(); - if(asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) + if (asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) asyncTask.cancel(true); } - public void scrollToTop(){ - if( lv_domains != null) + public void scrollToTop() { + if (lv_domains != null) lv_domains.setAdapter(domainsListAdapter); } @@ -235,26 +238,26 @@ public class DisplayMutedInstanceFragment extends Fragment implements OnRetrieve public void onRetrieveDomains(APIResponse apiResponse) { mainLoader.setVisibility(View.GONE); nextElementLoader.setVisibility(View.GONE); - if( apiResponse.getError() != null){ - Toasty.error(context, apiResponse.getError().getError(),Toast.LENGTH_LONG).show(); + if (apiResponse.getError() != null) { + Toasty.error(context, apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); swipeRefreshLayout.setRefreshing(false); swiped = false; flag_loading = false; return; } - flag_loading = (apiResponse.getMax_id() == null ); + flag_loading = (apiResponse.getMax_id() == null); List domains = apiResponse.getDomains(); - if( !swiped && firstLoad && (domains == null || domains.size() == 0)) + if (!swiped && firstLoad && (domains == null || domains.size() == 0)) textviewNoAction.setVisibility(View.VISIBLE); else textviewNoAction.setVisibility(View.GONE); max_id = apiResponse.getMax_id(); - if( swiped ){ + if (swiped) { domainsListAdapter = new DomainsListAdapter(this.domains, textviewNoAction); lv_domains.setAdapter(domainsListAdapter); swiped = false; } - if( domains != null && domains.size() > 0) { + if (domains != null && domains.size() > 0) { this.domains.addAll(domains); domainsListAdapter.notifyDataSetChanged(); } @@ -270,12 +273,12 @@ public class DisplayMutedInstanceFragment extends Fragment implements OnRetrieve @Override public void onPostAction(int statusCode, API.StatusAction statusAction, String userId, Error error) { - if( error != null){ - Toasty.error(context, error.getError(),Toast.LENGTH_LONG).show(); + if (error != null) { + Toasty.error(context, error.getError(), Toast.LENGTH_LONG).show(); return; } Helper.manageMessageStatusCode(context, statusCode, statusAction); - this.domains.add(0,userId); + this.domains.add(0, userId); domainsListAdapter.notifyItemInserted(0); } } diff --git a/app/src/main/java/app/fedilab/android/fragments/DisplayNotificationsFragment.java b/app/src/main/java/app/fedilab/android/fragments/DisplayNotificationsFragment.java index e49d0fdfe..3e23e0b05 100644 --- a/app/src/main/java/app/fedilab/android/fragments/DisplayNotificationsFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/DisplayNotificationsFragment.java @@ -23,6 +23,7 @@ import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Looper; + import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.core.content.ContextCompat; @@ -65,7 +66,6 @@ import static app.fedilab.android.activities.BaseMainActivity.countNewNotificati public class DisplayNotificationsFragment extends Fragment implements OnRetrieveNotificationsInterface, OnRetrieveMissingNotificationsInterface { - private boolean flag_loading; private Context context; private AsyncTask asyncTask; @@ -83,10 +83,10 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve private BroadcastReceiver receive_action; private BroadcastReceiver receive_data; - public DisplayNotificationsFragment(){ + public DisplayNotificationsFragment() { } - public enum Type{ + public enum Type { ALL, MENTION, FAVORITE, @@ -123,22 +123,21 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve boolean isOnWifi = Helper.isOnWIFI(context); int behaviorWithAttachments = sharedpreferences.getInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ALWAYS); userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - instance = sharedpreferences.getString(Helper.PREF_INSTANCE, context!=null?Helper.getLiveInstance(context):null); - notificationsListAdapter = new NotificationsListAdapter(isOnWifi, behaviorWithAttachments,this.notifications); + instance = sharedpreferences.getString(Helper.PREF_INSTANCE, context != null ? Helper.getLiveInstance(context) : null); + notificationsListAdapter = new NotificationsListAdapter(isOnWifi, behaviorWithAttachments, this.notifications); lv_notifications.setAdapter(notificationsListAdapter); mLayoutManager = new LinearLayoutManager(context); lv_notifications.setLayoutManager(mLayoutManager); lv_notifications.addOnScrollListener(new RecyclerView.OnScrollListener() { - public void onScrolled(RecyclerView recyclerView, int dx, int dy) - { - if(dy > 0) { + public void onScrolled(RecyclerView recyclerView, int dx, int dy) { + if (dy > 0) { int visibleItemCount = mLayoutManager.getChildCount(); int totalItemCount = mLayoutManager.getItemCount(); int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition(); if (firstVisibleItem + visibleItemCount == totalItemCount && context != null) { if (!flag_loading) { flag_loading = true; - asyncTask = new RetrieveNotificationsAsyncTask(context, type,true, null, max_id, DisplayNotificationsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + asyncTask = new RetrieveNotificationsAsyncTask(context, type, true, null, max_id, DisplayNotificationsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); nextElementLoader.setVisibility(View.VISIBLE); } } else { @@ -149,40 +148,40 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve }); - if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { - if (receive_action != null) - LocalBroadcastManager.getInstance(context).unregisterReceiver(receive_action); - receive_action = new BroadcastReceiver() { + if (receive_action != null) + LocalBroadcastManager.getInstance(context).unregisterReceiver(receive_action); + receive_action = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + Bundle b = intent.getExtras(); + assert b != null; + Status status = b.getParcelable("status"); + if (notificationsListAdapter != null && status != null) + notificationsListAdapter.notifyNotificationWithActionChanged(status); + } + }; + LocalBroadcastManager.getInstance(context).registerReceiver(receive_action, new IntentFilter(Helper.RECEIVE_ACTION)); + if (type == Type.ALL) { + if (receive_data != null) + LocalBroadcastManager.getInstance(context).unregisterReceiver(receive_data); + receive_data = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Bundle b = intent.getExtras(); assert b != null; - Status status = b.getParcelable("status"); - if( notificationsListAdapter != null && status != null) - notificationsListAdapter.notifyNotificationWithActionChanged(status); + String userIdService = b.getString("userIdService", null); + if (userIdService != null && userIdService.equals(userId)) { + Notification notification = b.getParcelable("data"); + refresh(notification); + if (context instanceof MainActivity && type == Type.ALL) + ((MainActivity) context).updateNotifCounter(); + } } }; - LocalBroadcastManager.getInstance(context).registerReceiver(receive_action, new IntentFilter(Helper.RECEIVE_ACTION)); - if( type == Type.ALL) { - if (receive_data != null) - LocalBroadcastManager.getInstance(context).unregisterReceiver(receive_data); - receive_data = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - Bundle b = intent.getExtras(); - assert b != null; - String userIdService = b.getString("userIdService", null); - if (userIdService != null && userIdService.equals(userId)) { - Notification notification = b.getParcelable("data"); - refresh(notification); - if (context instanceof MainActivity && type == Type.ALL ) - ((MainActivity) context).updateNotifCounter(); - } - } - }; - LocalBroadcastManager.getInstance(context).registerReceiver(receive_data, new IntentFilter(Helper.RECEIVE_DATA)); - } + LocalBroadcastManager.getInstance(context).registerReceiver(receive_data, new IntentFilter(Helper.RECEIVE_DATA)); + } } swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @@ -190,7 +189,7 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve public void onRefresh() { flag_loading = true; swiped = true; - if(type == Type.ALL) { + if (type == Type.ALL) { countNewNotifications = 0; try { ((MainActivity) context).updateNotifCounter(); @@ -198,15 +197,15 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve } } String sinceId = null; - if( notifications != null && notifications.size() > 0 ) + if (notifications != null && notifications.size() > 0) sinceId = notifications.get(0).getId(); - if( context != null) + if (context != null) asyncTask = new RetrieveMissingNotificationsAsyncTask(context, type, sinceId, DisplayNotificationsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } }); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: swipeRefreshLayout.setColorSchemeResources(R.color.mastodonC4, R.color.mastodonC2, @@ -226,29 +225,26 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve swipeRefreshLayout.setProgressBackgroundColorSchemeColor(ContextCompat.getColor(context, R.color.black_3)); break; } - if( context != null) - asyncTask = new RetrieveNotificationsAsyncTask(context, type,true, null, max_id, DisplayNotificationsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + if (context != null) + asyncTask = new RetrieveNotificationsAsyncTask(context, type, true, null, max_id, DisplayNotificationsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { - if( context != null) - asyncTask = new RetrieveNotificationsAsyncTask(context, type,true, null, max_id, DisplayNotificationsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + if (context != null) + asyncTask = new RetrieveNotificationsAsyncTask(context, type, true, null, max_id, DisplayNotificationsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } }, 500); return rootView; } - @Override - public void onCreate(Bundle saveInstance) - { + public void onCreate(Bundle saveInstance) { super.onCreate(saveInstance); } - @Override public void onAttach(Context context) { super.onAttach(context); @@ -258,18 +254,18 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve @Override public void onDestroy() { super.onDestroy(); - if(asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) + if (asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) asyncTask.cancel(true); - if( receive_action != null) + if (receive_action != null) LocalBroadcastManager.getInstance(context).unregisterReceiver(receive_action); - if( receive_data != null) + if (receive_data != null) LocalBroadcastManager.getInstance(context).unregisterReceiver(receive_data); } @Override public void onDestroyView() { - if( lv_notifications != null) { + if (lv_notifications != null) { lv_notifications.setAdapter(null); } super.onDestroyView(); @@ -284,7 +280,7 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve @Override public void onPause() { super.onPause(); - if (swipeRefreshLayout!=null) { + if (swipeRefreshLayout != null) { swipeRefreshLayout.setEnabled(false); swipeRefreshLayout.setRefreshing(false); swipeRefreshLayout.clearAnimation(); @@ -296,9 +292,9 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve mainLoader.setVisibility(View.GONE); nextElementLoader.setVisibility(View.GONE); String lastReadNotifications = sharedpreferences.getString(Helper.LAST_NOTIFICATION_MAX_ID + userId + instance, null); - if( apiResponse.getError() != null){ + if (apiResponse.getError() != null) { - Toasty.error(context, apiResponse.getError().getError(),Toast.LENGTH_LONG).show(); + Toasty.error(context, apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); flag_loading = false; swipeRefreshLayout.setRefreshing(false); swiped = false; @@ -309,11 +305,11 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve max_id = apiResponse.getMax_id(); List notifications = apiResponse.getNotifications(); - if( !swiped && firstLoad && (notifications == null || notifications.size() == 0)) + if (!swiped && firstLoad && (notifications == null || notifications.size() == 0)) textviewNoAction.setVisibility(View.VISIBLE); else textviewNoAction.setVisibility(View.GONE); - if( swiped ){ + if (swiped) { if (previousPosition > 0) { for (int i = 0; i < previousPosition; i++) { this.notifications.remove(0); @@ -322,10 +318,10 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve } swiped = false; } - if( notifications != null && notifications.size() > 0) { - for(Notification tmpNotification: notifications){ + if (notifications != null && notifications.size() > 0) { + for (Notification tmpNotification : notifications) { - if(type == Type.ALL) { + if (type == Type.ALL) { if (lastReadNotifications != null && tmpNotification.getId().compareTo(lastReadNotifications) > 0) { countNewNotifications++; } @@ -336,38 +332,39 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve } this.notifications.add(tmpNotification); } - if( firstLoad && type == Type.ALL) { + if (firstLoad && type == Type.ALL) { //Update the id of the last notification retrieved - if( MainActivity.lastNotificationId == null || notifications.get(0).getId().compareTo(MainActivity.lastNotificationId) > 0) { + if (MainActivity.lastNotificationId == null || notifications.get(0).getId().compareTo(MainActivity.lastNotificationId) > 0) { MainActivity.lastNotificationId = notifications.get(0).getId(); updateNotificationLastId(notifications.get(0).getId()); } } notificationsListAdapter.notifyItemRangeInserted(previousPosition, notifications.size()); - }else { - if( firstLoad) + } else { + if (firstLoad) textviewNoAction.setVisibility(View.VISIBLE); } - if( firstLoad && type == Type.ALL) - ((MainActivity)context).updateNotifCounter(); + if (firstLoad && type == Type.ALL) + ((MainActivity) context).updateNotifCounter(); swipeRefreshLayout.setRefreshing(false); firstLoad = false; //The initial call comes from a classic tab refresh - flag_loading = (max_id == null ); + flag_loading = (max_id == null); } /** * Called from main activity in onResume to retrieve missing notifications + * * @param sinceId String */ - void retrieveMissingNotifications(String sinceId){ + void retrieveMissingNotifications(String sinceId) { asyncTask = new RetrieveMissingNotificationsAsyncTask(context, type, sinceId, DisplayNotificationsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } @Override public void setMenuVisibility(final boolean visible) { super.setMenuVisibility(visible); - if( context == null) + if (context == null) return; //Store last notification id to avoid to notify for those that have been already seen if (visible && notifications != null && notifications.size() > 0) { @@ -376,8 +373,8 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve } } - public void scrollToTop(){ - if( lv_notifications != null) + public void scrollToTop() { + if (lv_notifications != null) lv_notifications.setAdapter(notificationsListAdapter); //Store last toot id for home timeline to avoid to notify for those that have been already seen if (this.notifications != null && this.notifications.size() > 0) { @@ -385,30 +382,30 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve } } - public void refreshAll(){ - if( context == null) + public void refreshAll() { + if (context == null) return; max_id = null; firstLoad = true; flag_loading = true; swiped = true; - if(type == Type.ALL) { + if (type == Type.ALL) { countNewNotifications = 0; } - asyncTask = new RetrieveNotificationsAsyncTask(context, type,true, null, null, DisplayNotificationsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + asyncTask = new RetrieveNotificationsAsyncTask(context, type, true, null, null, DisplayNotificationsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } - public void refresh(Notification notification){ - if( context == null) + public void refresh(Notification notification) { + if (context == null) return; - if( notification != null){ + if (notification != null) { //Makes sure the notifications is not already displayed - if( !this.notifications.contains(notification)) { + if (!this.notifications.contains(notification)) { //Update the id of the last notification retrieved notifications.add(0, notification); - if( type == Type.ALL) { + if (type == Type.ALL) { MainActivity.lastNotificationId = notification.getId(); countNewNotifications++; try { @@ -428,29 +425,28 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve } - @Override public void onRetrieveMissingNotifications(List notifications) { flag_loading = false; swipeRefreshLayout.setRefreshing(false); - if( this.notifications != null && this.notifications.size() > 0 && swiped){ + if (this.notifications != null && this.notifications.size() > 0 && swiped) { swiped = false; - notificationsListAdapter.notifyItemRangeChanged(0,this.notifications.size()); + notificationsListAdapter.notifyItemRangeChanged(0, this.notifications.size()); } - if( notifications != null && notifications.size() > 0) { - if( type == Type.ALL) { + if (notifications != null && notifications.size() > 0) { + if (type == Type.ALL) { //Update the id of the last notification retrieved - if( MainActivity.lastNotificationId == null || notifications.get(0).getId().compareTo(MainActivity.lastNotificationId) >= 0 ) { + if (MainActivity.lastNotificationId == null || notifications.get(0).getId().compareTo(MainActivity.lastNotificationId) >= 0) { MainActivity.lastNotificationId = notifications.get(0).getId(); updateNotificationLastId(notifications.get(0).getId()); } } - if( textviewNoAction.getVisibility() == View.VISIBLE){ + if (textviewNoAction.getVisibility() == View.VISIBLE) { textviewNoAction.setVisibility(View.GONE); lv_notifications.setVisibility(View.VISIBLE); } int inserted = 0; - for (int i = notifications.size()-1 ; i >= 0 ; i--) { + for (int i = notifications.size() - 1; i >= 0; i--) { if (this.notifications != null && this.notifications.size() == 0 || notifications.get(i).getId().compareTo(this.notifications.get(0).getId()) > 0) { countNewNotifications++; @@ -458,21 +454,22 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve inserted++; } } - notificationsListAdapter.notifyItemRangeInserted(0,inserted); + notificationsListAdapter.notifyItemRangeInserted(0, inserted); try { ((MainActivity) context).updateNotifCounter(); - }catch (Exception ignored){} + } catch (Exception ignored) { + } } } - /** * Records the id of the notification only if its greater than the previous one. + * * @param notificationId String current notification id to check */ - private void updateNotificationLastId(String notificationId){ - if( type == Type.ALL) { + private void updateNotificationLastId(String notificationId) { + if (type == Type.ALL) { String lastNotif = sharedpreferences.getString(Helper.LAST_NOTIFICATION_MAX_ID + userId + instance, null); if (lastNotif == null || notificationId.compareTo(lastNotif) >= 0) { countNewNotifications = 0; @@ -487,11 +484,11 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve /** * Records the id of the notification only if its greater than the previous one. */ - public void updateNotificationRead(){ - if( type == Type.ALL) { + public void updateNotificationRead() { + if (type == Type.ALL) { String lastNotif = sharedpreferences.getString(Helper.LAST_NOTIFICATION_MAX_ID + userId + instance, null); countNewNotifications = 0; - if( this.notifications != null && this.notifications.size() > 0 && this.notifications.get(0).getId().compareTo(lastNotif) > 0) { + if (this.notifications != null && this.notifications.size() > 0 && this.notifications.get(0).getId().compareTo(lastNotif) > 0) { SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(Helper.LAST_NOTIFICATION_MAX_ID + userId + instance, this.notifications.get(0).getId()); editor.apply(); diff --git a/app/src/main/java/app/fedilab/android/fragments/DisplayPeertubeNotificationsFragment.java b/app/src/main/java/app/fedilab/android/fragments/DisplayPeertubeNotificationsFragment.java index 514594dbb..5e6884cf1 100644 --- a/app/src/main/java/app/fedilab/android/fragments/DisplayPeertubeNotificationsFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/DisplayPeertubeNotificationsFragment.java @@ -20,12 +20,14 @@ import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Looper; + import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.core.content.ContextCompat; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -51,8 +53,7 @@ import app.fedilab.android.interfaces.OnRetrievePeertubeNotificationsInterface; * Created by Thomas on 24/01/2019. * Fragment to display peertube notifications */ -public class DisplayPeertubeNotificationsFragment extends Fragment implements OnRetrievePeertubeNotificationsInterface { - +public class DisplayPeertubeNotificationsFragment extends Fragment implements OnRetrievePeertubeNotificationsInterface { private boolean flag_loading; @@ -84,7 +85,7 @@ public class DisplayPeertubeNotificationsFragment extends Fragment implements O public static int NEW_FOLLOW = 10; public static int COMMENT_MENTION = 11; - public DisplayPeertubeNotificationsFragment(){ + public DisplayPeertubeNotificationsFragment() { } @Override @@ -110,22 +111,21 @@ public class DisplayPeertubeNotificationsFragment extends Fragment implements O boolean isOnWifi = Helper.isOnWIFI(context); int behaviorWithAttachments = sharedpreferences.getInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ALWAYS); userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - instance = sharedpreferences.getString(Helper.PREF_INSTANCE, context!=null?Helper.getLiveInstance(context):null); + instance = sharedpreferences.getString(Helper.PREF_INSTANCE, context != null ? Helper.getLiveInstance(context) : null); notificationsListAdapter = new PeertubeNotificationsListAdapter(this.notifications); lv_notifications.setAdapter(notificationsListAdapter); mLayoutManager = new LinearLayoutManager(context); lv_notifications.setLayoutManager(mLayoutManager); lv_notifications.addOnScrollListener(new RecyclerView.OnScrollListener() { - public void onScrolled(RecyclerView recyclerView, int dx, int dy) - { - if(dy > 0) { + public void onScrolled(RecyclerView recyclerView, int dx, int dy) { + if (dy > 0) { int visibleItemCount = mLayoutManager.getChildCount(); int totalItemCount = mLayoutManager.getItemCount(); int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition(); if (firstVisibleItem + visibleItemCount == totalItemCount && context != null) { if (!flag_loading) { flag_loading = true; - asyncTask = new RetrievePeertubeNotificationsAsyncTask(context, null, max_id, DisplayPeertubeNotificationsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + asyncTask = new RetrievePeertubeNotificationsAsyncTask(context, null, max_id, DisplayPeertubeNotificationsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); nextElementLoader.setVisibility(View.VISIBLE); } } else { @@ -145,15 +145,16 @@ public class DisplayPeertubeNotificationsFragment extends Fragment implements O swiped = true; try { ((MainActivity) context).updateNotifCounter(); - }catch (Exception ignored){} - if( context != null) { + } catch (Exception ignored) { + } + if (context != null) { asyncTask = new RetrievePeertubeNotificationsAsyncTask(context, null, max_id, DisplayPeertubeNotificationsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } }); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: swipeRefreshLayout.setColorSchemeResources(R.color.mastodonC4, R.color.mastodonC2, @@ -173,29 +174,26 @@ public class DisplayPeertubeNotificationsFragment extends Fragment implements O swipeRefreshLayout.setProgressBackgroundColorSchemeColor(ContextCompat.getColor(context, R.color.black_3)); break; } - if( context != null) - asyncTask = new RetrievePeertubeNotificationsAsyncTask(context, null, max_id, DisplayPeertubeNotificationsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + if (context != null) + asyncTask = new RetrievePeertubeNotificationsAsyncTask(context, null, max_id, DisplayPeertubeNotificationsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { - if( context != null) - asyncTask = new RetrievePeertubeNotificationsAsyncTask(context, null, max_id, DisplayPeertubeNotificationsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + if (context != null) + asyncTask = new RetrievePeertubeNotificationsAsyncTask(context, null, max_id, DisplayPeertubeNotificationsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } }, 500); return rootView; } - @Override - public void onCreate(Bundle saveInstance) - { + public void onCreate(Bundle saveInstance) { super.onCreate(saveInstance); } - @Override public void onAttach(Context context) { super.onAttach(context); @@ -204,15 +202,14 @@ public class DisplayPeertubeNotificationsFragment extends Fragment implements O public void onDestroy() { super.onDestroy(); - if(asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) + if (asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) asyncTask.cancel(true); } - - public void scrollToTop(){ - if( lv_notifications != null) + public void scrollToTop() { + if (lv_notifications != null) lv_notifications.setAdapter(notificationsListAdapter); //Store last toot id for home timeline to avoid to notify for those that have been already seen if (this.notifications != null && this.notifications.size() > 0) { @@ -220,31 +217,26 @@ public class DisplayPeertubeNotificationsFragment extends Fragment implements O } } - public void refreshAll(){ - if( context == null) + public void refreshAll() { + if (context == null) return; max_id = null; firstLoad = true; flag_loading = true; swiped = true; - asyncTask = new RetrievePeertubeNotificationsAsyncTask(context, null, null, DisplayPeertubeNotificationsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + asyncTask = new RetrievePeertubeNotificationsAsyncTask(context, null, null, DisplayPeertubeNotificationsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } - - - - - - /** * Records the id of the notification only if its greater than the previous one. + * * @param notificationId String current notification id to check */ - private void updateNotificationLastId(String notificationId){ + private void updateNotificationLastId(String notificationId) { String lastNotif = sharedpreferences.getString(Helper.LAST_NOTIFICATION_MAX_ID + userId + instance, null); - if( lastNotif == null || notificationId.compareTo(lastNotif) > 0){ + if (lastNotif == null || notificationId.compareTo(lastNotif) > 0) { SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(Helper.LAST_NOTIFICATION_MAX_ID + userId + instance, notificationId); editor.apply(); @@ -256,8 +248,8 @@ public class DisplayPeertubeNotificationsFragment extends Fragment implements O mainLoader.setVisibility(View.GONE); nextElementLoader.setVisibility(View.GONE); String lastReadNotifications = sharedpreferences.getString(Helper.LAST_NOTIFICATION_MAX_ID + userId + instance, null); - if( apiResponse.getError() != null){ - Toasty.error(context, apiResponse.getError().getError(),Toast.LENGTH_LONG).show(); + if (apiResponse.getError() != null) { + Toasty.error(context, apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); flag_loading = false; swipeRefreshLayout.setRefreshing(false); swiped = false; @@ -268,11 +260,11 @@ public class DisplayPeertubeNotificationsFragment extends Fragment implements O max_id = apiResponse.getMax_id(); List notifications = apiResponse.getPeertubeNotifications(); - if( !swiped && firstLoad && (notifications == null || notifications.size() == 0)) + if (!swiped && firstLoad && (notifications == null || notifications.size() == 0)) textviewNoAction.setVisibility(View.VISIBLE); else textviewNoAction.setVisibility(View.GONE); - if( swiped ){ + if (swiped) { if (previousPosition > 0) { for (int i = 0; i < previousPosition; i++) { this.notifications.remove(0); @@ -282,30 +274,31 @@ public class DisplayPeertubeNotificationsFragment extends Fragment implements O swiped = false; } - if( notifications != null && notifications.size() > 0) { - for(PeertubeNotification tmpNotification: notifications){ + if (notifications != null && notifications.size() > 0) { + for (PeertubeNotification tmpNotification : notifications) { try { ((MainActivity) context).updateNotifCounter(); - }catch (Exception ignored){} + } catch (Exception ignored) { + } this.notifications.add(tmpNotification); } - if( firstLoad) { + if (firstLoad) { //Update the id of the last notification retrieved - if( MainActivity.lastNotificationId == null || notifications.get(0).getId().compareTo(MainActivity.lastNotificationId) > 0) + if (MainActivity.lastNotificationId == null || notifications.get(0).getId().compareTo(MainActivity.lastNotificationId) > 0) MainActivity.lastNotificationId = notifications.get(0).getId(); updateNotificationLastId(notifications.get(0).getId()); } notificationsListAdapter.notifyItemRangeInserted(previousPosition, notifications.size()); - }else { - if( firstLoad) + } else { + if (firstLoad) textviewNoAction.setVisibility(View.VISIBLE); } - if( firstLoad ) - ((MainActivity)context).updateNotifCounter(); + if (firstLoad) + ((MainActivity) context).updateNotifCounter(); swipeRefreshLayout.setRefreshing(false); firstLoad = false; //The initial call comes from a classic tab refresh - flag_loading = (max_id == null ); + flag_loading = (max_id == null); } } diff --git a/app/src/main/java/app/fedilab/android/fragments/DisplayPlaylistsFragment.java b/app/src/main/java/app/fedilab/android/fragments/DisplayPlaylistsFragment.java index 517ad23bc..143cabedb 100644 --- a/app/src/main/java/app/fedilab/android/fragments/DisplayPlaylistsFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/DisplayPlaylistsFragment.java @@ -22,11 +22,15 @@ import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; + import androidx.annotation.NonNull; + import com.google.android.material.floatingactionbutton.FloatingActionButton; + import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import androidx.appcompat.app.AlertDialog; + import android.text.InputFilter; import android.view.LayoutInflater; import android.view.View; @@ -47,6 +51,7 @@ import net.gotev.uploadservice.ServerResponse; import net.gotev.uploadservice.UploadInfo; import net.gotev.uploadservice.UploadNotificationConfig; import net.gotev.uploadservice.UploadStatusDelegate; + import java.net.MalformedURLException; import java.util.ArrayList; import java.util.HashMap; @@ -111,18 +116,19 @@ public class DisplayPlaylistsFragment extends Fragment implements OnPlaylistActi playlists = new ArrayList<>(); playlistAdapter = new PlaylistAdapter(context, playlists, textviewNoAction); lv_playlist.setAdapter(playlistAdapter); - asyncTask = new ManagePlaylistsAsyncTask(context, ManagePlaylistsAsyncTask.action.GET_PLAYLIST, null, null, null,DisplayPlaylistsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + asyncTask = new ManagePlaylistsAsyncTask(context, ManagePlaylistsAsyncTask.action.GET_PLAYLIST, null, null, null, DisplayPlaylistsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); try { add_new = ((MainActivity) context).findViewById(R.id.add_new); - }catch (Exception ignored){} + } catch (Exception ignored) { + } LinkedHashMap translations = null; - if( peertubeInformation != null && peertubeInformation.getTranslations() != null) + if (peertubeInformation != null && peertubeInformation.getTranslations() != null) translations = new LinkedHashMap<>(peertubeInformation.getTranslations()); LinkedHashMap privaciesInit = new LinkedHashMap<>(peertubeInformation.getPrivacies()); - Map.Entry entryInt = privaciesInit.entrySet().iterator().next(); + Map.Entry entryInt = privaciesInit.entrySet().iterator().next(); privacyToSend = new HashMap<>(); privacyToSend.put(entryInt.getKey(), entryInt.getValue()); LinkedHashMap privacies = new LinkedHashMap<>(peertubeInformation.getPrivacies()); @@ -131,19 +137,17 @@ public class DisplayPlaylistsFragment extends Fragment implements OnPlaylistActi Iterator it = privacies.entrySet().iterator(); int i = 0; while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - if( translations == null || translations.size() == 0 || !translations.containsKey((String)pair.getValue())) - privaciesA[i] = (String)pair.getValue(); + Map.Entry pair = (Map.Entry) it.next(); + if (translations == null || translations.size() == 0 || !translations.containsKey((String) pair.getValue())) + privaciesA[i] = (String) pair.getValue(); else - privaciesA[i] = translations.get((String)pair.getValue()); + privaciesA[i] = translations.get((String) pair.getValue()); it.remove(); i++; } - - - if( add_new != null){ + if (add_new != null) { add_new.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { @@ -152,14 +156,14 @@ public class DisplayPlaylistsFragment extends Fragment implements OnPlaylistActi int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, style); - LayoutInflater inflater = ((Activity)context).getLayoutInflater(); - View dialogView = inflater.inflate(R.layout.add_playlist, new LinearLayout(context), false); + LayoutInflater inflater = ((Activity) context).getLayoutInflater(); + View dialogView = inflater.inflate(R.layout.add_playlist, new LinearLayout(context), false); dialogBuilder.setView(dialogView); EditText display_name = dialogView.findViewById(R.id.display_name); EditText description = dialogView.findViewById(R.id.description); @@ -178,27 +182,27 @@ public class DisplayPlaylistsFragment extends Fragment implements OnPlaylistActi @Override public void onClick(DialogInterface dialog, int id) { - if( display_name.getText() != null && display_name.getText().toString().trim().length() > 0 ) { + if (display_name.getText() != null && display_name.getText().toString().trim().length() > 0) { Playlist playlist = new Playlist(); playlist.setDisplayName(display_name.getText().toString().trim()); - if( description.getText() != null && description.getText().toString().trim().length() > 0 ){ + if (description.getText() != null && description.getText().toString().trim().length() > 0) { playlist.setDescription(description.getText().toString().trim()); } String idChannel = null; - if( channelToSend != null ) { + if (channelToSend != null) { Map.Entry channelM = channelToSend.entrySet().iterator().next(); idChannel = channelM.getValue(); - if( idChannel.length() > 0) + if (idChannel.length() > 0) playlist.setVideoChannelId(idChannel); } - Map.Entry privacyM = privacyToSend.entrySet().iterator().next(); + Map.Entry privacyM = privacyToSend.entrySet().iterator().next(); String label = privacyM.getValue(); String idPrivacy = String.valueOf(privacyM.getKey()); - if( label.equals("Public") && (playlist.getVideoChannelId() == null || playlist.getVideoChannelId().equals(""))){ - Toasty.error(context, context.getString(R.string.error_channel_mandatory),Toast.LENGTH_LONG).show(); - }else{ - if( privacyToSend != null){ + if (label.equals("Public") && (playlist.getVideoChannelId() == null || playlist.getVideoChannelId().equals(""))) { + Toasty.error(context, context.getString(R.string.error_channel_mandatory), Toast.LENGTH_LONG).show(); + } else { + if (privacyToSend != null) { playlist.setPrivacy(privacyToSend); } //new ManagePlaylistsAsyncTask(context, ManagePlaylistsAsyncTask.action.CREATE_PLAYLIST, playlist, null, null, DisplayPlaylistsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); @@ -210,7 +214,7 @@ public class DisplayPlaylistsFragment extends Fragment implements OnPlaylistActi //.addFileToUpload(uri.toString().replace("file://",""), "videofile") .addHeader("Authorization", "Bearer " + token) .setNotificationConfig(uploadConfig) - // .addParameter("name", filename) + // .addParameter("name", filename) .addParameter("videoChannelId", idChannel) .addParameter("privacy", idPrivacy) .addParameter("displayName", playlist.getDisplayName()) @@ -232,11 +236,11 @@ public class DisplayPlaylistsFragment extends Fragment implements OnPlaylistActi @Override public void onCompleted(Context context, UploadInfo uploadInfo, ServerResponse serverResponse) { DisplayPlaylistsFragment displayPlaylistsFragment; - if( getActivity() == null) + if (getActivity() == null) return; displayPlaylistsFragment = (DisplayPlaylistsFragment) getActivity().getSupportFragmentManager().findFragmentByTag("PLAYLISTS"); final FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction(); - if( displayPlaylistsFragment != null) { + if (displayPlaylistsFragment != null) { ft.detach(displayPlaylistsFragment); ft.attach(displayPlaylistsFragment); ft.commit(); @@ -256,8 +260,8 @@ public class DisplayPlaylistsFragment extends Fragment implements OnPlaylistActi dialog.dismiss(); add_new.setEnabled(false); } - }else{ - Toasty.error(context, context.getString(R.string.error_display_name),Toast.LENGTH_LONG).show(); + } else { + Toasty.error(context, context.getString(R.string.error_display_name), Toast.LENGTH_LONG).show(); } } @@ -281,7 +285,7 @@ public class DisplayPlaylistsFragment extends Fragment implements OnPlaylistActi imm.hideSoftInputFromWindow(display_name.getWindowToken(), 0); } }); - if( alertDialog.getWindow() != null ) + if (alertDialog.getWindow() != null) alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); alertDialog.show(); } @@ -291,10 +295,8 @@ public class DisplayPlaylistsFragment extends Fragment implements OnPlaylistActi } - @Override - public void onCreate(Bundle saveInstance) - { + public void onCreate(Bundle saveInstance) { super.onCreate(saveInstance); } @@ -307,23 +309,21 @@ public class DisplayPlaylistsFragment extends Fragment implements OnPlaylistActi public void onDestroy() { super.onDestroy(); - if(asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) + if (asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) asyncTask.cancel(true); } - - @Override public void onActionDone(ManagePlaylistsAsyncTask.action actionType, APIResponse apiResponse, int statusCode) { mainLoader.setVisibility(View.GONE); add_new.setEnabled(true); - if( apiResponse.getError() != null){ - Toasty.error(context, apiResponse.getError().getError(),Toast.LENGTH_LONG).show(); + if (apiResponse.getError() != null) { + Toasty.error(context, apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); return; } - if( actionType == ManagePlaylistsAsyncTask.action.GET_PLAYLIST) { + if (actionType == ManagePlaylistsAsyncTask.action.GET_PLAYLIST) { if (apiResponse.getPlaylists() != null && apiResponse.getPlaylists().size() > 0) { this.playlists.addAll(apiResponse.getPlaylists()); playlistAdapter.notifyDataSetChanged(); @@ -331,7 +331,7 @@ public class DisplayPlaylistsFragment extends Fragment implements OnPlaylistActi } else { textviewNoAction.setVisibility(View.VISIBLE); } - }else if( actionType == ManagePlaylistsAsyncTask.action.CREATE_PLAYLIST){ + } else if (actionType == ManagePlaylistsAsyncTask.action.CREATE_PLAYLIST) { if (apiResponse.getPlaylists() != null && apiResponse.getPlaylists().size() > 0) { Intent intent = new Intent(context, PlaylistsActivity.class); Bundle b = new Bundle(); @@ -341,11 +341,11 @@ public class DisplayPlaylistsFragment extends Fragment implements OnPlaylistActi this.playlists.add(0, apiResponse.getPlaylists().get(0)); playlistAdapter.notifyDataSetChanged(); textviewNoAction.setVisibility(View.GONE); - }else{ - Toasty.error(context, apiResponse.getError().getError(),Toast.LENGTH_LONG).show(); + } else { + Toasty.error(context, apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); } - }else if( actionType == ManagePlaylistsAsyncTask.action.DELETE_PLAYLIST){ - if( this.playlists.size() == 0) + } else if (actionType == ManagePlaylistsAsyncTask.action.DELETE_PLAYLIST) { + if (this.playlists.size() == 0) textviewNoAction.setVisibility(View.VISIBLE); } } @@ -373,14 +373,14 @@ public class DisplayPlaylistsFragment extends Fragment implements OnPlaylistActi //Populate channels List accounts = apiResponse.getAccounts(); - String[] channelName = new String[accounts.size()+1]; - String[] channelId= new String[accounts.size()+1]; + String[] channelName = new String[accounts.size() + 1]; + String[] channelId = new String[accounts.size() + 1]; int i = 1; channelName[0] = ""; channelId[0] = ""; channels = new HashMap<>(); - for(Account account: accounts){ - channels.put(account.getUsername(),account.getId()); + for (Account account : accounts) { + channels.put(account.getUsername(), account.getId()); channelName[i] = account.getUsername(); channelId[i] = account.getId(); i++; @@ -446,10 +446,10 @@ public class DisplayPlaylistsFragment extends Fragment implements OnPlaylistActi Iterator it = channelsCheck.entrySet().iterator(); int i = 0; while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - if( i == position){ + Map.Entry pair = (Map.Entry) it.next(); + if (i == position) { channelToSend = new HashMap<>(); - channelToSend.put((String)pair.getKey(), (String)pair.getValue()); + channelToSend.put((String) pair.getKey(), (String) pair.getValue()); break; } it.remove(); diff --git a/app/src/main/java/app/fedilab/android/fragments/DisplayScheduledTootsFragment.java b/app/src/main/java/app/fedilab/android/fragments/DisplayScheduledTootsFragment.java index 45e0cc792..96bd9669c 100644 --- a/app/src/main/java/app/fedilab/android/fragments/DisplayScheduledTootsFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/DisplayScheduledTootsFragment.java @@ -26,8 +26,10 @@ import android.os.Build; import android.os.Bundle; import android.os.PowerManager; import android.provider.Settings; + import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; + import android.text.Html; import android.text.Spanned; import android.view.LayoutInflater; @@ -76,7 +78,7 @@ public class DisplayScheduledTootsFragment extends Fragment implements OnRetriev private boolean firstCall; private ScheduledTootsListAdapter scheduledTootsListAdapter; - public enum typeOfSchedule{ + public enum typeOfSchedule { TOOT, BOOST, SERVER @@ -90,7 +92,7 @@ public class DisplayScheduledTootsFragment extends Fragment implements OnRetriev Bundle bundle = this.getArguments(); assert bundle != null; type = (typeOfSchedule) bundle.get("type"); - if( type == null) + if (type == null) type = typeOfSchedule.TOOT; lv_scheduled_toots = rootView.findViewById(R.id.lv_scheduled_toots); firstCall = true; @@ -101,11 +103,11 @@ public class DisplayScheduledTootsFragment extends Fragment implements OnRetriev storedStatuses = new ArrayList<>(); //Removes all scheduled toots that have sent SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - if( type == typeOfSchedule.TOOT) + if (type == typeOfSchedule.TOOT) new StatusStoredDAO(context, db).removeAllSent(); - else if( type == typeOfSchedule.BOOST) + else if (type == typeOfSchedule.BOOST) new BoostScheduleDAO(context, db).removeAllSent(); - else if( type == typeOfSchedule.SERVER) + else if (type == typeOfSchedule.SERVER) asyncTask = new RetrieveFeedsAsyncTask(context, RetrieveFeedsAsyncTask.Type.SCHEDULED_TOOTS, null, DisplayScheduledTootsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); scheduledTootsListAdapter = new ScheduledTootsListAdapter(context, type, storedStatuses, textviewNoAction); @@ -115,17 +117,17 @@ public class DisplayScheduledTootsFragment extends Fragment implements OnRetriev @Override public void onRetrieveFeeds(APIResponse apiResponse) { - if( apiResponse.getError() != null && apiResponse.getError().getStatusCode() != 404 ){ + if (apiResponse.getError() != null && apiResponse.getError().getStatusCode() != 404) { Toasty.error(context, apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); return; } mainLoader.setVisibility(View.GONE); - if(apiResponse.getStoredStatuses() != null && apiResponse.getStoredStatuses().size() > 0 ){ + if (apiResponse.getStoredStatuses() != null && apiResponse.getStoredStatuses().size() > 0) { storedStatuses.addAll(apiResponse.getStoredStatuses()); textviewNoAction.setVisibility(View.GONE); lv_scheduled_toots.setVisibility(View.VISIBLE); scheduledTootsListAdapter.notifyDataSetChanged(); - }else if( firstCall){ + } else if (firstCall) { textviewNoAction.setVisibility(View.VISIBLE); lv_scheduled_toots.setVisibility(View.GONE); } @@ -133,9 +135,9 @@ public class DisplayScheduledTootsFragment extends Fragment implements OnRetriev } @Override - public void onResume(){ + public void onResume() { super.onResume(); - if( type != null && type != typeOfSchedule.SERVER) { + if (type != null && type != typeOfSchedule.SERVER) { //Retrieves scheduled toots asyncTask = new RetrieveScheduledTootsAsyncTask(context, type, DisplayScheduledTootsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { @@ -192,8 +194,7 @@ public class DisplayScheduledTootsFragment extends Fragment implements OnRetriev } @Override - public void onCreate(Bundle saveInstance) - { + public void onCreate(Bundle saveInstance) { super.onCreate(saveInstance); } @@ -206,7 +207,7 @@ public class DisplayScheduledTootsFragment extends Fragment implements OnRetriev public void onDestroy() { super.onDestroy(); - if(asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) + if (asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) asyncTask.cancel(true); } @@ -215,13 +216,13 @@ public class DisplayScheduledTootsFragment extends Fragment implements OnRetriev public void onRetrieveScheduledToots(List storedStatuses) { mainLoader.setVisibility(View.GONE); - if( storedStatuses != null && storedStatuses.size() > 0 ){ + if (storedStatuses != null && storedStatuses.size() > 0) { scheduledTootsListAdapter = new ScheduledTootsListAdapter(context, type, storedStatuses, textviewNoAction); lv_scheduled_toots.setAdapter(scheduledTootsListAdapter); textviewNoAction.setVisibility(View.GONE); - }else { + } else { textviewNoAction.setVisibility(View.VISIBLE); - if( type == typeOfSchedule.BOOST) { + if (type == typeOfSchedule.BOOST) { TextView no_action_text = textviewNoAction.findViewById(R.id.no_action_text); TextView no_action_text_subtitle = textviewNoAction.findViewById(R.id.no_action_text_subtitle); no_action_text.setText(context.getString(R.string.no_scheduled_boosts)); diff --git a/app/src/main/java/app/fedilab/android/fragments/DisplaySearchFragment.java b/app/src/main/java/app/fedilab/android/fragments/DisplaySearchFragment.java index 0ee21604e..bc8c8dcc3 100644 --- a/app/src/main/java/app/fedilab/android/fragments/DisplaySearchFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/DisplaySearchFragment.java @@ -21,10 +21,14 @@ import android.content.Intent; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; + import androidx.annotation.NonNull; + import com.google.android.material.floatingactionbutton.FloatingActionButton; + import androidx.fragment.app.Fragment; import androidx.appcompat.app.AlertDialog; + import android.text.InputFilter; import android.view.LayoutInflater; import android.view.View; @@ -73,20 +77,21 @@ public class DisplaySearchFragment extends Fragment { mainLoader.setVisibility(View.VISIBLE); final SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); searches = new SearchDAO(context, db).getAllSearch(); - if( searches == null) + if (searches == null) searches = new ArrayList<>(); searchTootsListAdapter = new SearchTootsListAdapter(context, searches, textviewNoAction); lv_search_toots.setAdapter(searchTootsListAdapter); searchTootsListAdapter.notifyDataSetChanged(); - if( searches.size() == 0) { + if (searches.size() == 0) { textviewNoAction.setVisibility(View.VISIBLE); } mainLoader.setVisibility(View.GONE); FloatingActionButton add_new = null; try { add_new = ((MainActivity) context).findViewById(R.id.add_new); - }catch (Exception ignored){} - if( add_new != null) + } catch (Exception ignored) { + } + if (add_new != null) add_new.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { @@ -95,14 +100,14 @@ public class DisplaySearchFragment extends Fragment { int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, style); LayoutInflater inflater = getLayoutInflater(); - View dialogView = inflater.inflate(R.layout.search_toot, new LinearLayout(context), false); + View dialogView = inflater.inflate(R.layout.search_toot, new LinearLayout(context), false); dialogBuilder.setView(dialogView); final EditText editText = dialogView.findViewById(R.id.search_toot); editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(30)}); @@ -110,19 +115,19 @@ public class DisplaySearchFragment extends Fragment { @Override public void onClick(DialogInterface dialog, int id) { String keyword = editText.getText().toString().trim(); - keyword= keyword.replaceAll("^#+", ""); + keyword = keyword.replaceAll("^#+", ""); //Empty - if( keyword.length() == 0) + if (keyword.length() == 0) return; //Already in db List s_ = new SearchDAO(context, db).getSearchByKeyword(keyword); - if( s_ == null) + if (s_ == null) s_ = new ArrayList<>(); - if( s_.size() > 0){ + if (s_.size() > 0) { return; } new SearchDAO(context, db).insertSearch(keyword); - if( getActivity() != null) + if (getActivity() != null) getActivity().recreate(); Intent intent = new Intent(context, MainActivity.class); intent.putExtra(Helper.INTENT_ACTION, Helper.SEARCH_TAG); @@ -140,7 +145,7 @@ public class DisplaySearchFragment extends Fragment { imm.hideSoftInputFromWindow(editText.getWindowToken(), 0); } }); - if( alertDialog.getWindow() != null ) + if (alertDialog.getWindow() != null) alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); alertDialog.show(); } @@ -150,8 +155,7 @@ public class DisplaySearchFragment extends Fragment { @Override - public void onCreate(Bundle saveInstance) - { + public void onCreate(Bundle saveInstance) { super.onCreate(saveInstance); } diff --git a/app/src/main/java/app/fedilab/android/fragments/DisplaySearchTagsFragment.java b/app/src/main/java/app/fedilab/android/fragments/DisplaySearchTagsFragment.java index d46eae5e9..e5911957b 100644 --- a/app/src/main/java/app/fedilab/android/fragments/DisplaySearchTagsFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/DisplaySearchTagsFragment.java @@ -18,17 +18,20 @@ import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; + import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.core.content.ContextCompat; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.Toast; + import java.util.ArrayList; import java.util.List; @@ -42,7 +45,6 @@ import app.fedilab.android.asynctasks.RetrieveSearchAsyncTask; import app.fedilab.android.interfaces.OnRetrieveSearchInterface; - /** * Created by Thomas on 31/03/2019. * Fragment to display tags @@ -94,7 +96,7 @@ public class DisplaySearchTagsFragment extends Fragment implements OnRetrieveSea lv_search_tags.setLayoutManager(mLayoutManager); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: swipeRefreshLayout.setColorSchemeResources(R.color.mastodonC4, R.color.mastodonC2, @@ -122,41 +124,40 @@ public class DisplaySearchTagsFragment extends Fragment implements OnRetrieveSea tags = new ArrayList<>(); max_id = "0"; searchTagsAdapter.notifyItemRangeRemoved(0, size); - if( search != null) { - new RetrieveSearchAsyncTask(context, search, API.searchType.TAGS, null,DisplaySearchTagsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + if (search != null) { + new RetrieveSearchAsyncTask(context, search, API.searchType.TAGS, null, DisplaySearchTagsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } }); lv_search_tags.addOnScrollListener(new RecyclerView.OnScrollListener() { - public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) - { - int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition(); - if(dy > 0){ - int visibleItemCount = mLayoutManager.getChildCount(); - int totalItemCount = mLayoutManager.getItemCount(); - if(firstVisibleItem + visibleItemCount == totalItemCount && context != null) { - if(!flag_loading ) { - flag_loading = true; - if( search != null) { - new RetrieveSearchAsyncTask(context, search, API.searchType.TAGS, max_id, DisplaySearchTagsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { + int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition(); + if (dy > 0) { + int visibleItemCount = mLayoutManager.getChildCount(); + int totalItemCount = mLayoutManager.getItemCount(); + if (firstVisibleItem + visibleItemCount == totalItemCount && context != null) { + if (!flag_loading) { + flag_loading = true; + if (search != null) { + new RetrieveSearchAsyncTask(context, search, API.searchType.TAGS, max_id, DisplaySearchTagsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + } + loading_next_tags.setVisibility(View.VISIBLE); } - loading_next_tags.setVisibility(View.VISIBLE); + } else { + loading_next_tags.setVisibility(View.GONE); } - } else { - loading_next_tags.setVisibility(View.GONE); } } - } }); - if( search != null) { + if (search != null) { new RetrieveSearchAsyncTask(context, search, API.searchType.TAGS, null, DisplaySearchTagsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } return rootView; } - public void scrollToTop(){ - if( lv_search_tags != null && searchTagsAdapter != null) { + public void scrollToTop() { + if (lv_search_tags != null && searchTagsAdapter != null) { lv_search_tags.setAdapter(searchTagsAdapter); } } @@ -169,7 +170,7 @@ public class DisplaySearchTagsFragment extends Fragment implements OnRetrieveSea @Override public void onDestroyView() { - if( lv_search_tags != null) { + if (lv_search_tags != null) { lv_search_tags.setAdapter(null); } super.onDestroyView(); @@ -189,25 +190,25 @@ public class DisplaySearchTagsFragment extends Fragment implements OnRetrieveSea loader.setVisibility(View.GONE); swipeRefreshLayout.setRefreshing(false); if (apiResponse.getError() != null) { - if( apiResponse.getError().getError() != null) + if (apiResponse.getError().getError() != null) Toasty.error(context, apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); else Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); return; } - if(max_id == null) + if (max_id == null) max_id = "0"; max_id = String.valueOf(Integer.valueOf(max_id) + 20); lv_search_tags.setVisibility(View.VISIBLE); List newTags = new ArrayList<>(); - if( apiResponse.getResults() != null) { + if (apiResponse.getResults() != null) { newTags = apiResponse.getResults().getHashtags(); } tags.addAll(newTags); SearchTagsAdapter searchTagsAdapter = new SearchTagsAdapter(tags); lv_search_tags.setAdapter(searchTagsAdapter); searchTagsAdapter.notifyDataSetChanged(); - if( newTags.size() == 0 && tags.size() == 0 ) + if (newTags.size() == 0 && tags.size() == 0) textviewNoAction.setVisibility(View.VISIBLE); else textviewNoAction.setVisibility(View.GONE); diff --git a/app/src/main/java/app/fedilab/android/fragments/DisplayStatusFragment.java b/app/src/main/java/app/fedilab/android/fragments/DisplayStatusFragment.java index 8de79a41c..d03e69acb 100644 --- a/app/src/main/java/app/fedilab/android/fragments/DisplayStatusFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/DisplayStatusFragment.java @@ -25,6 +25,7 @@ import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Looper; + import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.core.content.ContextCompat; @@ -124,11 +125,12 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn private boolean ischannel; private boolean ownVideos; private BroadcastReceiver receive_action; - private BroadcastReceiver receive_data; + private BroadcastReceiver receive_data; private Date lastReadTootDate, initialBookMarkDate, updatedBookMarkDate; private int timelineId; private String currentfilter; - public DisplayStatusFragment(){ + + public DisplayStatusFragment() { } @Override @@ -149,26 +151,26 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn targetedId = bundle.getString("targetedid", null); ownVideos = bundle.getBoolean("ownvideos", false); //Peetube account watching its videos tag = bundle.getString("tag", null); - showMediaOnly = bundle.getBoolean("showMediaOnly",false); - showPinned = bundle.getBoolean("showPinned",false); - showReply = bundle.getBoolean("showReply",false); + showMediaOnly = bundle.getBoolean("showMediaOnly", false); + showPinned = bundle.getBoolean("showPinned", false); + showReply = bundle.getBoolean("showReply", false); remoteInstance = bundle.getString("remote_instance", ""); search_peertube = bundle.getString("search_peertube", null); remote_channel_name = bundle.getString("remote_channel_name", null); - instanceType = bundle.getString("instanceType", "MASTODON"); - ischannel = bundle.getBoolean("ischannel",false); + instanceType = bundle.getString("instanceType", "MASTODON"); + ischannel = bundle.getBoolean("ischannel", false); timelineId = bundle.getInt("timelineId"); currentfilter = bundle.getString("currentfilter", null); } - if( ischannel) + if (ischannel) type = RetrieveFeedsAsyncTask.Type.CHANNEL; SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); //instanceType should not be null only for Peertube accounts - if( remoteInstance != null && !remoteInstance.equals("") && instanceType == null){ + if (remoteInstance != null && !remoteInstance.equals("") && instanceType == null) { List remoteInstanceObj = new InstancesDAO(context, db).getInstanceByName(remoteInstance); - if( remoteInstanceObj != null && remoteInstanceObj.size() > 0) + if (remoteInstanceObj != null && remoteInstanceObj.size() > 0) instanceType = remoteInstanceObj.get(0).getType(); } isSwipped = false; @@ -182,50 +184,50 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn boolean isOnWifi = Helper.isOnWIFI(context); swipeRefreshLayout = rootView.findViewById(R.id.swipeContainer); lv_status = rootView.findViewById(R.id.lv_status); - mainLoader = rootView.findViewById(R.id.loader); + mainLoader = rootView.findViewById(R.id.loader); nextElementLoader = rootView.findViewById(R.id.loading_next_status); - textviewNoAction = rootView.findViewById(R.id.no_action); + textviewNoAction = rootView.findViewById(R.id.no_action); textviewNoActionText = rootView.findViewById(R.id.no_action_text); mainLoader.setVisibility(View.VISIBLE); nextElementLoader.setVisibility(View.GONE); userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - instance = sharedpreferences.getString(Helper.PREF_INSTANCE, context!=null?Helper.getLiveInstance(context):null); + instance = sharedpreferences.getString(Helper.PREF_INSTANCE, context != null ? Helper.getLiveInstance(context) : null); //For Home timeline, fetch stored values for bookmark and last read toot - if( type == RetrieveFeedsAsyncTask.Type.HOME) { + if (type == RetrieveFeedsAsyncTask.Type.HOME) { initialBookMark = sharedpreferences.getString(Helper.BOOKMARK_ID + userId + instance, null); - initialBookMarkDate = Helper.stringToDate(context, sharedpreferences.getString(Helper.BOOKMARK_DATE + userId + instance, null)); + initialBookMarkDate = Helper.stringToDate(context, sharedpreferences.getString(Helper.BOOKMARK_DATE + userId + instance, null)); lastReadToot = sharedpreferences.getString(Helper.LAST_READ_TOOT_ID + userId + instance, null); - lastReadTootDate = Helper.stringToDate(context, sharedpreferences.getString(Helper.LAST_READ_TOOT_DATE + userId + instance, null)); + lastReadTootDate = Helper.stringToDate(context, sharedpreferences.getString(Helper.LAST_READ_TOOT_DATE + userId + instance, null)); } - if( instanceType == null || instanceType.equals("MASTODON") || instanceType.equals("MISSKEY") || instanceType.equals("GNU") ){ - if( type == RetrieveFeedsAsyncTask.Type.TAG && tag != null) { + if (instanceType == null || instanceType.equals("MASTODON") || instanceType.equals("MISSKEY") || instanceType.equals("GNU")) { + if (type == RetrieveFeedsAsyncTask.Type.TAG && tag != null) { BaseMainActivity.displayPeertube = null; List tagTimelines = new SearchDAO(context, db).getTimelineInfo(tag); - if( tagTimelines != null && tagTimelines.size() > 0) { + if (tagTimelines != null && tagTimelines.size() > 0) { tagTimeline = tagTimelines.get(0); statusListAdapter = new StatusListAdapter(tagTimeline, targetedId, isOnWifi, this.statuses); lv_status.setAdapter(statusListAdapter); } - }else{ + } else { BaseMainActivity.displayPeertube = null; statusListAdapter = new StatusListAdapter(type, targetedId, isOnWifi, this.statuses); lv_status.setAdapter(statusListAdapter); } - }else if( instanceType.equals("PEERTUBE")){ - if( remoteInstance != null && MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) //if it's a Peertube account connected + } else if (instanceType.equals("PEERTUBE")) { + if (remoteInstance != null && MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) //if it's a Peertube account connected remoteInstance = instance; BaseMainActivity.displayPeertube = remoteInstance; peertubeAdapater = new PeertubeAdapter(remoteInstance, ownVideos, this.peertubes); lv_status.setAdapter(peertubeAdapater); - }else if( instanceType.equals("PIXELFED")){ - if( remoteInstance != null && MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) //if it's a Peertube account connected + } else if (instanceType.equals("PIXELFED")) { + if (remoteInstance != null && MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) //if it's a Peertube account connected remoteInstance = instance; pixelfedListAdapter = new PixelfedListAdapter(type, this.statuses); lv_status.setAdapter(pixelfedListAdapter); - }else if( instanceType.equals("ART")){ - if ( type == RetrieveFeedsAsyncTask.Type.TAG) { + } else if (instanceType.equals("ART")) { + if (type == RetrieveFeedsAsyncTask.Type.TAG) { List tagTimelines = new SearchDAO(context, db).getTimelineInfo(tag); if (tagTimelines != null && tagTimelines.size() > 0) { tagTimeline = tagTimelines.get(0); @@ -239,8 +241,8 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn //Manage broadcast receiver for Mastodon timelines - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA|| MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { - if( receive_action != null) + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + if (receive_action != null) LocalBroadcastManager.getInstance(context).unregisterReceiver(receive_action); receive_action = new BroadcastReceiver() { @Override @@ -249,12 +251,12 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn assert b != null; Status status = b.getParcelable("status"); String delete_statuses_from = b.getString("delete_statuses_for_id", null); - if( status != null && statusListAdapter != null) { + if (status != null && statusListAdapter != null) { statusListAdapter.notifyStatusWithActionChanged(status); - }else if( delete_statuses_from != null){ + } else if (delete_statuses_from != null) { List statusesToRemove = new ArrayList<>(); - for(Status status_temp: statuses){ - if( status_temp.getAccount().getId().equals(delete_statuses_from)) + for (Status status_temp : statuses) { + if (status_temp.getAccount().getId().equals(delete_statuses_from)) statusesToRemove.add(status); } statuses.removeAll(statusesToRemove); @@ -264,7 +266,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn }; LocalBroadcastManager.getInstance(context).registerReceiver(receive_action, new IntentFilter(Helper.RECEIVE_ACTION)); - if( type == RetrieveFeedsAsyncTask.Type.HOME || type == RetrieveFeedsAsyncTask.Type.LOCAL || type == RetrieveFeedsAsyncTask.Type.PUBLIC){ + if (type == RetrieveFeedsAsyncTask.Type.HOME || type == RetrieveFeedsAsyncTask.Type.LOCAL || type == RetrieveFeedsAsyncTask.Type.PUBLIC) { if (receive_data != null) LocalBroadcastManager.getInstance(context).unregisterReceiver(receive_data); @@ -281,34 +283,33 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn } }; } - if( type == RetrieveFeedsAsyncTask.Type.PUBLIC) + if (type == RetrieveFeedsAsyncTask.Type.PUBLIC) LocalBroadcastManager.getInstance(context).registerReceiver(receive_data, new IntentFilter(Helper.RECEIVE_FEDERATED_DATA)); - else if( type == RetrieveFeedsAsyncTask.Type.HOME) + else if (type == RetrieveFeedsAsyncTask.Type.HOME) LocalBroadcastManager.getInstance(context).registerReceiver(receive_data, new IntentFilter(Helper.RECEIVE_HOME_DATA)); - else if( type == RetrieveFeedsAsyncTask.Type.LOCAL) + else if (type == RetrieveFeedsAsyncTask.Type.LOCAL) LocalBroadcastManager.getInstance(context).registerReceiver(receive_data, new IntentFilter(Helper.RECEIVE_LOCAL_DATA)); } - if( type == RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE && search_peertube != null) - ((Activity)context).setTitle(remoteInstance + " - " + search_peertube); - if( type == RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE && remote_channel_name != null) - ((Activity)context).setTitle(remote_channel_name + " - " + remoteInstance); - if( type != RetrieveFeedsAsyncTask.Type.POVERVIEW ) //No paginations for Peertube Overviews (it's a fixed size content + if (type == RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE && search_peertube != null) + ((Activity) context).setTitle(remoteInstance + " - " + search_peertube); + if (type == RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE && remote_channel_name != null) + ((Activity) context).setTitle(remote_channel_name + " - " + remoteInstance); + if (type != RetrieveFeedsAsyncTask.Type.POVERVIEW) //No paginations for Peertube Overviews (it's a fixed size content lv_status.addOnScrollListener(new RecyclerView.OnScrollListener() { - public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) - { - if (type != RetrieveFeedsAsyncTask.Type.ART && context instanceof BaseMainActivity ) { - if( dy < 0 && !((BaseMainActivity)context).getFloatingVisibility() ) + public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { + if (type != RetrieveFeedsAsyncTask.Type.ART && context instanceof BaseMainActivity) { + if (dy < 0 && !((BaseMainActivity) context).getFloatingVisibility()) ((BaseMainActivity) context).manageFloatingButton(true); - if( dy > 0 && ((BaseMainActivity)context).getFloatingVisibility() ) + if (dy > 0 && ((BaseMainActivity) context).getFloatingVisibility()) ((BaseMainActivity) context).manageFloatingButton(false); } int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition(); - if(dy > 0){ + if (dy > 0) { int visibleItemCount = mLayoutManager.getChildCount(); int totalItemCount = mLayoutManager.getItemCount(); - if(firstVisibleItem + visibleItemCount == totalItemCount && context != null) { - if(!flag_loading ) { + if (firstVisibleItem + visibleItemCount == totalItemCount && context != null) { + if (!flag_loading) { flag_loading = true; manageAsyncTask(true); nextElementLoader.setVisibility(View.VISIBLE); @@ -317,12 +318,12 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn nextElementLoader.setVisibility(View.GONE); } } - if(type == RetrieveFeedsAsyncTask.Type.HOME && statuses != null && statuses.size() > firstVisibleItem && firstVisibleItem >= 0) { + if (type == RetrieveFeedsAsyncTask.Type.HOME && statuses != null && statuses.size() > firstVisibleItem && firstVisibleItem >= 0) { Date bookmarkL = statuses.get(firstVisibleItem).getCreated_at(); updatedBookMark = statuses.get(firstVisibleItem).getId(); updatedBookMarkDate = statuses.get(firstVisibleItem).getCreated_at(); - if( lastReadTootDate == null || (bookmarkL != null && bookmarkL.after(lastReadTootDate))){ - //Last read toot, only incremented if the id of the toot is greater than the recorded one + if (lastReadTootDate == null || (bookmarkL != null && bookmarkL.after(lastReadTootDate))) { + //Last read toot, only incremented if the id of the toot is greater than the recorded one lastReadTootDate = bookmarkL; } } @@ -330,17 +331,17 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn }); - if( instanceType == null || !instanceType.equals("PEERTUBE")) + if (instanceType == null || !instanceType.equals("PEERTUBE")) swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { - if( type == RetrieveFeedsAsyncTask.Type.HOME) + if (type == RetrieveFeedsAsyncTask.Type.HOME) MainActivity.countNewStatus = 0; isSwipped = true; - if( type != RetrieveFeedsAsyncTask.Type.CONVERSATION) + if (type != RetrieveFeedsAsyncTask.Type.CONVERSATION) retrieveMissingToots(null); - else{ - if( statuses.size() > 0) + else { + if (statuses.size() > 0) retrieveMissingToots(statuses.get(0).getId()); else retrieveMissingToots(null); @@ -370,7 +371,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn } SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: swipeRefreshLayout.setColorSchemeResources(R.color.mastodonC4, R.color.mastodonC2, @@ -390,14 +391,14 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn swipeRefreshLayout.setProgressBackgroundColorSchemeColor(ContextCompat.getColor(context, R.color.black_3)); break; } - if( context != null) { + if (context != null) { //Load data depending of the value manageAsyncTask(false); - }else { + } else { new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { - if( context != null){ + if (context != null) { manageAsyncTask(false); } } @@ -407,9 +408,9 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn } @Override - public void onPause(){ + public void onPause() { super.onPause(); - if (swipeRefreshLayout!=null) { + if (swipeRefreshLayout != null) { swipeRefreshLayout.setEnabled(false); swipeRefreshLayout.setRefreshing(false); swipeRefreshLayout.clearAnimation(); @@ -417,13 +418,13 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn //Store bookmark on pause if (context instanceof BaseMainActivity && type == RetrieveFeedsAsyncTask.Type.HOME) { SharedPreferences.Editor editor = sharedpreferences.edit(); - if(updatedBookMark != null) + if (updatedBookMark != null) editor.putString(Helper.BOOKMARK_ID + userId + instance, updatedBookMark); - if(updatedBookMarkDate != null) + if (updatedBookMarkDate != null) editor.putString(Helper.BOOKMARK_DATE + userId + instance, Helper.dateToString(updatedBookMarkDate)); - if( lastReadToot != null) + if (lastReadToot != null) editor.putString(Helper.LAST_READ_TOOT_ID + userId + instance, lastReadToot); - if( lastReadTootDate != null) + if (lastReadTootDate != null) editor.putString(Helper.LAST_READ_TOOT_DATE + userId + instance, Helper.dateToString(lastReadTootDate)); editor.apply(); } @@ -431,13 +432,11 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn @Override - public void onCreate(Bundle saveInstance) - { + public void onCreate(Bundle saveInstance) { super.onCreate(saveInstance); } - @Override public void onAttach(Context context) { super.onAttach(context); @@ -446,20 +445,20 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn @Override - public void onStop(){ + public void onStop() { super.onStop(); - if( statusListAdapter != null){ + if (statusListAdapter != null) { statusListAdapter.storeToot(); } /* if( asyncTask != null && !asyncTask.isCancelled()){ asyncTask.cancel(true); }*/ - if( type == RetrieveFeedsAsyncTask.Type.PUBLIC && streamingFederatedIntent != null){ + if (type == RetrieveFeedsAsyncTask.Type.PUBLIC && streamingFederatedIntent != null) { SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putBoolean(Helper.SHOULD_CONTINUE_STREAMING_FEDERATED + userId + instance, false); editor.apply(); context.stopService(streamingFederatedIntent); - }else if(type == RetrieveFeedsAsyncTask.Type.LOCAL && streamingLocalIntent != null){ + } else if (type == RetrieveFeedsAsyncTask.Type.LOCAL && streamingLocalIntent != null) { SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putBoolean(Helper.SHOULD_CONTINUE_STREAMING_LOCAL + userId + instance, false); editor.apply(); @@ -468,13 +467,13 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn } @Override - public void onDestroy (){ + public void onDestroy() { super.onDestroy(); - if(asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) + if (asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) asyncTask.cancel(true); - if( receive_action != null) + if (receive_action != null) LocalBroadcastManager.getInstance(context).unregisterReceiver(receive_action); - if( receive_data != null) + if (receive_data != null) LocalBroadcastManager.getInstance(context).unregisterReceiver(receive_data); } @@ -485,51 +484,51 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn nextElementLoader.setVisibility(View.GONE); //handle other API error but discards 404 - error which can often happen due to toots which have been deleted - if( this.peertubes == null || this.statuses == null || apiResponse == null || (apiResponse.getError() != null && apiResponse.getError().getStatusCode() != 404) ){ - if( apiResponse == null) - Toasty.error(context, context.getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + if (this.peertubes == null || this.statuses == null || apiResponse == null || (apiResponse.getError() != null && apiResponse.getError().getStatusCode() != 404)) { + if (apiResponse == null) + Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); else - Toasty.error(context, apiResponse.getError().getError(),Toast.LENGTH_LONG).show(); + Toasty.error(context, apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); swipeRefreshLayout.setRefreshing(false); flag_loading = false; return; } //For remote Peertube remote instances - if(instanceType.equals("PEERTUBE")){ + if (instanceType.equals("PEERTUBE")) { int previousPosition = this.peertubes.size(); - if( max_id == null) + if (max_id == null) max_id = "0"; //max_id needs to work like an offset int tootPerPage = sharedpreferences.getInt(Helper.SET_TOOT_PER_PAGE, Helper.TOOTS_PER_PAGE); max_id = String.valueOf(Integer.valueOf(max_id) + tootPerPage); - if( apiResponse.getPeertubes() == null){ + if (apiResponse.getPeertubes() == null) { return; } this.peertubes.addAll(apiResponse.getPeertubes()); //If no item were inserted previously the adapter is created - if( previousPosition == 0) { + if (previousPosition == 0) { peertubeAdapater = new PeertubeAdapter(remoteInstance, ownVideos, this.peertubes); lv_status.setAdapter(peertubeAdapater); - }else + } else peertubeAdapater.notifyItemRangeInserted(previousPosition, apiResponse.getPeertubes().size()); //remove handlers swipeRefreshLayout.setRefreshing(false); - if( firstLoad && (apiResponse.getPeertubes() == null || apiResponse.getPeertubes().size() ==0)){ + if (firstLoad && (apiResponse.getPeertubes() == null || apiResponse.getPeertubes().size() == 0)) { textviewNoActionText.setText(R.string.no_video_to_display); textviewNoAction.setVisibility(View.VISIBLE); } flag_loading = false; firstLoad = false; - }else { + } else { //When Mastodon statuses have been fetched. - if( type == RetrieveFeedsAsyncTask.Type.CONVERSATION ){ //Conversation timeline + if (type == RetrieveFeedsAsyncTask.Type.CONVERSATION) { //Conversation timeline //this timeline is dealt differently because it is embedded in Conversation entity and not directly in statuses List conversations = apiResponse.getConversations(); //Statuses from conversation entity are retrieved List statusesConversations = new ArrayList<>(); - if( conversations != null) { + if (conversations != null) { for (Conversation conversation : conversations) { Status status = conversation.getLast_status(); if (status != null) { @@ -547,32 +546,32 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn int previousPosition = this.statuses.size(); List statuses; - if( apiResponse.getResults() != null && apiResponse.getResults().getStatuses() != null) + if (apiResponse.getResults() != null && apiResponse.getResults().getStatuses() != null) statuses = apiResponse.getResults().getStatuses(); else statuses = apiResponse.getStatuses(); //At this point all statuses are in "List statuses" //Pagination for Pixelfed - if(instanceType.equals("PIXELFED")) { - if( max_id == null) + if (instanceType.equals("PIXELFED")) { + if (max_id == null) max_id = "1"; //max_id needs to work like an offset max_id = String.valueOf(Integer.valueOf(max_id) + 1); - }else if( type == RetrieveFeedsAsyncTask.Type.SEARCH && !tag.contains("_cache_")) { - if(max_id == null) + } else if (type == RetrieveFeedsAsyncTask.Type.SEARCH && !tag.contains("_cache_")) { + if (max_id == null) max_id = "0"; max_id = String.valueOf(Integer.valueOf(max_id) + 20); - } else{ + } else { max_id = apiResponse.getMax_id(); } //while max_id is different from null, there are some more toots to load when scrolling - flag_loading = (max_id == null ); + flag_loading = (max_id == null); //If it's the first load and the reply doesn't contain any toots, a message is displayed. - if( firstLoad && (statuses == null || statuses.size() == 0)) { + if (firstLoad && (statuses == null || statuses.size() == 0)) { textviewNoAction.setVisibility(View.VISIBLE); lv_status.setVisibility(View.GONE); - }else { + } else { lv_status.setVisibility(View.VISIBLE); textviewNoAction.setVisibility(View.GONE); } @@ -580,33 +579,33 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn //First toot are loaded as soon as the bookmark has been retrieved //Only for the Home timeline - if( type == RetrieveFeedsAsyncTask.Type.HOME && !firstTootsLoaded){ + if (type == RetrieveFeedsAsyncTask.Type.HOME && !firstTootsLoaded) { boolean remember_position_home = sharedpreferences.getBoolean(Helper.SET_REMEMBER_POSITION_HOME, true); - if( remember_position_home) - asyncTask = new RetrieveFeedsAfterBookmarkAsyncTask(context, null, false,DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + if (remember_position_home) + asyncTask = new RetrieveFeedsAfterBookmarkAsyncTask(context, null, false, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); firstTootsLoaded = true; } //Let's deal with statuses - if( statuses != null && statuses.size() > 0) { - if ( statusListAdapter != null && ( instanceType.equals("MASTODON") || instanceType.equals("MISSKEY") || instanceType.equals("GNU"))) { + if (statuses != null && statuses.size() > 0) { + if (statusListAdapter != null && (instanceType.equals("MASTODON") || instanceType.equals("MISSKEY") || instanceType.equals("GNU"))) { this.statuses.addAll(statuses); statusListAdapter.notifyItemRangeInserted(previousPosition, statuses.size()); - }else if(artListAdapter != null && instanceType.equals("ART") ) { + } else if (artListAdapter != null && instanceType.equals("ART")) { boolean show_nsfw = sharedpreferences.getBoolean(Helper.SET_ART_WITH_NSFW, false); - if( !show_nsfw) { + if (!show_nsfw) { ArrayList safeStatuses = new ArrayList<>(); - for(Status status: statuses){ - if( !status.isSensitive()) + for (Status status : statuses) { + if (!status.isSensitive()) safeStatuses.add(status); } this.statuses.addAll(safeStatuses); artListAdapter.notifyItemRangeInserted(previousPosition, safeStatuses.size()); - }else { + } else { this.statuses.addAll(statuses); artListAdapter.notifyItemRangeInserted(previousPosition, statuses.size()); } - }else if(pixelfedListAdapter != null && instanceType.equals("PIXELFED") ) { + } else if (pixelfedListAdapter != null && instanceType.equals("PIXELFED")) { this.statuses.addAll(statuses); pixelfedListAdapter.notifyItemRangeInserted(previousPosition, statuses.size()); } @@ -619,33 +618,35 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn /** * Deals with new status coming from the streaming api + * * @param status Status */ - public void refresh(Status status){ + public void refresh(Status status) { //New data are available if (context == null) return; - if( status.getId() != null && statuses != null && statuses.size() > 0 && statuses.get(0)!= null - && status.getCreated_at().after(statuses.get(0).getCreated_at()) ) { + if (status.getId() != null && statuses != null && statuses.size() > 0 && statuses.get(0) != null + && status.getCreated_at().after(statuses.get(0).getCreated_at())) { List tempTootResult = new ArrayList(); tempTootResult.add(status); - if( tempTootResult.size() > 0) + if (tempTootResult.size() > 0) status = tempTootResult.get(0); if (type == RetrieveFeedsAsyncTask.Type.HOME) { //Makes sure the status is not already displayed - if( !statuses.contains(status)){ + if (!statuses.contains(status)) { //Update the id of the last toot retrieved MainActivity.lastHomeId = status.getId(); statuses.add(0, status); statusListAdapter.notifyItemInserted(0); try { ((MainActivity) context).updateHomeCounter(); - }catch (Exception ignored){} + } catch (Exception ignored) { + } } - } else if (type == RetrieveFeedsAsyncTask.Type.PUBLIC || type == RetrieveFeedsAsyncTask.Type.LOCAL|| type == RetrieveFeedsAsyncTask.Type.DIRECT|| type == RetrieveFeedsAsyncTask.Type.GNU_DM) { + } else if (type == RetrieveFeedsAsyncTask.Type.PUBLIC || type == RetrieveFeedsAsyncTask.Type.LOCAL || type == RetrieveFeedsAsyncTask.Type.DIRECT || type == RetrieveFeedsAsyncTask.Type.GNU_DM) { status.setNew(false); statuses.add(0, status); @@ -664,65 +665,67 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn @Override public void onDestroyView() { - if( lv_status != null) { + if (lv_status != null) { lv_status.setAdapter(null); } super.onDestroyView(); } @Override - public void onResume(){ + public void onResume() { super.onResume(); swipeRefreshLayout.setEnabled(true); boolean liveNotifications = sharedpreferences.getBoolean(Helper.SET_LIVE_NOTIFICATIONS, true); - if (type == RetrieveFeedsAsyncTask.Type.HOME){ - if( getUserVisibleHint() ){ - if( statuses != null && statuses.size() > 0 && asyncTask.getStatus() != AsyncTask.Status.RUNNING) { + if (type == RetrieveFeedsAsyncTask.Type.HOME) { + if (getUserVisibleHint()) { + if (statuses != null && statuses.size() > 0 && asyncTask.getStatus() != AsyncTask.Status.RUNNING) { retrieveMissingToots(statuses.get(0).getId()); } } - } else if( type == RetrieveFeedsAsyncTask.Type.PUBLIC){ - if( getUserVisibleHint() ){ + } else if (type == RetrieveFeedsAsyncTask.Type.PUBLIC) { + if (getUserVisibleHint()) { SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putBoolean(Helper.SHOULD_CONTINUE_STREAMING_FEDERATED + userId + instance, true); editor.apply(); - if(liveNotifications) { + if (liveNotifications) { streamingFederatedIntent = new Intent(context, StreamingFederatedTimelineService.class); try { context.startService(streamingFederatedIntent); - }catch (Exception ignored){} + } catch (Exception ignored) { + } } - if( statuses != null && statuses.size() > 0) + if (statuses != null && statuses.size() > 0) retrieveMissingToots(statuses.get(0).getId()); } - }else if (type == RetrieveFeedsAsyncTask.Type.LOCAL){ + } else if (type == RetrieveFeedsAsyncTask.Type.LOCAL) { - if( getUserVisibleHint() ){ + if (getUserVisibleHint()) { SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putBoolean(Helper.SHOULD_CONTINUE_STREAMING_LOCAL + userId + instance, true); editor.apply(); - if( liveNotifications ) { + if (liveNotifications) { streamingLocalIntent = new Intent(context, StreamingLocalTimelineService.class); try { context.startService(streamingLocalIntent); - }catch (Exception ignored){} + } catch (Exception ignored) { + } } - if( statuses != null && statuses.size() > 0) + if (statuses != null && statuses.size() > 0) retrieveMissingToots(statuses.get(0).getId()); } - }else if (type == RetrieveFeedsAsyncTask.Type.DIRECT|| type == RetrieveFeedsAsyncTask.Type.GNU_DM){ - if( getUserVisibleHint() ){ - if( statuses != null && statuses.size() > 0) + } else if (type == RetrieveFeedsAsyncTask.Type.DIRECT || type == RetrieveFeedsAsyncTask.Type.GNU_DM) { + if (getUserVisibleHint()) { + if (statuses != null && statuses.size() > 0) retrieveMissingToots(statuses.get(0).getId()); } - }else if (type == RetrieveFeedsAsyncTask.Type.CONVERSATION){ - if( getUserVisibleHint() ){ - if( statuses != null && statuses.size() > 0) + } else if (type == RetrieveFeedsAsyncTask.Type.CONVERSATION) { + if (getUserVisibleHint()) { + if (statuses != null && statuses.size() > 0) retrieveMissingToots(statuses.get(0).getId()); } - }else if (type == RetrieveFeedsAsyncTask.Type.TAG){ - if( getUserVisibleHint() ){ - if( statuses != null && statuses.size() > 0) + } else if (type == RetrieveFeedsAsyncTask.Type.TAG) { + if (getUserVisibleHint()) { + if (statuses != null && statuses.size() > 0) retrieveMissingToots(statuses.get(0).getId()); } } @@ -730,15 +733,16 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn /** * Called from main activity in onResume to retrieve missing toots (home timeline) + * * @param sinceId String */ - private void retrieveMissingToots(String sinceId){ + private void retrieveMissingToots(String sinceId) { - if( type == RetrieveFeedsAsyncTask.Type.HOME) - asyncTask = new RetrieveFeedsAfterBookmarkAsyncTask(context, null, false,DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - if (type == RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE ) + if (type == RetrieveFeedsAsyncTask.Type.HOME) + asyncTask = new RetrieveFeedsAfterBookmarkAsyncTask(context, null, false, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + if (type == RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE) asyncTask = new RetrieveMissingFeedsAsyncTask(context, remoteInstance, sinceId, type, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - else if(type == RetrieveFeedsAsyncTask.Type.TAG) + else if (type == RetrieveFeedsAsyncTask.Type.TAG) asyncTask = new RetrieveMissingFeedsAsyncTask(context, tag, sinceId, type, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else asyncTask = new RetrieveMissingFeedsAsyncTask(context, sinceId, type, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); @@ -746,8 +750,8 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn } - public void retrieveMissingHome(){ - if( statusListAdapter != null && statuses != null && lv_status != null && mLayoutManager != null){ + public void retrieveMissingHome() { + if (statusListAdapter != null && statuses != null && lv_status != null && mLayoutManager != null) { int firstVisible = mLayoutManager.findFirstVisibleItemPosition(); Iterator s = statuses.iterator(); int i = 0; @@ -758,65 +762,68 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn statusListAdapter.notifyItemChanged(0); i++; } - if( statuses.size() > 0) + if (statuses.size() > 0) initialBookMarkDate = statuses.get(0).getCreated_at(); - asyncTask = new RetrieveFeedsAfterBookmarkAsyncTask(context, null, false,DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + asyncTask = new RetrieveFeedsAfterBookmarkAsyncTask(context, null, false, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } /** * When tab comes visible, first displayed toot is defined as read + * * @param visible boolean */ @Override public void setMenuVisibility(final boolean visible) { super.setMenuVisibility(visible); - if( context == null) + if (context == null) return; boolean liveNotifications = sharedpreferences.getBoolean(Helper.SET_LIVE_NOTIFICATIONS, true); //Store last toot id for home timeline to avoid to notify for those that have been already seen - if (type == RetrieveFeedsAsyncTask.Type.HOME ) { + if (type == RetrieveFeedsAsyncTask.Type.HOME) { if (visible) { - if( statuses != null && statuses.size() > 0) { + if (statuses != null && statuses.size() > 0) { retrieveMissingToots(statuses.get(0).getId()); } } - } else if( type == RetrieveFeedsAsyncTask.Type.PUBLIC ){ + } else if (type == RetrieveFeedsAsyncTask.Type.PUBLIC) { if (visible) { SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putBoolean(Helper.SHOULD_CONTINUE_STREAMING_FEDERATED + userId + instance, true); editor.apply(); - if(liveNotifications ) { + if (liveNotifications) { streamingFederatedIntent = new Intent(context, StreamingFederatedTimelineService.class); try { context.startService(streamingFederatedIntent); - }catch (Exception ignored){} + } catch (Exception ignored) { + } } - if( statuses != null && statuses.size() > 0) + if (statuses != null && statuses.size() > 0) retrieveMissingToots(statuses.get(0).getId()); - }else { - if( streamingFederatedIntent != null ){ + } else { + if (streamingFederatedIntent != null) { SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putBoolean(Helper.SHOULD_CONTINUE_STREAMING_FEDERATED + userId + instance, false); editor.apply(); context.stopService(streamingFederatedIntent); } } - }else if (type == RetrieveFeedsAsyncTask.Type.LOCAL){ + } else if (type == RetrieveFeedsAsyncTask.Type.LOCAL) { if (visible) { SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putBoolean(Helper.SHOULD_CONTINUE_STREAMING_LOCAL + userId + instance, true); editor.apply(); - if( liveNotifications ) { + if (liveNotifications) { streamingLocalIntent = new Intent(context, StreamingLocalTimelineService.class); try { context.startService(streamingLocalIntent); - }catch (Exception ignored){} + } catch (Exception ignored) { + } } - if( statuses != null && statuses.size() > 0) + if (statuses != null && statuses.size() > 0) retrieveMissingToots(statuses.get(0).getId()); - }else { - if( streamingLocalIntent != null ){ + } else { + if (streamingLocalIntent != null) { SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putBoolean(Helper.SHOULD_CONTINUE_STREAMING_LOCAL + userId + instance, false); editor.apply(); @@ -827,16 +834,15 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn } - - public void scrollToTop(){ - if( lv_status != null && instanceType != null) { - if( statusListAdapter != null && (instanceType.equals("MASTODON") || instanceType.equals("MISSKEY") || instanceType.equals("GNU"))) + public void scrollToTop() { + if (lv_status != null && instanceType != null) { + if (statusListAdapter != null && (instanceType.equals("MASTODON") || instanceType.equals("MISSKEY") || instanceType.equals("GNU"))) lv_status.setAdapter(statusListAdapter); - else if( pixelfedListAdapter != null && instanceType.equals("PIXELFED")) + else if (pixelfedListAdapter != null && instanceType.equals("PIXELFED")) lv_status.setAdapter(pixelfedListAdapter); - else if( artListAdapter != null && instanceType.equals("ART")) + else if (artListAdapter != null && instanceType.equals("ART")) lv_status.setAdapter(artListAdapter); - else if( peertubeAdapater != null && instanceType.equals("PEERTUBE")) + else if (peertubeAdapater != null && instanceType.equals("PEERTUBE")) lv_status.setAdapter(peertubeAdapater); } } @@ -844,24 +850,24 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn /** * Refresh status in list */ - public void refreshFilter(){ + public void refreshFilter() { - if( statusListAdapter != null) { + if (statusListAdapter != null) { statusListAdapter.notifyDataSetChanged(); - }else if( pixelfedListAdapter != null) { + } else if (pixelfedListAdapter != null) { pixelfedListAdapter.notifyDataSetChanged(); - }else if( artListAdapter != null){ + } else if (artListAdapter != null) { artListAdapter.notifyDataSetChanged(); } } @Override public void onRetrieveMissingFeeds(List statuses) { - if(swipeRefreshLayout == null) + if (swipeRefreshLayout == null) return; //Clean label new swipeRefreshLayout.setRefreshing(false); - if( isSwipped && this.statuses != null && this.statuses.size() > 0) { + if (isSwipped && this.statuses != null && this.statuses.size() > 0) { for (Status status : this.statuses) { status.setNew(false); } @@ -882,26 +888,26 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn isSwipped = false; - if( statuses != null && statuses.size() > 0) { - if( textviewNoAction.getVisibility() == View.VISIBLE){ + if (statuses != null && statuses.size() > 0) { + if (textviewNoAction.getVisibility() == View.VISIBLE) { textviewNoAction.setVisibility(View.GONE); lv_status.setVisibility(View.VISIBLE); } int inserted = 0; int insertedConversation = 0; - if(type == RetrieveFeedsAsyncTask.Type.CONVERSATION){ //Remove conversation already displayed if new messages + if (type == RetrieveFeedsAsyncTask.Type.CONVERSATION) { //Remove conversation already displayed if new messages int position = 0; insertedConversation = statuses.size(); - if( this.statuses != null) { + if (this.statuses != null) { for (Iterator it = this.statuses.iterator(); it.hasNext(); ) { Status status = it.next(); for (Status status1 : statuses) { if (status.getConversationId() != null && status.getConversationId().equals(status1.getConversationId())) { - if( instanceType.equals("MASTODON") || instanceType.equals("MISSKEY")|| instanceType.equals("GNU")) + if (instanceType.equals("MASTODON") || instanceType.equals("MISSKEY") || instanceType.equals("GNU")) statusListAdapter.notifyItemRemoved(position); - else if( instanceType.equals("PIXELFED")) + else if (instanceType.equals("PIXELFED")) pixelfedListAdapter.notifyItemRemoved(position); - else if( instanceType.equals("ART")) + else if (instanceType.equals("ART")) artListAdapter.notifyItemRemoved(position); it.remove(); } @@ -911,22 +917,22 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn } } for (int i = statuses.size() - 1; i >= 0; i--) { - if( this.statuses != null) { - if( type != RetrieveFeedsAsyncTask.Type.HOME){ - if( tagTimeline != null && instanceType.equals("ART") && !tagTimeline.isNSFW() ){ - if( !statuses.get(i).isSensitive()) { + if (this.statuses != null) { + if (type != RetrieveFeedsAsyncTask.Type.HOME) { + if (tagTimeline != null && instanceType.equals("ART") && !tagTimeline.isNSFW()) { + if (!statuses.get(i).isSensitive()) { this.statuses.add(0, statuses.get(i)); inserted++; } - }else { + } else { if (this.statuses.size() == 0 || statuses.get(i).getCreated_at().after(this.statuses.get(0).getCreated_at())) { inserted++; this.statuses.add(0, statuses.get(i)); } } - }else { - if( lastReadTootDate != null && statuses.get(i).getCreated_at().after(lastReadTootDate)) { - if( !this.statuses.contains(statuses.get(i)) ) { + } else { + if (lastReadTootDate != null && statuses.get(i).getCreated_at().after(lastReadTootDate)) { + if (!this.statuses.contains(statuses.get(i))) { statuses.get(i).setNew(true); MainActivity.countNewStatus++; inserted++; @@ -936,51 +942,52 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn } } } - if( statusListAdapter != null && (instanceType.equals("MASTODON") || instanceType.equals("MISSKEY")|| instanceType.equals("GNU"))) + if (statusListAdapter != null && (instanceType.equals("MASTODON") || instanceType.equals("MISSKEY") || instanceType.equals("GNU"))) statusListAdapter.notifyItemRangeInserted(0, inserted); - else if( pixelfedListAdapter != null && instanceType.equals("PIXELFED")) + else if (pixelfedListAdapter != null && instanceType.equals("PIXELFED")) pixelfedListAdapter.notifyItemRangeInserted(0, inserted); - else if( artListAdapter != null && instanceType.equals("ART")) + else if (artListAdapter != null && instanceType.equals("ART")) artListAdapter.notifyItemRangeInserted(0, inserted); try { - if( type == RetrieveFeedsAsyncTask.Type.HOME) + if (type == RetrieveFeedsAsyncTask.Type.HOME) ((MainActivity) context).updateHomeCounter(); else { - if( type != RetrieveFeedsAsyncTask.Type.CONVERSATION) + if (type != RetrieveFeedsAsyncTask.Type.CONVERSATION) ((MainActivity) context).manageTab(type, inserted); else ((MainActivity) context).manageTab(type, insertedConversation); } - }catch (Exception ignored){} + } catch (Exception ignored) { + } } } - public void fetchMore(String max_id){ - asyncTask = new RetrieveFeedsAfterBookmarkAsyncTask(context, max_id, true,DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + public void fetchMore(String max_id) { + asyncTask = new RetrieveFeedsAfterBookmarkAsyncTask(context, max_id, true, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } @Override public void onRetrieveFeedsAfterBookmark(APIResponse apiResponse) { - if( statusListAdapter == null) + if (statusListAdapter == null) return; - if( apiResponse == null || (apiResponse.getError() != null && apiResponse.getError().getStatusCode() != 404) ){ - if( apiResponse == null) - Toasty.error(context, context.getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + if (apiResponse == null || (apiResponse.getError() != null && apiResponse.getError().getStatusCode() != 404)) { + if (apiResponse == null) + Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); else - Toasty.error(context, apiResponse.getError().getError(),Toast.LENGTH_LONG).show(); + Toasty.error(context, apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); swipeRefreshLayout.setRefreshing(false); flag_loading = false; return; } List statuses = apiResponse.getStatuses(); - if( statuses == null || statuses.size() == 0 || this.statuses == null ) + if (statuses == null || statuses.size() == 0 || this.statuses == null) return; //Find the position of toots between those already present int position = 0; - if( position < this.statuses.size() && statuses.get(0).getCreated_at() != null && this.statuses.get(position).getCreated_at() != null) { + if (position < this.statuses.size() && statuses.get(0).getCreated_at() != null && this.statuses.get(position).getCreated_at() != null) { while (position < this.statuses.size() && statuses.get(0).getCreated_at().before(this.statuses.get(position).getCreated_at())) { position++; } @@ -988,16 +995,16 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn ArrayList tmpStatuses = new ArrayList<>(); for (Status tmpStatus : statuses) { //Put the toot at its place in the list (id desc) - if( !apiResponse.isFetchmore() && this.statuses.size() > 0 && !this.statuses.contains(tmpStatus) && tmpStatus.getCreated_at() != null && this.statuses.get(0).getCreated_at() != null && tmpStatus.getCreated_at().after(this.statuses.get(0).getCreated_at())) { //Element not already added + if (!apiResponse.isFetchmore() && this.statuses.size() > 0 && !this.statuses.contains(tmpStatus) && tmpStatus.getCreated_at() != null && this.statuses.get(0).getCreated_at() != null && tmpStatus.getCreated_at().after(this.statuses.get(0).getCreated_at())) { //Element not already added //Mark status at new ones when their id is greater than the last read toot id - if (type == RetrieveFeedsAsyncTask.Type.HOME && lastReadTootDate != null && tmpStatus.getCreated_at().after(lastReadTootDate) ) { + if (type == RetrieveFeedsAsyncTask.Type.HOME && lastReadTootDate != null && tmpStatus.getCreated_at().after(lastReadTootDate)) { tmpStatus.setNew(true); MainActivity.countNewStatus++; } tmpStatuses.add(tmpStatus); - }else if( apiResponse.isFetchmore() && !this.statuses.contains(tmpStatus)) { //Element not already added + } else if (apiResponse.isFetchmore() && !this.statuses.contains(tmpStatus)) { //Element not already added //Mark status at new ones when their id is greater than the last read toot id - if (type == RetrieveFeedsAsyncTask.Type.HOME && lastReadTootDate != null && tmpStatus.getCreated_at().after(lastReadTootDate) ) { + if (type == RetrieveFeedsAsyncTask.Type.HOME && lastReadTootDate != null && tmpStatus.getCreated_at().after(lastReadTootDate)) { tmpStatus.setNew(true); MainActivity.countNewStatus++; } @@ -1006,34 +1013,35 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn } try { ((MainActivity) context).updateHomeCounter(); - }catch (Exception ignored){} + } catch (Exception ignored) { + } int tootPerPage = sharedpreferences.getInt(Helper.SET_TOOT_PER_PAGE, Helper.TOOTS_PER_PAGE); //Display the fetch more toot button - if( tmpStatuses.size() >= tootPerPage) { - if (initialBookMarkDate != null && tmpStatuses.size() > 0 && tmpStatuses.get(tmpStatuses.size() - 1).getCreated_at().after(initialBookMarkDate)) { - if( StatusListAdapter.fetch_all_more && statuses.size() > 0){ + if (tmpStatuses.size() >= tootPerPage) { + if (initialBookMarkDate != null && tmpStatuses.size() > 0 && tmpStatuses.get(tmpStatuses.size() - 1).getCreated_at().after(initialBookMarkDate)) { + if (StatusListAdapter.fetch_all_more && statuses.size() > 0) { fetchMore(tmpStatuses.get(tmpStatuses.size() - 1).getId()); - }else{ + } else { tmpStatuses.get(tmpStatuses.size() - 1).setFetchMore(true); StatusListAdapter.fetch_all_more = false; } } - }else{ + } else { StatusListAdapter.fetch_all_more = false; } this.statuses.addAll(position, tmpStatuses); statusListAdapter.notifyItemRangeInserted(position, tmpStatuses.size()); boolean display_content_after_fetch_more = sharedpreferences.getBoolean(Helper.SET_DISPLAY_CONTENT_AFTER_FM, true); - if( position > 0 && display_content_after_fetch_more) + if (position > 0 && display_content_after_fetch_more) lv_status.scrollToPosition(position + tmpStatuses.size()); - if( textviewNoAction.getVisibility() == View.VISIBLE && tmpStatuses.size() > 0){ + if (textviewNoAction.getVisibility() == View.VISIBLE && tmpStatuses.size() > 0) { textviewNoAction.setVisibility(View.GONE); lv_status.setVisibility(View.VISIBLE); } } //Update last read toots value when pressing tab button - public void updateLastReadToot(){ + public void updateLastReadToot() { if (type == RetrieveFeedsAsyncTask.Type.HOME && this.statuses != null && this.statuses.size() > 0) { lastReadToot = this.statuses.get(0).getId(); } @@ -1046,7 +1054,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn //Tag timelines else if (type == RetrieveFeedsAsyncTask.Type.SEARCH) asyncTask = new RetrieveFeedsAsyncTask(context, type, tag, targetedId, max_id, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - else if (type == RetrieveFeedsAsyncTask.Type.TAG ) + else if (type == RetrieveFeedsAsyncTask.Type.TAG) asyncTask = new RetrieveFeedsAsyncTask(context, type, timelineId, max_id, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else if (type == RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE) { //Remote instances @@ -1057,7 +1065,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn asyncTask = new RetrieveFeedsAsyncTask(context, remoteInstance, remote_channel_name, null, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else asyncTask = new RetrievePeertubeSearchAsyncTask(context, remoteInstance, search_peertube, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else if(type == RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE_FILTERED){ + } else if (type == RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE_FILTERED) { RetrieveFeedsParam retrieveFeedsParam = new RetrieveFeedsParam(); retrieveFeedsParam.setAction(type); retrieveFeedsParam.setCurrentfilter(currentfilter); @@ -1065,14 +1073,14 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn retrieveFeedsParam.setMax_id(max_id); retrieveFeedsParam.setSocial(instanceType); asyncTask = new RetrieveFeedsAsyncTask(context, retrieveFeedsParam, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else if( type == RetrieveFeedsAsyncTask.Type.LIST){ - new ManageListsAsyncTask(context,targetedId, max_id ,null, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else { - if( !pagination) { + } else if (type == RetrieveFeedsAsyncTask.Type.LIST) { + new ManageListsAsyncTask(context, targetedId, max_id, null, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + } else { + if (!pagination) { if (type == RetrieveFeedsAsyncTask.Type.HOME) { if (context instanceof BaseMainActivity) { boolean remember_position_home = sharedpreferences.getBoolean(Helper.SET_REMEMBER_POSITION_HOME, true); - if(remember_position_home ) + if (remember_position_home) asyncTask = new RetrieveFeedsAsyncTask(context, type, initialBookMark, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else asyncTask = new RetrieveFeedsAsyncTask(context, type, null, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); @@ -1080,10 +1088,10 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn } else { //Most classical search will be done by this call asyncTask = new RetrieveFeedsAsyncTask(context, type, null, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } - }else { - if( type == RetrieveFeedsAsyncTask.Type.HOME){ + } else { + if (type == RetrieveFeedsAsyncTask.Type.HOME) { asyncTask = new RetrieveFeedsAsyncTask(context, type, max_id, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else {//Most classical search will be done by this call for pagination + } else {//Most classical search will be done by this call for pagination asyncTask = new RetrieveFeedsAsyncTask(context, type, max_id, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } @@ -1097,14 +1105,14 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn nextElementLoader.setVisibility(View.GONE); //Discards 404 - error which can often happen due to toots which have been deleted if (apiResponse.getError() != null) { - if ( !apiResponse.getError().getError().startsWith("404 -")) + if (!apiResponse.getError().getError().startsWith("404 -")) Toasty.error(context, apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); swipeRefreshLayout.setRefreshing(false); isSwipped = false; flag_loading = false; return; } - if( actionType == ManageListsAsyncTask.action.GET_LIST_TIMELINE) { + if (actionType == ManageListsAsyncTask.action.GET_LIST_TIMELINE) { int previousPosition = this.statuses.size(); List statuses = apiResponse.getStatuses(); @@ -1134,13 +1142,13 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn } public void pullToRefresh() { - if(swipeRefreshLayout != null){ + if (swipeRefreshLayout != null) { swipeRefreshLayout.setRefreshing(true); - }else { + } else { return; } - if (instanceType == null || !instanceType.equals("PEERTUBE")){ - if( type == RetrieveFeedsAsyncTask.Type.HOME) + if (instanceType == null || !instanceType.equals("PEERTUBE")) { + if (type == RetrieveFeedsAsyncTask.Type.HOME) MainActivity.countNewStatus = 0; isSwipped = true; int lenght = statuses.size(); @@ -1161,7 +1169,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn max_id = null; manageAsyncTask(false); - }else if( peertubes != null){ + } else if (peertubes != null) { if (peertubes.size() > 0) { int size = peertubes.size(); isSwipped = true; diff --git a/app/src/main/java/app/fedilab/android/fragments/SettingsPeertubeFragment.java b/app/src/main/java/app/fedilab/android/fragments/SettingsPeertubeFragment.java index e56c955c7..13f41c276 100644 --- a/app/src/main/java/app/fedilab/android/fragments/SettingsPeertubeFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/SettingsPeertubeFragment.java @@ -17,8 +17,10 @@ package app.fedilab.android.fragments; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; + import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -61,13 +63,13 @@ public class SettingsPeertubeFragment extends Fragment { if (videoMode == Helper.VIDEO_MODE_TORRENT) videoMode = Helper.VIDEO_MODE_DIRECT; int positionVideoMode = 0; - if( videoMode == Helper.VIDEO_MODE_DIRECT) + if (videoMode == Helper.VIDEO_MODE_DIRECT) positionVideoMode = 1; video_mode_spinner.setSelection(positionVideoMode); video_mode_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { - if( count1 > 0 ) { + if (count1 > 0) { SharedPreferences.Editor editor = sharedpreferences.edit(); switch (position) { /*case 0: @@ -86,6 +88,7 @@ public class SettingsPeertubeFragment extends Fragment { } count1++; } + @Override public void onNothingSelected(AdapterView parent) { @@ -109,14 +112,12 @@ public class SettingsPeertubeFragment extends Fragment { } - @Override public void onCreate(Bundle saveInstance) { super.onCreate(saveInstance); } - @Override public void onAttach(Context context) { super.onAttach(context); diff --git a/app/src/main/java/app/fedilab/android/fragments/TabLayoutNotificationsFragment.java b/app/src/main/java/app/fedilab/android/fragments/TabLayoutNotificationsFragment.java index 3c11a1f20..9b2a759ff 100644 --- a/app/src/main/java/app/fedilab/android/fragments/TabLayoutNotificationsFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/TabLayoutNotificationsFragment.java @@ -19,13 +19,17 @@ import android.content.Context; import android.content.SharedPreferences; import android.graphics.PorterDuff; import android.os.Bundle; + import androidx.annotation.NonNull; + import com.google.android.material.tabs.TabLayout; + import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentStatePagerAdapter; import androidx.core.content.ContextCompat; import androidx.viewpager.widget.ViewPager; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -57,7 +61,7 @@ public class TabLayoutNotificationsFragment extends Fragment { TabLayout tabLayout = inflatedView.findViewById(R.id.tabLayout); - if(MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.all))); TabLayout.Tab tabMention = tabLayout.newTab(); @@ -67,17 +71,15 @@ public class TabLayoutNotificationsFragment extends Fragment { TabLayout.Tab tabFollow = tabLayout.newTab(); tabMention.setCustomView(R.layout.tab_badge); - if(MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) tabFav.setCustomView(R.layout.tab_badge); - if(MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) tabBoost.setCustomView(R.layout.tab_badge); - if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) tabPoll.setCustomView(R.layout.tab_badge); tabFollow.setCustomView(R.layout.tab_badge); - - SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); @@ -86,20 +88,20 @@ public class TabLayoutNotificationsFragment extends Fragment { iconMention.setImageResource(R.drawable.ic_mention_notif_tab); - ImageView iconFav =null; - if( tabFav.getCustomView() != null) { + ImageView iconFav = null; + if (tabFav.getCustomView() != null) { iconFav = tabFav.getCustomView().findViewById(R.id.tab_icon); iconFav.setImageResource(R.drawable.ic_star_notif_tab); } - ImageView iconBoost =null; - if( tabBoost.getCustomView() != null) { + ImageView iconBoost = null; + if (tabBoost.getCustomView() != null) { iconBoost = tabBoost.getCustomView().findViewById(R.id.tab_icon); iconBoost.setImageResource(R.drawable.ic_repeat_notif_tab); } - ImageView iconPoll =null; - if( tabPoll.getCustomView() != null) { + ImageView iconPoll = null; + if (tabPoll.getCustomView() != null) { iconPoll = tabPoll.getCustomView().findViewById(R.id.tab_icon); iconPoll.setImageResource(R.drawable.ic_view_list_poll_notif); } @@ -109,13 +111,12 @@ public class TabLayoutNotificationsFragment extends Fragment { iconFollow.setImageResource(R.drawable.ic_follow_notif_tab); - tabLayout.addTab(tabMention); - if( tabFav.getCustomView() != null) + if (tabFav.getCustomView() != null) tabLayout.addTab(tabFav); - if( tabBoost.getCustomView() != null) + if (tabBoost.getCustomView() != null) tabLayout.addTab(tabBoost); - if( tabPoll.getCustomView() != null) + if (tabPoll.getCustomView() != null) tabLayout.addTab(tabPoll); tabLayout.addTab(tabFollow); @@ -126,20 +127,20 @@ public class TabLayoutNotificationsFragment extends Fragment { if (theme == Helper.THEME_LIGHT) { iconMention.setColorFilter(ContextCompat.getColor(context, R.color.action_light_header), PorterDuff.Mode.SRC_IN); - if( iconFav != null) + if (iconFav != null) iconFav.setColorFilter(ContextCompat.getColor(context, R.color.action_light_header), PorterDuff.Mode.SRC_IN); - if( iconBoost != null) + if (iconBoost != null) iconBoost.setColorFilter(ContextCompat.getColor(context, R.color.action_light_header), PorterDuff.Mode.SRC_IN); - if( iconPoll != null) + if (iconPoll != null) iconPoll.setColorFilter(ContextCompat.getColor(context, R.color.action_light_header), PorterDuff.Mode.SRC_IN); iconFollow.setColorFilter(ContextCompat.getColor(context, R.color.action_light_header), PorterDuff.Mode.SRC_IN); } else { iconMention.setColorFilter(ContextCompat.getColor(context, R.color.dark_text), PorterDuff.Mode.SRC_IN); - if( iconFav != null) + if (iconFav != null) iconFav.setColorFilter(ContextCompat.getColor(context, R.color.dark_text), PorterDuff.Mode.SRC_IN); - if( iconBoost != null) + if (iconBoost != null) iconBoost.setColorFilter(ContextCompat.getColor(context, R.color.dark_text), PorterDuff.Mode.SRC_IN); - if( iconPoll != null) + if (iconPoll != null) iconPoll.setColorFilter(ContextCompat.getColor(context, R.color.dark_text), PorterDuff.Mode.SRC_IN); iconFollow.setColorFilter(ContextCompat.getColor(context, R.color.dark_text), PorterDuff.Mode.SRC_IN); } @@ -150,7 +151,7 @@ public class TabLayoutNotificationsFragment extends Fragment { viewPager.setAdapter(new PagerAdapter (getChildFragmentManager(), tabLayout.getTabCount())); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); - tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { + tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); @@ -163,7 +164,7 @@ public class TabLayoutNotificationsFragment extends Fragment { @Override public void onTabReselected(TabLayout.Tab tab) { - if( viewPager.getAdapter() != null) { + if (viewPager.getAdapter() != null) { Fragment fragment = (Fragment) viewPager.getAdapter().instantiateItem(viewPager, tab.getPosition()); DisplayNotificationsFragment displayNotificationsFragment = ((DisplayNotificationsFragment) fragment); displayNotificationsFragment.scrollToTop(); @@ -174,7 +175,7 @@ public class TabLayoutNotificationsFragment extends Fragment { return inflatedView; } - public ViewPager getViewPager(){ + public ViewPager getViewPager() { return viewPager; } @@ -202,21 +203,21 @@ public class TabLayoutNotificationsFragment extends Fragment { String tag = ""; switch (position) { case 0: - if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { type = DisplayNotificationsFragment.Type.ALL; - }else + } else type = DisplayNotificationsFragment.Type.MENTION; break; case 1: - if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) type = DisplayNotificationsFragment.Type.MENTION; - else if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU) + else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU) type = DisplayNotificationsFragment.Type.BOOST; - else if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) + else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) type = DisplayNotificationsFragment.Type.FOLLOW; break; case 2: - if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU ) + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU) type = DisplayNotificationsFragment.Type.FAVORITE; else type = DisplayNotificationsFragment.Type.FOLLOW; @@ -250,19 +251,19 @@ public class TabLayoutNotificationsFragment extends Fragment { } } - public void refreshAll(){ - if( viewPager == null) + public void refreshAll() { + if (viewPager == null) return; FragmentStatePagerAdapter a = (FragmentStatePagerAdapter) viewPager.getAdapter(); - if( a != null) { + if (a != null) { DisplayNotificationsFragment notifAll = (DisplayNotificationsFragment) a.instantiateItem(viewPager, 0); notifAll.refreshAll(); } } - public void retrieveMissingNotifications(String sinceId){ + public void retrieveMissingNotifications(String sinceId) { FragmentStatePagerAdapter a = (FragmentStatePagerAdapter) viewPager.getAdapter(); - if( a != null) { + if (a != null) { DisplayNotificationsFragment notifAll = (DisplayNotificationsFragment) a.instantiateItem(viewPager, 0); notifAll.retrieveMissingNotifications(sinceId); } diff --git a/app/src/main/java/app/fedilab/android/fragments/TabLayoutScheduleFragment.java b/app/src/main/java/app/fedilab/android/fragments/TabLayoutScheduleFragment.java index c95882c82..1e3696474 100644 --- a/app/src/main/java/app/fedilab/android/fragments/TabLayoutScheduleFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/TabLayoutScheduleFragment.java @@ -15,12 +15,16 @@ package app.fedilab.android.fragments; * see . */ import android.os.Bundle; + import androidx.annotation.NonNull; + import com.google.android.material.tabs.TabLayout; + import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentStatePagerAdapter; import androidx.viewpager.widget.ViewPager; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -38,14 +42,13 @@ import app.fedilab.android.asynctasks.UpdateAccountInfoAsyncTask; public class TabLayoutScheduleFragment extends Fragment { - @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View inflatedView = inflater.inflate(R.layout.tablayout_toots, container, false); TabLayout tabLayout = inflatedView.findViewById(R.id.tabLayout); - if(MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.toots_server))); tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.toots_client))); tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.reblog))); @@ -54,7 +57,7 @@ public class TabLayoutScheduleFragment extends Fragment { (getChildFragmentManager(), tabLayout.getTabCount())); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); - tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { + tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); @@ -91,13 +94,13 @@ public class TabLayoutScheduleFragment extends Fragment { case 0: DisplayScheduledTootsFragment displayScheduledTootsFragment; Bundle bundle; - if(MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { displayScheduledTootsFragment = new DisplayScheduledTootsFragment(); bundle = new Bundle(); bundle.putSerializable("type", DisplayScheduledTootsFragment.typeOfSchedule.SERVER); displayScheduledTootsFragment.setArguments(bundle); return displayScheduledTootsFragment; - }else { + } else { displayScheduledTootsFragment = new DisplayScheduledTootsFragment(); bundle = new Bundle(); bundle.putSerializable("type", DisplayScheduledTootsFragment.typeOfSchedule.TOOT); @@ -105,13 +108,13 @@ public class TabLayoutScheduleFragment extends Fragment { return displayScheduledTootsFragment; } case 1: - if(MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { displayScheduledTootsFragment = new DisplayScheduledTootsFragment(); bundle = new Bundle(); bundle.putSerializable("type", DisplayScheduledTootsFragment.typeOfSchedule.TOOT); displayScheduledTootsFragment.setArguments(bundle); return displayScheduledTootsFragment; - }else { + } else { displayScheduledTootsFragment = new DisplayScheduledTootsFragment(); bundle = new Bundle(); bundle.putSerializable("type", DisplayScheduledTootsFragment.typeOfSchedule.BOOST); diff --git a/app/src/main/java/app/fedilab/android/fragments/TabLayoutTootsFragment.java b/app/src/main/java/app/fedilab/android/fragments/TabLayoutTootsFragment.java index 0e38c0baa..930ad4f2a 100644 --- a/app/src/main/java/app/fedilab/android/fragments/TabLayoutTootsFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/TabLayoutTootsFragment.java @@ -13,13 +13,18 @@ package app.fedilab.android.fragments; * * You should have received a copy of the GNU General Public License along with Fedilab; if not, * see . */ + import android.os.Bundle; + import androidx.annotation.NonNull; + import com.google.android.material.tabs.TabLayout; + import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentStatePagerAdapter; import androidx.viewpager.widget.ViewPager; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -49,7 +54,7 @@ public class TabLayoutTootsFragment extends Fragment { TabLayout tabLayout = inflatedView.findViewById(R.id.tabLayout); tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.toots))); tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.replies))); - if(MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.media))); tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.pinned_toots))); } @@ -63,7 +68,7 @@ public class TabLayoutTootsFragment extends Fragment { (getChildFragmentManager(), tabLayout.getTabCount())); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); - tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { + tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); @@ -103,7 +108,7 @@ public class TabLayoutTootsFragment extends Fragment { Bundle bundle = new Bundle(); bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.USER); bundle.putString("targetedid", targetedId); - bundle.putBoolean("showReply",false); + bundle.putBoolean("showReply", false); displayStatusFragment.setArguments(bundle); return displayStatusFragment; case 1: @@ -111,7 +116,7 @@ public class TabLayoutTootsFragment extends Fragment { bundle = new Bundle(); bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.USER); bundle.putString("targetedid", targetedId); - bundle.putBoolean("showReply",true); + bundle.putBoolean("showReply", true); displayStatusFragment.setArguments(bundle); return displayStatusFragment; case 2: @@ -125,7 +130,7 @@ public class TabLayoutTootsFragment extends Fragment { bundle = new Bundle(); bundle.putSerializable("type", RetrieveFeedsAsyncTask.Type.USER); bundle.putString("targetedid", targetedId); - bundle.putBoolean("showPinned",true); + bundle.putBoolean("showPinned", true); displayStatusFragment.setArguments(bundle); return displayStatusFragment; default: @@ -140,7 +145,7 @@ public class TabLayoutTootsFragment extends Fragment { } } - public ViewPager getViewPager(){ + public ViewPager getViewPager() { return viewPager; } } \ No newline at end of file diff --git a/app/src/main/java/app/fedilab/android/fragments/WhoToFollowFragment.java b/app/src/main/java/app/fedilab/android/fragments/WhoToFollowFragment.java index 2b261d3d4..52f00cbe7 100644 --- a/app/src/main/java/app/fedilab/android/fragments/WhoToFollowFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/WhoToFollowFragment.java @@ -18,8 +18,10 @@ import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; + import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -40,7 +42,6 @@ import app.fedilab.android.asynctasks.WhoToFollowAsyncTask; import app.fedilab.android.interfaces.OnRetrieveWhoToFollowInterface; - /** * Created by Thomas on 10/09/2018. * Fragment to display who to follow list @@ -64,10 +65,10 @@ public class WhoToFollowFragment extends Fragment implements OnRetrieveWhoToFoll cal.setTime(new Date()); cal.add(Calendar.MINUTE, -15); Date dateAllowed = cal.getTime(); - if (lastDateListRefresh == null || Helper.stringToDate(context, lastDateListRefresh).before(dateAllowed)){ + if (lastDateListRefresh == null || Helper.stringToDate(context, lastDateListRefresh).before(dateAllowed)) { mainLoader.setVisibility(View.VISIBLE); new WhoToFollowAsyncTask(context, null, WhoToFollowFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else { + } else { String lastList = sharedpreferences.getString(Helper.LAST_LIST, null); List list = Helper.restoreArrayFromString(lastList); displayResults(list); @@ -77,8 +78,7 @@ public class WhoToFollowFragment extends Fragment implements OnRetrieveWhoToFoll } @Override - public void onCreate(Bundle saveInstance) - { + public void onCreate(Bundle saveInstance) { super.onCreate(saveInstance); } @@ -89,21 +89,21 @@ public class WhoToFollowFragment extends Fragment implements OnRetrieveWhoToFoll } - private void displayResults(List list){ + private void displayResults(List list) { mainLoader.setVisibility(View.GONE); - if( list != null){ + if (list != null) { ListView lv_list = rootView.findViewById(R.id.lv_list); WhoToFollowAdapter whoToFollowAdapter = new WhoToFollowAdapter(list); lv_list.setAdapter(whoToFollowAdapter); - }else{ - Toasty.error(context, context.getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + } else { + Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); } } @Override public void onRetrieveWhoToFollowList(List list) { - if( list != null){ + if (list != null) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(Helper.LAST_DATE_LIST_REFRESH, Helper.dateToString(new Date())); diff --git a/app/src/main/java/app/fedilab/android/helper/CountDrawable.java b/app/src/main/java/app/fedilab/android/helper/CountDrawable.java index ef470ae8b..40ec4c2fa 100644 --- a/app/src/main/java/app/fedilab/android/helper/CountDrawable.java +++ b/app/src/main/java/app/fedilab/android/helper/CountDrawable.java @@ -10,6 +10,7 @@ import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.Drawable; + import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; @@ -56,20 +57,19 @@ public class CountDrawable extends Drawable { /*Using Math.max rather than Math.min */ float radius = ((Math.max(width, height) / 2)) / 2; - float centerX = (width - radius - 1) +5; - float centerY = radius -5; - if(mCount.length() <= 2){ + float centerX = (width - radius - 1) + 5; + float centerY = radius - 5; + if (mCount.length() <= 2) { // Draw badge circle. - canvas.drawCircle(centerX, centerY, (int)(radius+5.5), mBadgePaint); - } - else{ - canvas.drawCircle(centerX, centerY, (int)(radius+6.5), mBadgePaint); + canvas.drawCircle(centerX, centerY, (int) (radius + 5.5), mBadgePaint); + } else { + canvas.drawCircle(centerX, centerY, (int) (radius + 6.5), mBadgePaint); } // Draw badge count text inside the circle. mTextPaint.getTextBounds(mCount, 0, mCount.length(), mTxtRect); float textHeight = mTxtRect.bottom - mTxtRect.top; float textY = centerY + (textHeight / 2f); - if(mCount.length() > 2) + if (mCount.length() > 2) canvas.drawText("99+", centerX, textY, mTextPaint); else canvas.drawText(mCount, centerX, textY, mTextPaint); diff --git a/app/src/main/java/app/fedilab/android/helper/CrossActions.java b/app/src/main/java/app/fedilab/android/helper/CrossActions.java index 9bbf9da56..478ca7e9e 100644 --- a/app/src/main/java/app/fedilab/android/helper/CrossActions.java +++ b/app/src/main/java/app/fedilab/android/helper/CrossActions.java @@ -23,8 +23,10 @@ import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; + import androidx.appcompat.app.AlertDialog; import androidx.recyclerview.widget.RecyclerView; + import android.text.Html; import android.widget.Toast; @@ -66,10 +68,11 @@ public class CrossActions { /** * Returns the list of connected accounts when cross actions are allowed otherwise, returns the current account + * * @param context Context * @return List */ - private static List connectedAccounts(Context context, Status status, boolean limitedToOwner){ + private static List connectedAccounts(Context context, Status status, boolean limitedToOwner) { final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); List accountstmp = new AccountDAO(context, db).getAllAccountCrossAction(); @@ -77,46 +80,46 @@ public class CrossActions { String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, null); Account currentAccount = new AccountDAO(context, db).getUniqAccount(userId, instance); List accounts = new ArrayList<>(); - if( accountstmp != null && !limitedToOwner && accountstmp.size() > 1 ){ + if (accountstmp != null && !limitedToOwner && accountstmp.size() > 1) { //It's for a reply - if( status != null){ + if (status != null) { //Status is private or direct - if( status.getVisibility().equals("private") || status.getVisibility().equals("direct") ){ + if (status.getVisibility().equals("private") || status.getVisibility().equals("direct")) { //Retrieves mentioned accounts and compares them to the list of accounts in the device. List mentions = status.getMentions(); List addedAccount = new ArrayList<>(); //Adds the owner accounts.add(currentAccount); addedAccount.add(currentAccount.getId() + "|" + currentAccount.getAcct()); - for(Mention mention: mentions){ - for(Account account: accountstmp){ - String mentionAcct = (mention.getAcct().contains("@"))?mention.getAcct():mention.getAcct()+"@"+currentAccount.getInstance(); - if( (account.getAcct() + "@" + account.getInstance()).equals(mentionAcct) && !addedAccount.contains(account.getId() + "|" + account.getAcct())) { - if( account.getSocial() == null || account.getSocial().equals("MASTODON") || account.getSocial().equals("PLEROMA")) + for (Mention mention : mentions) { + for (Account account : accountstmp) { + String mentionAcct = (mention.getAcct().contains("@")) ? mention.getAcct() : mention.getAcct() + "@" + currentAccount.getInstance(); + if ((account.getAcct() + "@" + account.getInstance()).equals(mentionAcct) && !addedAccount.contains(account.getId() + "|" + account.getAcct())) { + if (account.getSocial() == null || account.getSocial().equals("MASTODON") || account.getSocial().equals("PLEROMA")) accounts.add(account); } } } - for(Account account: accountstmp){ + for (Account account : accountstmp) { Account tootOwner = status.getAccount(); - String mentionAcct = (tootOwner.getAcct().contains("@"))?tootOwner.getAcct():tootOwner.getAcct()+"@"+currentAccount.getInstance(); - if( (account.getAcct() + "@" + account.getInstance()).equals(mentionAcct) && !addedAccount.contains(account.getId() + "|" + account.getAcct())) { - if( account.getSocial() == null || account.getSocial().equals("MASTODON")|| account.getSocial().equals("PLEROMA")) + String mentionAcct = (tootOwner.getAcct().contains("@")) ? tootOwner.getAcct() : tootOwner.getAcct() + "@" + currentAccount.getInstance(); + if ((account.getAcct() + "@" + account.getInstance()).equals(mentionAcct) && !addedAccount.contains(account.getId() + "|" + account.getAcct())) { + if (account.getSocial() == null || account.getSocial().equals("MASTODON") || account.getSocial().equals("PLEROMA")) accounts.add(account); } } - }else { + } else { accounts = accountstmp; } - }else { + } else { accounts = accountstmp; } return accounts; - }else { + } else { List oneAccount = new ArrayList<>(); Account account = new AccountDAO(context, db).getUniqAccount(userId, instance); oneAccount.add(account); - return oneAccount; + return oneAccount; } } @@ -130,9 +133,9 @@ public class CrossActions { int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } boolean confirmation = false; @@ -140,7 +143,7 @@ public class CrossActions { confirmation = sharedpreferences.getBoolean(Helper.SET_NOTIF_VALIDATION_FAV, false); else if (doAction == API.StatusAction.UNREBLOG || doAction == API.StatusAction.REBLOG) confirmation = sharedpreferences.getBoolean(Helper.SET_NOTIF_VALIDATION, true); - if((type == RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE || type == RetrieveFeedsAsyncTask.Type.NEWS) && limitedToOwner){ + if ((type == RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE || type == RetrieveFeedsAsyncTask.Type.NEWS) && limitedToOwner) { String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, null); SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); @@ -149,29 +152,29 @@ public class CrossActions { displayConfirmationDialogCrossAction(context, currentAccount, doAction, status, onPostActionInterface, baseAdapter); else { new PostActionAsyncTask(context, currentAccount, status, doAction, onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - if( doAction == API.StatusAction.FAVOURITE || doAction == API.StatusAction.UNFAVOURITE){ + if (doAction == API.StatusAction.FAVOURITE || doAction == API.StatusAction.UNFAVOURITE) { if (doAction == API.StatusAction.FAVOURITE) { status.setFavourited(true); status.setFavAnimated(true); - }else{ + } else { status.setFavourited(false); status.setFavAnimated(false); } - if(baseAdapter instanceof PixelfedListAdapter) + if (baseAdapter instanceof PixelfedListAdapter) ((PixelfedListAdapter) baseAdapter).notifyStatusChanged(status); - else if(baseAdapter instanceof StatusListAdapter) + else if (baseAdapter instanceof StatusListAdapter) ((StatusListAdapter) baseAdapter).notifyStatusChanged(status); - }else if(doAction == API.StatusAction.REBLOG || doAction == API.StatusAction.UNREBLOG){ + } else if (doAction == API.StatusAction.REBLOG || doAction == API.StatusAction.UNREBLOG) { if (doAction == API.StatusAction.REBLOG) { status.setReblogged(true); status.setBoostAnimated(true); - }else{ + } else { status.setReblogged(false); status.setBoostAnimated(false); } - if(baseAdapter instanceof PixelfedListAdapter) + if (baseAdapter instanceof PixelfedListAdapter) ((PixelfedListAdapter) baseAdapter).notifyStatusChanged(status); - else if(baseAdapter instanceof StatusListAdapter) + else if (baseAdapter instanceof StatusListAdapter) ((StatusListAdapter) baseAdapter).notifyStatusChanged(status); } } @@ -186,29 +189,29 @@ public class CrossActions { else if (doAction == API.StatusAction.PIN || doAction == API.StatusAction.UNPIN) pinAction(context, status, baseAdapter, onPostActionInterface); - if( doAction == API.StatusAction.FAVOURITE || doAction == API.StatusAction.UNFAVOURITE){ + if (doAction == API.StatusAction.FAVOURITE || doAction == API.StatusAction.UNFAVOURITE) { if (doAction == API.StatusAction.FAVOURITE) { status.setFavourited(true); status.setFavAnimated(true); - }else{ + } else { status.setFavourited(false); status.setFavAnimated(false); } - if(baseAdapter instanceof PixelfedListAdapter) + if (baseAdapter instanceof PixelfedListAdapter) ((PixelfedListAdapter) baseAdapter).notifyStatusChanged(status); - else if(baseAdapter instanceof StatusListAdapter) + else if (baseAdapter instanceof StatusListAdapter) ((StatusListAdapter) baseAdapter).notifyStatusChanged(status); - }else if(doAction == API.StatusAction.REBLOG || doAction == API.StatusAction.UNREBLOG){ + } else if (doAction == API.StatusAction.REBLOG || doAction == API.StatusAction.UNREBLOG) { if (doAction == API.StatusAction.REBLOG) { status.setReblogged(true); status.setBoostAnimated(true); - }else{ + } else { status.setReblogged(false); status.setBoostAnimated(false); } - if(baseAdapter instanceof PixelfedListAdapter) + if (baseAdapter instanceof PixelfedListAdapter) ((PixelfedListAdapter) baseAdapter).notifyStatusChanged(status); - else if(baseAdapter instanceof StatusListAdapter) + else if (baseAdapter instanceof StatusListAdapter) ((StatusListAdapter) baseAdapter).notifyStatusChanged(status); } } @@ -219,7 +222,7 @@ public class CrossActions { final AccountsSearchAdapter accountsSearchAdapter = new AccountsSearchAdapter(context, accounts, true); final Account[] accountArray = new Account[accounts.size()]; int i = 0; - for(Account account: accounts){ + for (Account account : accounts) { accountArray[i] = account; i++; } @@ -237,34 +240,34 @@ public class CrossActions { String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, null); SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); Account loggedAccount = new AccountDAO(context, db).getUniqAccount(userId, instance); - if( targetedAccount == null){ - if(loggedAccount.getInstance().equals(selectedAccount.getInstance())){ + if (targetedAccount == null) { + if (loggedAccount.getInstance().equals(selectedAccount.getInstance())) { new PostActionAsyncTask(context, selectedAccount, doAction, status.getId(), onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else{ //Account is from another instance + } else { //Account is from another instance new PostActionAsyncTask(context, selectedAccount, status, doAction, onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } - if( selectedAccount.getInstance().equals(loggedAccount.getInstance()) && selectedAccount.getId().equals(loggedAccount.getId())) { + if (selectedAccount.getInstance().equals(loggedAccount.getInstance()) && selectedAccount.getId().equals(loggedAccount.getId())) { if (doAction == API.StatusAction.REBLOG) { status.setReblogged(true); - if( type == RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE || type == RetrieveFeedsAsyncTask.Type.NEWS) + if (type == RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE || type == RetrieveFeedsAsyncTask.Type.NEWS) status.setBoostAnimated(true); } else if (doAction == API.StatusAction.FAVOURITE) { status.setFavourited(true); - if( type == RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE|| type == RetrieveFeedsAsyncTask.Type.NEWS) + if (type == RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE || type == RetrieveFeedsAsyncTask.Type.NEWS) status.setFavAnimated(true); } else if (doAction == API.StatusAction.PIN) { status.setPinned(true); } - if( baseAdapter != null) + if (baseAdapter != null) baseAdapter.notifyDataSetChanged(); } - }else{ + } else { new PostActionAsyncTask(context, selectedAccount, targetedAccount, doAction, onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - if( selectedAccount.getInstance().equals(loggedAccount.getInstance()) && selectedAccount.getId().equals(loggedAccount.getId())) { + if (selectedAccount.getInstance().equals(loggedAccount.getInstance()) && selectedAccount.getId().equals(loggedAccount.getId())) { if (doAction == API.StatusAction.FOLLOW) { targetedAccount.setFollowing(true); } - if( baseAdapter != null) + if (baseAdapter != null) baseAdapter.notifyDataSetChanged(); } } @@ -276,7 +279,7 @@ public class CrossActions { } - public static void followPeertubeChannel(final Context context, Account remoteAccount, OnPostActionInterface onPostActionInterface){ + public static void followPeertubeChannel(final Context context, Account remoteAccount, OnPostActionInterface onPostActionInterface) { new AsyncTask() { private WeakReference contextReference = new WeakReference<>(context); Results response; @@ -295,20 +298,21 @@ public class CrossActions { response = apiResponse.getResults(); return null; } + @Override protected void onPostExecute(Void result) { - if( response == null){ + if (response == null) { return; } List remoteAccounts = response.getAccounts(); - if( remoteAccounts != null && remoteAccounts.size() > 0) { + if (remoteAccounts != null && remoteAccounts.size() > 0) { new PostActionAsyncTask(context, null, remoteAccounts.get(0), API.StatusAction.FOLLOW, onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } - }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR ); + }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } - public static void doCrossProfile(final Context context, Account remoteAccount){ + public static void doCrossProfile(final Context context, Account remoteAccount) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, null); @@ -328,7 +332,7 @@ public class CrossActions { protected Void doInBackground(Void... voids) { API api = new API(contextReference.get(), account.getInstance(), account.getToken()); String url = remoteAccount.getUrl(); - if( url == null) { + if (url == null) { if (remoteAccount.getHost() != null && remoteAccount.getAcct().split("@").length > 1) //Peertube compatibility url = "https://" + remoteAccount.getHost() + "/accounts/" + remoteAccount.getAcct().split("@")[0]; else @@ -338,23 +342,24 @@ public class CrossActions { response = apiResponse.getResults(); return null; } + @Override protected void onPostExecute(Void result) { - if( response == null){ + if (response == null) { return; } List remoteAccounts = response.getAccounts(); - if( remoteAccounts != null && remoteAccounts.size() > 0) { + if (remoteAccounts != null && remoteAccounts.size() > 0) { Account fetchedAccount = null; - if( remoteAccounts.size() == 1){ + if (remoteAccounts.size() == 1) { Account acc = remoteAccounts.get(0); if (remoteAccount.getUsername() == null || acc.getUsername().equals(remoteAccount.getUsername())) { fetchedAccount = acc; } - }else { + } else { remoteAccounts.size(); - for(Account acc: remoteAccounts){ + for (Account acc : remoteAccounts) { String instance = null; try { @@ -363,12 +368,12 @@ public class CrossActions { } catch (URISyntaxException e) { e.printStackTrace(); } - if( instance != null ) { + if (instance != null) { if ((acc.getUsername()).equals(remoteAccount.getAcct())) { fetchedAccount = acc; break; } - }else{ + } else { if (acc.getAcct().equals(remoteAccount.getAcct())) { fetchedAccount = acc; break; @@ -376,11 +381,11 @@ public class CrossActions { } } } - if(fetchedAccount != null){ + if (fetchedAccount != null) { Intent intent = new Intent(context, ShowAccountActivity.class); Bundle b = new Bundle(); //Flag it has a peertube account - if( remoteAccount.getHost() != null && remoteAccount.getAcct().split("@").length > 1) + if (remoteAccount.getHost() != null && remoteAccount.getAcct().split("@").length > 1) b.putBoolean("peertubeaccount", true); b.putParcelable("account", fetchedAccount); intent.putExtras(b); @@ -389,10 +394,10 @@ public class CrossActions { } } - }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR ); + }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } - public static void doCrossConversation(final Context context, Status remoteStatus){ + public static void doCrossConversation(final Context context, Status remoteStatus) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, null); @@ -415,13 +420,14 @@ public class CrossActions { response = apiResponse.getResults(); return null; } + @Override protected void onPostExecute(Void result) { - if( response == null){ + if (response == null) { return; } List statuses = response.getStatuses(); - if( statuses != null && statuses.size() > 0) { + if (statuses != null && statuses.size() > 0) { Intent intent = new Intent(context, ShowConversationActivity.class); Bundle b = new Bundle(); b.putParcelable("status", statuses.get(0)); @@ -429,11 +435,11 @@ public class CrossActions { context.startActivity(intent); } } - }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR ); + }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } - public static void doCrossConversation(final Context context, String url){ + public static void doCrossConversation(final Context context, String url) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, null); @@ -453,16 +459,17 @@ public class CrossActions { protected Void doInBackground(Void... voids) { API api = new API(contextReference.get(), account.getInstance(), account.getToken()); APIResponse apiResponse = api.search(url); - response = apiResponse.getResults(); + response = apiResponse.getResults(); return null; } + @Override protected void onPostExecute(Void result) { - if( response == null){ + if (response == null) { return; } List statuses = response.getStatuses(); - if( statuses != null && statuses.size() > 0) { + if (statuses != null && statuses.size() > 0) { Intent intent = new Intent(context, ShowConversationActivity.class); Bundle b = new Bundle(); b.putParcelable("status", statuses.get(0)); @@ -470,13 +477,13 @@ public class CrossActions { context.startActivity(intent); } } - }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR ); + }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } - public static void doCrossBookmark(final Context context, final Status status, StatusListAdapter statusListAdapter ){ + public static void doCrossBookmark(final Context context, final Status status, StatusListAdapter statusListAdapter) { List accounts = connectedAccounts(context, status, false); - if( accounts.size() == 1) { + if (accounts.size() == 1) { status.setBookmarked(!status.isBookmarked()); try { SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); @@ -488,17 +495,17 @@ public class CrossActions { Toasty.success(context, context.getString(R.string.status_unbookmarked), Toast.LENGTH_LONG).show(); } statusListAdapter.notifyStatusChanged(status); - }catch (Exception e){ + } catch (Exception e) { e.printStackTrace(); - Toasty.error(context, context.getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); } - }else { + } else { AlertDialog.Builder builderSingle = new AlertDialog.Builder(context, style); builderSingle.setTitle(context.getString(R.string.choose_accounts)); final AccountsSearchAdapter accountsSearchAdapter = new AccountsSearchAdapter(context, accounts, true); final Account[] accountArray = new Account[accounts.size()]; int i = 0; - for(Account account: accounts){ + for (Account account : accounts) { accountArray[i] = account; i++; } @@ -528,14 +535,15 @@ public class CrossActions { response = apiResponse.getResults(); return null; } + @Override protected void onPostExecute(Void result) { - if( response == null){ - Toasty.error(contextReference.get(),context.getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + if (response == null) { + Toasty.error(contextReference.get(), context.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); return; } List statuses = response.getStatuses(); - if( statuses != null && statuses.size() > 0) { + if (statuses != null && statuses.size() > 0) { final SQLiteDatabase db = Sqlite.getInstance(contextReference.get(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); app.fedilab.android.client.Entities.Status statusBookmarked = new StatusCacheDAO(contextReference.get(), db).getStatus(StatusCacheDAO.BOOKMARK_CACHE, statuses.get(0).getId(), account.getId(), account.getInstance()); if (statusBookmarked == null) { @@ -548,7 +556,7 @@ public class CrossActions { statusListAdapter.notifyStatusChanged(statuses.get(0)); } } - }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR ); + }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } }); @@ -557,34 +565,34 @@ public class CrossActions { } - - public static void doCrossReply(final Context context, final Status status, final RetrieveFeedsAsyncTask.Type type, boolean limitedToOwner){ + public static void doCrossReply(final Context context, final Status status, final RetrieveFeedsAsyncTask.Type type, boolean limitedToOwner) { List accounts = connectedAccounts(context, status, limitedToOwner); - if( accounts.size() == 1 && type != RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE && type != RetrieveFeedsAsyncTask.Type.NEWS) { + if (accounts.size() == 1 && type != RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE && type != RetrieveFeedsAsyncTask.Type.NEWS) { Intent intent = new Intent(context, TootActivity.class); Bundle b = new Bundle(); - if( status != null && status.getReblog() != null ) + if (status != null && status.getReblog() != null) b.putParcelable("tootReply", status.getReblog()); else b.putParcelable("tootReply", status); intent.putExtras(b); //Put your id to your next Intent context.startActivity(intent); - if( type == RetrieveFeedsAsyncTask.Type.CONTEXT ){ + if (type == RetrieveFeedsAsyncTask.Type.CONTEXT) { try { //Avoid to open multi activities when replying in a conversation - ((ShowConversationActivity)context).finish(); - }catch (Exception ignored){} + ((ShowConversationActivity) context).finish(); + } catch (Exception ignored) { + } } - }else { - if( type != RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE && type != RetrieveFeedsAsyncTask.Type.NEWS){ + } else { + if (type != RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE && type != RetrieveFeedsAsyncTask.Type.NEWS) { AlertDialog.Builder builderSingle = new AlertDialog.Builder(context, style); builderSingle.setTitle(context.getString(R.string.choose_accounts)); final AccountsSearchAdapter accountsSearchAdapter = new AccountsSearchAdapter(context, accounts, true); final Account[] accountArray = new Account[accounts.size()]; int i = 0; - for(Account account: accounts){ + for (Account account : accounts) { accountArray[i] = account; i++; } @@ -598,7 +606,7 @@ public class CrossActions { @Override public void onClick(final DialogInterface dialog, int which) { final Account account = accountArray[which]; - if(status != null) { + if (status != null) { new AsyncTask() { private List remoteStatuses; private WeakReference contextReference = new WeakReference<>(context); @@ -644,7 +652,7 @@ public class CrossActions { b.putParcelable("tootReply", remoteStatuses.get(0)); b.putParcelable("idRedirect", status); } - b.putString("accountReplyToken", account.getId()+"|"+account.getInstance()); + b.putString("accountReplyToken", account.getId() + "|" + account.getInstance()); intent.putExtras(b); //Put your id to your next Intent contextReference.get().startActivity(intent); if (type == RetrieveFeedsAsyncTask.Type.CONTEXT) { @@ -658,10 +666,10 @@ public class CrossActions { dialog.dismiss(); } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else{ + } else { Intent intent = new Intent(context, TootActivity.class); Bundle b = new Bundle(); - b.putString("accountReplyToken", account.getId()+"|"+account.getInstance()); + b.putString("accountReplyToken", account.getId() + "|" + account.getInstance()); intent.putExtras(b); //Put your id to your next Intent context.startActivity(intent); } @@ -669,7 +677,7 @@ public class CrossActions { } }); builderSingle.show(); - }else{ + } else { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, null); @@ -685,19 +693,19 @@ public class CrossActions { API api = new API(contextReference.get(), account.getInstance(), account.getToken()); String uri; - if(status.getReblog() != null ){ - if( status.getReblog().getUri().startsWith("http")) + if (status.getReblog() != null) { + if (status.getReblog().getUri().startsWith("http")) uri = status.getReblog().getUri(); else uri = status.getReblog().getUrl(); - }else { - if( status.getUri().startsWith("http")) + } else { + if (status.getUri().startsWith("http")) uri = status.getUri(); else uri = status.getUrl(); } APIResponse search = api.search(uri); - if( search != null && search.getResults() != null){ + if (search != null && search.getResults() != null) { remoteStatuses = search.getResults().getStatuses(); } return null; @@ -707,41 +715,41 @@ public class CrossActions { protected void onPostExecute(Void result) { Intent intent = new Intent(contextReference.get(), TootActivity.class); Bundle b = new Bundle(); - if( remoteStatuses == null || remoteStatuses.size() == 0){ + if (remoteStatuses == null || remoteStatuses.size() == 0) { return; } - if( remoteStatuses.get(0).getReblog() != null ) { + if (remoteStatuses.get(0).getReblog() != null) { b.putParcelable("tootReply", remoteStatuses.get(0).getReblog()); b.putParcelable("idRedirect", remoteStatuses.get(0).getReblog()); - }else { + } else { b.putParcelable("tootReply", remoteStatuses.get(0)); b.putParcelable("idRedirect", remoteStatuses.get(0)); } - b.putString("accountReplyToken", account.getId()+"|"+account.getInstance()); + b.putString("accountReplyToken", account.getId() + "|" + account.getInstance()); intent.putExtras(b); //Put your id to your next Intent contextReference.get().startActivity(intent); } - }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR ); + }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } } - public static void doCrossShare(final Context context, final Bundle bundle){ + public static void doCrossShare(final Context context, final Bundle bundle) { List accounts = connectedAccounts(context, null, false); - if( accounts.size() == 1) { + if (accounts.size() == 1) { Intent intentToot = new Intent(context, TootActivity.class); intentToot.putExtras(bundle); context.startActivity(intentToot); - ((BaseActivity)context).finish(); - }else { + ((BaseActivity) context).finish(); + } else { AlertDialog.Builder builderSingle = new AlertDialog.Builder(context, style); builderSingle.setTitle(context.getString(R.string.choose_accounts)); final AccountsSearchAdapter accountsSearchAdapter = new AccountsSearchAdapter(context, accounts, true); final Account[] accountArray = new Account[accounts.size()]; int i = 0; - for(Account account: accounts){ + for (Account account : accounts) { accountArray[i] = account; i++; } @@ -756,10 +764,10 @@ public class CrossActions { public void onClick(final DialogInterface dialog, int which) { final Account account = accountArray[which]; Intent intentToot = new Intent(context, TootActivity.class); - bundle.putString("accountReplyToken", account.getId()+"|"+account.getInstance()); + bundle.putString("accountReplyToken", account.getId() + "|" + account.getInstance()); intentToot.putExtras(bundle); context.startActivity(intentToot); - ((BaseActivity)context).finish(); + ((BaseActivity) context).finish(); dialog.dismiss(); } }); @@ -769,23 +777,24 @@ public class CrossActions { /** * Display a validation message + * * @param action int * @param status Status */ - private static void displayConfirmationDialog(final Context context, final API.StatusAction action, final Status status, final RecyclerView.Adapter baseAdapter, final OnPostActionInterface onPostActionInterface){ + private static void displayConfirmationDialog(final Context context, final API.StatusAction action, final Status status, final RecyclerView.Adapter baseAdapter, final OnPostActionInterface onPostActionInterface) { String title = null; - if( action == API.StatusAction.FAVOURITE){ + if (action == API.StatusAction.FAVOURITE) { title = context.getString(R.string.favourite_add); - }else if( action == API.StatusAction.UNFAVOURITE){ + } else if (action == API.StatusAction.UNFAVOURITE) { title = context.getString(R.string.favourite_remove); - }else if( action == API.StatusAction.REBLOG){ + } else if (action == API.StatusAction.REBLOG) { title = context.getString(R.string.reblog_add); - }else if(action == API.StatusAction.UNREBLOG){ + } else if (action == API.StatusAction.UNREBLOG) { title = context.getString(R.string.reblog_remove); - }else if ( action == API.StatusAction.PIN) { + } else if (action == API.StatusAction.PIN) { title = context.getString(R.string.pin_add); - }else if (action == API.StatusAction.UNPIN) { + } else if (action == API.StatusAction.UNPIN) { title = context.getString(R.string.pin_remove); } @@ -801,36 +810,36 @@ public class CrossActions { .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { - if( action == API.StatusAction.REBLOG || action == API.StatusAction.UNREBLOG) + if (action == API.StatusAction.REBLOG || action == API.StatusAction.UNREBLOG) reblogAction(context, status, onPostActionInterface); - else if( action == API.StatusAction.FAVOURITE || action == API.StatusAction.UNFAVOURITE) + else if (action == API.StatusAction.FAVOURITE || action == API.StatusAction.UNFAVOURITE) favouriteAction(context, status, onPostActionInterface); - else if ( action == API.StatusAction.PIN || action == API.StatusAction.UNPIN) + else if (action == API.StatusAction.PIN || action == API.StatusAction.UNPIN) pinAction(context, status, baseAdapter, onPostActionInterface); - if( action == API.StatusAction.FAVOURITE || action == API.StatusAction.UNFAVOURITE){ + if (action == API.StatusAction.FAVOURITE || action == API.StatusAction.UNFAVOURITE) { if (action == API.StatusAction.FAVOURITE) { status.setFavourited(true); status.setFavAnimated(true); - }else{ + } else { status.setFavourited(false); status.setFavAnimated(false); } - if(baseAdapter instanceof PixelfedListAdapter) + if (baseAdapter instanceof PixelfedListAdapter) ((PixelfedListAdapter) baseAdapter).notifyStatusChanged(status); - else if(baseAdapter instanceof StatusListAdapter) + else if (baseAdapter instanceof StatusListAdapter) ((StatusListAdapter) baseAdapter).notifyStatusChanged(status); - }else if(action == API.StatusAction.REBLOG || action == API.StatusAction.UNREBLOG){ + } else if (action == API.StatusAction.REBLOG || action == API.StatusAction.UNREBLOG) { if (action == API.StatusAction.REBLOG) { status.setReblogged(true); status.setBoostAnimated(true); - }else{ + } else { status.setReblogged(false); status.setBoostAnimated(false); } - if(baseAdapter instanceof PixelfedListAdapter) + if (baseAdapter instanceof PixelfedListAdapter) ((PixelfedListAdapter) baseAdapter).notifyStatusChanged(status); - else if(baseAdapter instanceof StatusListAdapter) + else if (baseAdapter instanceof StatusListAdapter) ((StatusListAdapter) baseAdapter).notifyStatusChanged(status); } dialog.dismiss(); @@ -847,26 +856,26 @@ public class CrossActions { } - /** * Display a validation message + * * @param action int * @param status Status */ - private static void displayConfirmationDialogCrossAction(final Context context,Account currentAccount, final API.StatusAction action, final Status status, final OnPostActionInterface onPostActionInterface, final RecyclerView.Adapter baseAdapter){ + private static void displayConfirmationDialogCrossAction(final Context context, Account currentAccount, final API.StatusAction action, final Status status, final OnPostActionInterface onPostActionInterface, final RecyclerView.Adapter baseAdapter) { String title = null; - if( action == API.StatusAction.FAVOURITE){ + if (action == API.StatusAction.FAVOURITE) { title = context.getString(R.string.favourite_add); - }else if( action == API.StatusAction.UNFAVOURITE){ + } else if (action == API.StatusAction.UNFAVOURITE) { title = context.getString(R.string.favourite_remove); - }else if( action == API.StatusAction.REBLOG){ + } else if (action == API.StatusAction.REBLOG) { title = context.getString(R.string.reblog_add); - }else if(action == API.StatusAction.UNREBLOG){ + } else if (action == API.StatusAction.UNREBLOG) { title = context.getString(R.string.reblog_remove); - }else if ( action == API.StatusAction.PIN) { + } else if (action == API.StatusAction.PIN) { title = context.getString(R.string.pin_add); - }else if (action == API.StatusAction.UNPIN) { + } else if (action == API.StatusAction.UNPIN) { title = context.getString(R.string.pin_remove); } @@ -882,29 +891,29 @@ public class CrossActions { .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { - if( action == API.StatusAction.FAVOURITE || action == API.StatusAction.UNFAVOURITE){ + if (action == API.StatusAction.FAVOURITE || action == API.StatusAction.UNFAVOURITE) { if (action == API.StatusAction.FAVOURITE) { status.setFavourited(true); status.setFavAnimated(true); - }else{ + } else { status.setFavourited(false); status.setFavAnimated(false); } - if(baseAdapter instanceof PixelfedListAdapter) + if (baseAdapter instanceof PixelfedListAdapter) ((PixelfedListAdapter) baseAdapter).notifyStatusChanged(status); - else if(baseAdapter instanceof StatusListAdapter) + else if (baseAdapter instanceof StatusListAdapter) ((StatusListAdapter) baseAdapter).notifyStatusChanged(status); - }else if(action == API.StatusAction.REBLOG || action == API.StatusAction.UNREBLOG){ + } else if (action == API.StatusAction.REBLOG || action == API.StatusAction.UNREBLOG) { if (action == API.StatusAction.REBLOG) { status.setReblogged(true); status.setBoostAnimated(true); - }else{ + } else { status.setReblogged(false); status.setBoostAnimated(false); } - if(baseAdapter instanceof PixelfedListAdapter) + if (baseAdapter instanceof PixelfedListAdapter) ((PixelfedListAdapter) baseAdapter).notifyStatusChanged(status); - else if(baseAdapter instanceof StatusListAdapter) + else if (baseAdapter instanceof StatusListAdapter) ((StatusListAdapter) baseAdapter).notifyStatusChanged(status); } new PostActionAsyncTask(context, currentAccount, status, action, onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); @@ -923,13 +932,14 @@ public class CrossActions { /** * Follow/Unfollow an account + * * @param account Account */ - private static void followAction(Context context, Account account, RecyclerView.Adapter baseAdapter, OnPostActionInterface onPostActionInterface){ - if( account.isFollowing()){ + private static void followAction(Context context, Account account, RecyclerView.Adapter baseAdapter, OnPostActionInterface onPostActionInterface) { + if (account.isFollowing()) { new PostActionAsyncTask(context, API.StatusAction.UNFOLLOW, account.getId(), onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); account.setFollowing(false); - }else{ + } else { new PostActionAsyncTask(context, API.StatusAction.FOLLOW, account.getId(), onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); account.setFollowing(true); } @@ -938,14 +948,15 @@ public class CrossActions { /** * Favourites/Unfavourites a status + * * @param status Status */ - private static void favouriteAction(Context context, Status status,OnPostActionInterface onPostActionInterface){ + private static void favouriteAction(Context context, Status status, OnPostActionInterface onPostActionInterface) { - if( status.isFavourited() || (status.getReblog() != null && status.getReblog().isFavourited())){ + if (status.isFavourited() || (status.getReblog() != null && status.getReblog().isFavourited())) { new PostActionAsyncTask(context, API.StatusAction.UNFAVOURITE, status.getId(), onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); status.setFavourited(false); - }else{ + } else { new PostActionAsyncTask(context, API.StatusAction.FAVOURITE, status.getId(), onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); status.setFavourited(true); } @@ -953,14 +964,15 @@ public class CrossActions { /** * Reblog/Unreblog a status + * * @param status Status */ - private static void reblogAction(Context context, Status status, OnPostActionInterface onPostActionInterface){ - if( status.isReblogged() || (status.getReblog()!= null && status.getReblog().isReblogged())){ - String statusId = status.getReblog()!=null?status.getReblog().getId():status.getId(); + private static void reblogAction(Context context, Status status, OnPostActionInterface onPostActionInterface) { + if (status.isReblogged() || (status.getReblog() != null && status.getReblog().isReblogged())) { + String statusId = status.getReblog() != null ? status.getReblog().getId() : status.getId(); new PostActionAsyncTask(context, API.StatusAction.UNREBLOG, statusId, onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); status.setReblogged(false); - }else{ + } else { new PostActionAsyncTask(context, API.StatusAction.REBLOG, status.getId(), onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); status.setReblogged(true); } @@ -968,6 +980,7 @@ public class CrossActions { /** * Pin or unpin a status + * * @param status Status */ private static void pinAction(Context context, Status status, RecyclerView.Adapter baseAdapter, OnPostActionInterface onPostActionInterface) { @@ -983,6 +996,4 @@ public class CrossActions { } - - } diff --git a/app/src/main/java/app/fedilab/android/helper/CustomQuoteSpan.java b/app/src/main/java/app/fedilab/android/helper/CustomQuoteSpan.java index 38c25deec..fdc55b5ac 100644 --- a/app/src/main/java/app/fedilab/android/helper/CustomQuoteSpan.java +++ b/app/src/main/java/app/fedilab/android/helper/CustomQuoteSpan.java @@ -9,7 +9,6 @@ import android.text.style.LineBackgroundSpan; import org.jetbrains.annotations.NotNull; /** - * * Original work from @heath-borders: https://stackoverflow.com/a/29114976/3197259 */ public class CustomQuoteSpan implements LeadingMarginSpan, LineBackgroundSpan { diff --git a/app/src/main/java/app/fedilab/android/helper/CustomTextView.java b/app/src/main/java/app/fedilab/android/helper/CustomTextView.java index ceb46e572..53fcb1f0c 100644 --- a/app/src/main/java/app/fedilab/android/helper/CustomTextView.java +++ b/app/src/main/java/app/fedilab/android/helper/CustomTextView.java @@ -14,14 +14,17 @@ package app.fedilab.android.helper; * * You should have received a copy of the GNU General Public License along with Fedilab; if not, * see . */ + import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import android.content.res.TypedArray; import android.graphics.Paint; + import androidx.annotation.DimenRes; import androidx.annotation.Px; import androidx.appcompat.widget.AppCompatTextView; + import android.text.SpannableStringBuilder; import android.util.AttributeSet; @@ -39,6 +42,7 @@ public class CustomTextView extends AppCompatTextView { private float emojiSize; private boolean emoji; + public CustomTextView(Context context) { super(context); } @@ -67,25 +71,29 @@ public class CustomTextView extends AppCompatTextView { @Override public void setText(final CharSequence rawText, final BufferType type) { - if( emoji) { + if (emoji) { final CharSequence text = rawText == null ? "" : rawText; final SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text); final Paint.FontMetrics fontMetrics = getPaint().getFontMetrics(); final float defaultEmojiSize = fontMetrics.descent - fontMetrics.ascent; EmojiManager.getInstance().replaceWithImages(getContext(), spannableStringBuilder, emojiSize, defaultEmojiSize); super.setText(spannableStringBuilder, type); - }else { + } else { super.setText(rawText, type); } } - /** sets the emoji size in pixels and automatically invalidates the text and renders it with the new size */ + /** + * sets the emoji size in pixels and automatically invalidates the text and renders it with the new size + */ public final void setEmojiSize(@Px final int pixels) { setEmojiSize(pixels, true); } - /** sets the emoji size in pixels and automatically invalidates the text and renders it with the new size when {@code shouldInvalidate} is true */ + /** + * sets the emoji size in pixels and automatically invalidates the text and renders it with the new size when {@code shouldInvalidate} is true + */ public final void setEmojiSize(@Px final int pixels, final boolean shouldInvalidate) { emojiSize = pixels; @@ -94,12 +102,16 @@ public class CustomTextView extends AppCompatTextView { } } - /** sets the emoji size in pixels with the provided resource and automatically invalidates the text and renders it with the new size */ + /** + * sets the emoji size in pixels with the provided resource and automatically invalidates the text and renders it with the new size + */ public final void setEmojiSizeRes(@DimenRes final int res) { setEmojiSizeRes(res, true); } - /** sets the emoji size in pixels with the provided resource and invalidates the text and renders it with the new size when {@code shouldInvalidate} is true */ + /** + * sets the emoji size in pixels with the provided resource and invalidates the text and renders it with the new size when {@code shouldInvalidate} is true + */ public final void setEmojiSizeRes(@DimenRes final int res, final boolean shouldInvalidate) { setEmojiSize(getResources().getDimensionPixelSize(res), shouldInvalidate); } diff --git a/app/src/main/java/app/fedilab/android/helper/EmojiEditTextInterface.java b/app/src/main/java/app/fedilab/android/helper/EmojiEditTextInterface.java index f2acc2e2f..8fd07f791 100644 --- a/app/src/main/java/app/fedilab/android/helper/EmojiEditTextInterface.java +++ b/app/src/main/java/app/fedilab/android/helper/EmojiEditTextInterface.java @@ -12,15 +12,23 @@ public interface EmojiEditTextInterface { float getEmojiSize(); - /** sets the emoji size in pixels and automatically invalidates the text and renders it with the new size */ + /** + * sets the emoji size in pixels and automatically invalidates the text and renders it with the new size + */ void setEmojiSize(@Px int pixels); - /** sets the emoji size in pixels and automatically invalidates the text and renders it with the new size when {@code shouldInvalidate} is true */ + /** + * sets the emoji size in pixels and automatically invalidates the text and renders it with the new size when {@code shouldInvalidate} is true + */ void setEmojiSize(@Px int pixels, boolean shouldInvalidate); - /** sets the emoji size in pixels with the provided resource and automatically invalidates the text and renders it with the new size */ + /** + * sets the emoji size in pixels with the provided resource and automatically invalidates the text and renders it with the new size + */ void setEmojiSizeRes(@DimenRes int res); - /** sets the emoji size in pixels with the provided resource and invalidates the text and renders it with the new size when {@code shouldInvalidate} is true */ + /** + * sets the emoji size in pixels with the provided resource and invalidates the text and renders it with the new size when {@code shouldInvalidate} is true + */ void setEmojiSizeRes(@DimenRes int res, boolean shouldInvalidate); } diff --git a/app/src/main/java/app/fedilab/android/helper/ExpandableHeightListView.java b/app/src/main/java/app/fedilab/android/helper/ExpandableHeightListView.java index 1e06397cb..894ac5042 100644 --- a/app/src/main/java/app/fedilab/android/helper/ExpandableHeightListView.java +++ b/app/src/main/java/app/fedilab/android/helper/ExpandableHeightListView.java @@ -11,37 +11,30 @@ import android.widget.ListView; * Expanded listview */ -public class ExpandableHeightListView extends ListView - { +public class ExpandableHeightListView extends ListView { - boolean expanded = false; + boolean expanded = false; - public ExpandableHeightListView(Context context) - { - super(context); - } + public ExpandableHeightListView(Context context) { + super(context); + } - public ExpandableHeightListView(Context context, AttributeSet attrs) - { - super(context, attrs); - } + public ExpandableHeightListView(Context context, AttributeSet attrs) { + super(context, attrs); + } - public ExpandableHeightListView(Context context, AttributeSet attrs,int defStyle) - { - super(context, attrs, defStyle); - } + public ExpandableHeightListView(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + } - public boolean isExpanded() - { + public boolean isExpanded() { return expanded; } @Override - public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) - { + public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // HACK! TAKE THAT ANDROID! - if (isExpanded()) - { + if (isExpanded()) { // Calculate entire height by providing a very large height hint. // But do not use the highest 2 bits of this integer; those are // reserved for the MeasureSpec mode. @@ -50,15 +43,12 @@ public class ExpandableHeightListView extends ListView ViewGroup.LayoutParams params = getLayoutParams(); params.height = getMeasuredHeight(); - } - else - { + } else { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } } - public void setExpanded(@SuppressWarnings("SameParameterValue") boolean expanded) - { + public void setExpanded(@SuppressWarnings("SameParameterValue") boolean expanded) { this.expanded = expanded; } } \ No newline at end of file diff --git a/app/src/main/java/app/fedilab/android/helper/FileNameCleaner.java b/app/src/main/java/app/fedilab/android/helper/FileNameCleaner.java index b16fdb9ad..ec78f9b5d 100644 --- a/app/src/main/java/app/fedilab/android/helper/FileNameCleaner.java +++ b/app/src/main/java/app/fedilab/android/helper/FileNameCleaner.java @@ -16,7 +16,7 @@ public class FileNameCleaner { public static String cleanFileName(String badFileName) { StringBuilder cleanName = new StringBuilder(); int len = badFileName.codePointCount(0, badFileName.length()); - for (int i=0; i emoji = new HashMap<>(); @@ -579,22 +583,23 @@ public class Helper { try { BufferedReader br = new BufferedReader(new InputStreamReader(context.getAssets().open("emoji.csv"))); String line; - while( (line = br.readLine()) != null) { + while ((line = br.readLine()) != null) { String str[] = line.split(","); String unicode = null; - if(str.length == 2) - unicode = new String(new int[] {Integer.parseInt(str[1].replace("0x","").trim(), 16)}, 0, 1); - else if(str.length == 3) - unicode = new String(new int[] {Integer.parseInt(str[1].replace("0x","").trim(), 16), Integer.parseInt(str[2].replace("0x","").trim(), 16)}, 0, 2); - else if(str.length == 4) - unicode = new String(new int[] {Integer.parseInt(str[1].replace("0x","").trim(), 16), Integer.parseInt(str[2].replace("0x","").trim(), 16), Integer.parseInt(str[3].replace("0x","").trim(), 16)}, 0, 3); - else if(str.length == 5) - unicode = new String(new int[] {Integer.parseInt(str[1].replace("0x","").trim(), 16), Integer.parseInt(str[2].replace("0x","").trim(), 16), Integer.parseInt(str[3].replace("0x","").trim(), 16), Integer.parseInt(str[4].replace("0x","").trim(), 16)}, 0, 4); - if( unicode != null) - emoji.put(str[0],unicode); + if (str.length == 2) + unicode = new String(new int[]{Integer.parseInt(str[1].replace("0x", "").trim(), 16)}, 0, 1); + else if (str.length == 3) + unicode = new String(new int[]{Integer.parseInt(str[1].replace("0x", "").trim(), 16), Integer.parseInt(str[2].replace("0x", "").trim(), 16)}, 0, 2); + else if (str.length == 4) + unicode = new String(new int[]{Integer.parseInt(str[1].replace("0x", "").trim(), 16), Integer.parseInt(str[2].replace("0x", "").trim(), 16), Integer.parseInt(str[3].replace("0x", "").trim(), 16)}, 0, 3); + else if (str.length == 5) + unicode = new String(new int[]{Integer.parseInt(str[1].replace("0x", "").trim(), 16), Integer.parseInt(str[2].replace("0x", "").trim(), 16), Integer.parseInt(str[3].replace("0x", "").trim(), 16), Integer.parseInt(str[4].replace("0x", "").trim(), 16)}, 0, 4); + if (unicode != null) + emoji.put(str[0], unicode); } br.close(); - } catch (IOException ignored) {} + } catch (IOException ignored) { + } } /*** @@ -603,10 +608,10 @@ public class Helper { */ public static boolean isConnectedToInternet(Context context, String instance) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); - if( cm == null) + if (cm == null) return true; NetworkInfo ni = cm.getActiveNetworkInfo(); - if ( ni != null && ni.isConnected()) { + if (ni != null && ni.isConnected()) { try { InetAddress ipAddr = InetAddress.getByName(instance); return !ipAddr.toString().equals(""); @@ -620,17 +625,19 @@ public class Helper { /** * Returns boolean depending if the user is authenticated + * * @param context Context * @return boolean */ public static boolean isLoggedIn(Context context) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String prefKeyOauthTokenT = sharedpreferences.getString(PREF_KEY_OAUTH_TOKEN, null); - return ( prefKeyOauthTokenT != null); + return (prefKeyOauthTokenT != null); } /** * Log out the authenticated user by removing its token + * * @param context Context */ public static void logout(Context context) { @@ -649,6 +656,7 @@ public class Helper { /** * Log out the authenticated user by removing its token + * * @param activity Activity */ public static void logoutCurrentUser(Activity activity) { @@ -659,13 +667,13 @@ public class Helper { String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(activity)); Account account = new AccountDAO(activity, db).getUniqAccount(userId, instance); - if( account != null) { + if (account != null) { account.setToken("null"); new AccountDAO(activity, db).updateAccount(account); } Account newAccount = new AccountDAO(activity, db).getLastUsedAccount(); SharedPreferences.Editor editor = sharedpreferences.edit(); - if( newAccount == null){ + if (newAccount == null) { editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, null); editor.putString(Helper.CLIENT_ID, null); editor.putString(Helper.CLIENT_SECRET, null); @@ -675,7 +683,7 @@ public class Helper { editor.putString(Helper.PREF_INSTANCE, null); editor.putString(Helper.ID, null); editor.apply(); - }else{ + } else { editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, newAccount.getToken()); editor.putString(Helper.PREF_KEY_ID, newAccount.getId()); editor.putString(Helper.PREF_INSTANCE, newAccount.getInstance().trim()); @@ -694,8 +702,9 @@ public class Helper { /** * Convert String date from Mastodon + * * @param context Context - * @param date String + * @param date String * @return Date */ public static Date mstStringToDate(Context context, String date) throws ParseException { @@ -706,7 +715,7 @@ public class Helper { Locale local = Locale.getDefault(); if (!date.contains("+")) { STRING_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; - } else{ //GNU date format + } else { //GNU date format STRING_DATE_FORMAT = "EEE MMM dd HH:mm:ss ZZZZZ yyyy"; local = Locale.ENGLISH; } @@ -715,7 +724,7 @@ public class Helper { simpleDateFormat.setLenient(true); try { return simpleDateFormat.parse(date); - }catch (Exception e){ + } catch (Exception e) { String newdate = date.split("\\+")[0].trim(); simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", local); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("gmt")); @@ -726,13 +735,14 @@ public class Helper { /** * Convert String date from Mastodon + * * @param context Context - * @param date String + * @param date String * @return Date */ public static Date opencollectivetStringToDate(Context context, String date) throws ParseException { Locale userLocale; - if (date == null ) + if (date == null) return null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { userLocale = context.getResources().getConfiguration().getLocales().get(0); @@ -750,30 +760,33 @@ public class Helper { /** * Convert a date in String -> format yyyy-MM-dd HH:mm:ss + * * @param date Date * @return String */ public static String dateToString(Date date) { - if( date == null) + if (date == null) return null; - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.getDefault()); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); return dateFormat.format(date); } /** * Convert a date in String -> format yyyy-MM-dd HH:mm:ss + * * @param date Date * @return String */ public static String dateToStringPoll(Date date) { - if( date == null) + if (date == null) return null; - SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd HH:mm",Locale.getDefault()); + SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd HH:mm", Locale.getDefault()); return dateFormat.format(date); } /** * Convert a date in String -> format yyyy-MM-dd HH:mm:ss + * * @param date Date * @return String */ @@ -784,8 +797,9 @@ public class Helper { /** * Convert a date in String -> format yyyy-MM-dd HH:mm:ss + * * @param context Context - * @param date Date + * @param date Date * @return String */ public static String dateFileToString(Context context, Date date) { @@ -796,17 +810,18 @@ public class Helper { //noinspection deprecation userLocale = context.getResources().getConfiguration().locale; } - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss",userLocale); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", userLocale); return dateFormat.format(date); } /** * Convert String date from db to Date Object + * * @param stringDate date to convert * @return Date */ public static Date stringToDate(Context context, String stringDate) { - if( stringDate == null) + if (stringDate == null) return null; Locale userLocale; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { @@ -815,7 +830,7 @@ public class Helper { //noinspection deprecation userLocale = context.getResources().getConfiguration().locale; } - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",userLocale); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", userLocale); Date date = null; try { date = dateFormat.parse(stringDate); @@ -827,8 +842,9 @@ public class Helper { /** * Converts a Date date into a date-time string (SHORT format for both) + * * @param context Context - * @param date to be converted + * @param date to be converted * @return String */ @@ -849,10 +865,11 @@ public class Helper { /** * Makes the tvDate TextView field clickable, and displays the absolute date & time of a toot - * for 5 seconds. + * for 5 seconds. + * * @param context Context - * @param tvDate TextView - * @param date Date + * @param tvDate TextView + * @param date Date */ public static void absoluteDateTimeReveal(final Context context, final TextView tvDate, final Date date) { @@ -877,6 +894,7 @@ public class Helper { /** * Check if WIFI is opened + * * @param context Context * @return boolean */ @@ -888,11 +906,11 @@ public class Helper { } - public static String dateDiffFull(Date dateToot){ + public static String dateDiffFull(Date dateToot) { SimpleDateFormat df = (SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.MEDIUM, Locale.getDefault()); try { return df.format(dateToot); - }catch (Exception e){ + } catch (Exception e) { return ""; } } @@ -903,7 +921,7 @@ public class Helper { * @param dateToot Date * @return String */ - public static String dateDiff(Context context, Date dateToot){ + public static String dateDiff(Context context, Date dateToot) { Date now = new Date(); long diff = now.getTime() - dateToot.getTime(); long seconds = diff / 1000; @@ -914,19 +932,19 @@ public class Helper { long years = days / 365; String format = DateFormat.getDateInstance(DateFormat.SHORT).format(dateToot); - if( years > 0 ) { + if (years > 0) { return format; - } else if( months > 0 || days > 7) { + } else if (months > 0 || days > 7) { //Removes the year depending of the locale from DateFormat.SHORT format SimpleDateFormat df = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault()); df.applyPattern(df.toPattern().replaceAll("[^\\p{Alpha}]*y+[^\\p{Alpha}]*", "")); return df.format(dateToot); - }else if( days > 0 ) + } else if (days > 0) return context.getString(R.string.date_day, days); - else if(hours > 0) - return context.getResources().getString(R.string.date_hours, (int)hours); - else if(minutes > 0) - return context.getResources().getString(R.string.date_minutes, (int)minutes); + else if (hours > 0) + return context.getResources().getString(R.string.date_hours, (int) hours); + else if (minutes > 0) + return context.getResources().getString(R.string.date_minutes, (int) minutes); else { if (seconds < 0) seconds = 0; @@ -940,92 +958,89 @@ public class Helper { * @param statusCode int the status code * @param statusAction API.StatusAction the initial action */ - public static void manageMessageStatusCode(Context context, int statusCode, API.StatusAction statusAction){ + public static void manageMessageStatusCode(Context context, int statusCode, API.StatusAction statusAction) { String message = ""; final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); boolean display_confirm = sharedpreferences.getBoolean(Helper.SET_DISPLAY_CONFIRM, true); - if( !display_confirm){ + if (!display_confirm) { return; } - if( statusCode >= 200 && statusCode < 400 ){ - if( statusAction == API.StatusAction.BLOCK){ + if (statusCode >= 200 && statusCode < 400) { + if (statusAction == API.StatusAction.BLOCK) { message = context.getString(R.string.toast_block); - }else if(statusAction == API.StatusAction.UNBLOCK){ + } else if (statusAction == API.StatusAction.UNBLOCK) { message = context.getString(R.string.toast_unblock); - }else if(statusAction == API.StatusAction.REBLOG){ + } else if (statusAction == API.StatusAction.REBLOG) { message = context.getString(R.string.toast_reblog); - }else if(statusAction == API.StatusAction.UNREBLOG){ + } else if (statusAction == API.StatusAction.UNREBLOG) { message = context.getString(R.string.toast_unreblog); - }else if(statusAction == API.StatusAction.MUTE){ + } else if (statusAction == API.StatusAction.MUTE) { message = context.getString(R.string.toast_mute); - }else if(statusAction == API.StatusAction.UNMUTE){ + } else if (statusAction == API.StatusAction.UNMUTE) { message = context.getString(R.string.toast_unmute); - }else if(statusAction == API.StatusAction.MUTE_CONVERSATION){ + } else if (statusAction == API.StatusAction.MUTE_CONVERSATION) { message = context.getString(R.string.toast_mute_conversation); - }else if(statusAction == API.StatusAction.UNMUTE_CONVERSATION){ + } else if (statusAction == API.StatusAction.UNMUTE_CONVERSATION) { message = context.getString(R.string.toast_unmute_conversation); - }else if(statusAction == API.StatusAction.FOLLOW){ + } else if (statusAction == API.StatusAction.FOLLOW) { message = context.getString(R.string.toast_follow); - }else if(statusAction == API.StatusAction.UNFOLLOW){ + } else if (statusAction == API.StatusAction.UNFOLLOW) { message = context.getString(R.string.toast_unfollow); - }else if(statusAction == API.StatusAction.FAVOURITE){ + } else if (statusAction == API.StatusAction.FAVOURITE) { message = context.getString(R.string.toast_favourite); - }else if(statusAction == API.StatusAction.UNFAVOURITE){ + } else if (statusAction == API.StatusAction.UNFAVOURITE) { message = context.getString(R.string.toast_unfavourite); - }else if(statusAction == API.StatusAction.PIN){ + } else if (statusAction == API.StatusAction.PIN) { message = context.getString(R.string.toast_pin); - }else if (statusAction == API.StatusAction.UNPIN){ + } else if (statusAction == API.StatusAction.UNPIN) { message = context.getString(R.string.toast_unpin); - }else if(statusAction == API.StatusAction.REPORT){ + } else if (statusAction == API.StatusAction.REPORT) { message = context.getString(R.string.toast_report); - }else if(statusAction == API.StatusAction.UNSTATUS){ + } else if (statusAction == API.StatusAction.UNSTATUS) { message = context.getString(R.string.toast_unstatus); - }else if(statusAction == API.StatusAction.UNENDORSE){ + } else if (statusAction == API.StatusAction.UNENDORSE) { message = context.getString(R.string.toast_unendorse); - }else if(statusAction == API.StatusAction.ENDORSE){ + } else if (statusAction == API.StatusAction.ENDORSE) { message = context.getString(R.string.toast_endorse); - }else if(statusAction == API.StatusAction.SHOW_BOOST){ + } else if (statusAction == API.StatusAction.SHOW_BOOST) { message = context.getString(R.string.toast_show_boost); - }else if(statusAction == API.StatusAction.HIDE_BOOST){ + } else if (statusAction == API.StatusAction.HIDE_BOOST) { message = context.getString(R.string.toast_hide_boost); - }else if(statusAction == API.StatusAction.BLOCK_DOMAIN){ + } else if (statusAction == API.StatusAction.BLOCK_DOMAIN) { message = context.getString(R.string.toast_block_domain); } - }else { + } else { message = context.getString(R.string.toast_error); } - if( !message.trim().equals("")) + if (!message.trim().equals("")) Toasty.success(context, message, Toast.LENGTH_LONG).show(); } - - - - /** * Manage downloads with URLs + * * @param context Context - * @param url String download url + * @param url String download url */ - public static void manageDownloads(final Context context, final String url){ + public static void manageDownloads(final Context context, final String url) { final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } final AlertDialog.Builder builder = new AlertDialog.Builder(context, style); final DownloadManager.Request request; try { request = new DownloadManager.Request(Uri.parse(url.trim())); - }catch (Exception e){ - Toasty.error(context,context.getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + } catch (Exception e) { + Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); return; } final String fileName = URLUtil.guessFileName(url, null, null); @@ -1049,7 +1064,7 @@ public class Helper { } }); AlertDialog alert = builder.create(); - if( alert.getWindow() != null ) + if (alert.getWindow() != null) alert.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); alert.show(); } @@ -1070,13 +1085,14 @@ public class Helper { /** * Sends notification with intent + * * @param context Context - * @param intent Intent associated to the notifcation - * @param icon Bitmap profile picture - * @param title String title of the notification + * @param intent Intent associated to the notifcation + * @param icon Bitmap profile picture + * @param title String title of the notification * @param message String message for the notification */ - public static void notify_user(Context context, Account account, Intent intent, Bitmap icon, NotifType notifType, String title, String message ) { + public static void notify_user(Context context, Account account, Intent intent, Bitmap icon, NotifType notifType, String title, String message) { final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); // prepare intent which is triggered if the user click on the notification NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); @@ -1091,7 +1107,7 @@ public class Helper { val = String.valueOf(count); }*/ - int notificationId = (int)System.currentTimeMillis(); + int notificationId = (int) System.currentTimeMillis(); PendingIntent pIntent = PendingIntent.getActivity(context, notificationId, intent, PendingIntent.FLAG_ONE_SHOT); intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_CLEAR_TOP); @@ -1100,9 +1116,9 @@ public class Helper { String channelId; String channelTitle; - switch(notifType){ + switch (notifType) { case BOOST: - channelId = "channel_boost"+account.getAcct()+"@"+account.getInstance(); + channelId = "channel_boost" + account.getAcct() + "@" + account.getInstance(); channelTitle = context.getString(R.string.channel_notif_boost); break; case FAV: @@ -1143,12 +1159,12 @@ public class Helper { .setWhen(System.currentTimeMillis()) .setAutoCancel(true); if (notifType == MENTION) { - if(message.length() > 500){ - message = message.substring(0, 499)+"…"; + if (message.length() > 500) { + message = message.substring(0, 499) + "…"; } notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(message)); } - notificationBuilder.setGroup(account.getAcct()+"@"+account.getInstance()) + notificationBuilder.setGroup(account.getAcct() + "@" + account.getInstance()) .setContentIntent(pIntent) .setContentText(message); int ledColour = Color.BLUE; @@ -1180,15 +1196,15 @@ public class Helper { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel; NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); - if( sharedpreferences.getBoolean(Helper.SET_NOTIF_SILENT,false) ) { + if (sharedpreferences.getBoolean(Helper.SET_NOTIF_SILENT, false)) { channel = new NotificationChannel(channelId, channelTitle, NotificationManager.IMPORTANCE_LOW); channel.setSound(null, null); - channel.setVibrationPattern(new long[] { 500, 500, 500}); + channel.setVibrationPattern(new long[]{500, 500, 500}); channel.enableVibration(true); channel.setLightColor(ledColour); - }else { + } else { channel = new NotificationChannel(channelId, channelTitle, NotificationManager.IMPORTANCE_HIGH); - String soundUri = sharedpreferences.getString(Helper.SET_NOTIF_SOUND, ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() +"/"+ R.raw.boop); + String soundUri = sharedpreferences.getString(Helper.SET_NOTIF_SOUND, ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/" + R.raw.boop); AudioAttributes audioAttributes = new AudioAttributes.Builder() .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) .setUsage(AudioAttributes.USAGE_NOTIFICATION) @@ -1197,11 +1213,11 @@ public class Helper { } assert mNotificationManager != null; mNotificationManager.createNotificationChannel(channel); - }else{ - if( sharedpreferences.getBoolean(Helper.SET_NOTIF_SILENT,false) ) { - notificationBuilder.setVibrate(new long[] { 500, 500, 500}); - }else { - String soundUri =sharedpreferences.getString(Helper.SET_NOTIF_SOUND, ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() +"/"+ R.raw.boop); + } else { + if (sharedpreferences.getBoolean(Helper.SET_NOTIF_SILENT, false)) { + notificationBuilder.setVibrate(new long[]{500, 500, 500}); + } else { + String soundUri = sharedpreferences.getString(Helper.SET_NOTIF_SOUND, ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/" + R.raw.boop); notificationBuilder.setSound(Uri.parse(soundUri)); } notificationBuilder.setLights(ledColour, 500, 1000); @@ -1214,10 +1230,11 @@ public class Helper { /** * Manage downloads with URLs + * * @param context Context - * @param url String download url + * @param url String download url */ - public static void manageMoveFileDownload(final Context context, final String preview_url, final String url, Bitmap bitmap, File fileVideo, boolean isSharing){ + public static void manageMoveFileDownload(final Context context, final String preview_url, final String url, Bitmap bitmap, File fileVideo, boolean isSharing) { final String fileName = URLUtil.guessFileName(url, null, null); final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); @@ -1225,13 +1242,13 @@ public class Helper { String mime = getMimeType(url); try { File file; - if( bitmap != null) { + if (bitmap != null) { file = new File(myDir, fileName); //noinspection ResultOfMethodCallIgnored file.createNewFile(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); - if( mime !=null && (mime.contains("png") || mime.contains(".PNG"))) + if (mime != null && (mime.contains("png") || mime.contains(".PNG"))) bitmap.compress(Bitmap.CompressFormat.PNG, 0, bos); else bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos); @@ -1241,7 +1258,7 @@ public class Helper { fos.write(bitmapdata); fos.flush(); fos.close(); - }else{ + } else { File fileVideoTargeded = new File(myDir, fileName); copy(fileVideo, fileVideoTargeded); file = fileVideoTargeded; @@ -1253,11 +1270,11 @@ public class Helper { Uri uri = Uri.parse("file://" + file.getAbsolutePath()); intent.setDataAndType(uri, getMimeType(url)); - if( !isSharing) + if (!isSharing) Glide.with(context) .asBitmap() .load(preview_url) - .listener(new RequestListener(){ + .listener(new RequestListener() { @Override public boolean onResourceReady(Bitmap resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) { @@ -1271,8 +1288,8 @@ public class Helper { String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(context)); Account account = new AccountDAO(context, db).getUniqAccount(userId, instance); notify_user(context, account, intent, BitmapFactory.decodeResource(context.getResources(), - R.mipmap.ic_launcher), NotifType.STORE, context.getString(R.string.save_over), context.getString(R.string.download_from, fileName)); - Toasty.success(context, context.getString(R.string.toast_saved),Toast.LENGTH_LONG).show(); + R.mipmap.ic_launcher), NotifType.STORE, context.getString(R.string.save_over), context.getString(R.string.download_from, fileName)); + Toasty.success(context, context.getString(R.string.toast_saved), Toast.LENGTH_LONG).show(); return false; } }) @@ -1283,13 +1300,13 @@ public class Helper { String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(context)); Account account = new AccountDAO(context, db).getUniqAccount(userId, instance); - notify_user(context, account, intent, resource, NotifType.STORE, context.getString(R.string.save_over), context.getString(R.string.download_from, fileName)); - Toasty.success(context, context.getString(R.string.toast_saved),Toast.LENGTH_LONG).show(); + notify_user(context, account, intent, resource, NotifType.STORE, context.getString(R.string.save_over), context.getString(R.string.download_from, fileName)); + Toasty.success(context, context.getString(R.string.toast_saved), Toast.LENGTH_LONG).show(); } }); else { Intent shareIntent = new Intent(Intent.ACTION_SEND); - if( bitmap != null) + if (bitmap != null) shareIntent.setType("image/*"); else shareIntent.setType("video/*"); @@ -1297,12 +1314,14 @@ public class Helper { shareIntent.putExtra(Intent.EXTRA_TEXT, R.string.share_with); context.startActivity(shareIntent); } - } catch (Exception ignored) {} + } catch (Exception ignored) { + } } /** * Copy a file by transferring bytes from in to out + * * @param src File source file * @param dst File targeted file * @throws IOException Exception @@ -1319,20 +1338,23 @@ public class Helper { while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } - }catch (Exception ignored){}finally { + } catch (Exception ignored) { + } finally { out.close(); } - } catch (Exception ignored){}finally { + } catch (Exception ignored) { + } finally { in.close(); } } /** * Returns the instance of the authenticated user + * * @param context Context * @return String domain instance */ - public static String getLiveInstance(Context context){ + public static String getLiveInstance(Context context) { final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); return sharedpreferences.getString(Helper.PREF_INSTANCE, null); } @@ -1341,59 +1363,60 @@ public class Helper { return instanceWithProtocol(context, getLiveInstance(context)); } - public static String instanceWithProtocol(Context context, String instance){ - if( instance == null) + public static String instanceWithProtocol(Context context, String instance) { + if (instance == null) return null; - if( instance.endsWith(".onion")) { + if (instance.endsWith(".onion")) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - String scheme = sharedpreferences.getString(SET_ONION_SCHEME+instance, "http"); + String scheme = sharedpreferences.getString(SET_ONION_SCHEME + instance, "http"); return scheme + "://" + instance; - }else { + } else { return "https://" + instance; } } - /** * Converts dp to pixel - * @param dp float - the value in dp to convert + * + * @param dp float - the value in dp to convert * @param context Context * @return float - the converted value in pixel */ - public static float convertDpToPixel(float dp, Context context){ + public static float convertDpToPixel(float dp, Context context) { Resources resources = context.getResources(); DisplayMetrics metrics = resources.getDisplayMetrics(); - return dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT); + return dp * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT); } /** * Toggle for the menu (ie: main menu or accounts menu) + * * @param activity Activity */ - public static void menuAccounts(final Activity activity){ + public static void menuAccounts(final Activity activity) { final NavigationView navigationView = activity.findViewById(R.id.nav_view); SharedPreferences mSharedPreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String currrentUserId = mSharedPreferences.getString(Helper.PREF_KEY_ID, null); - final ImageView arrow = navigationView.getHeaderView(0).findViewById(R.id.owner_accounts); - if( currrentUserId == null) + final ImageView arrow = navigationView.getHeaderView(0).findViewById(R.id.owner_accounts); + if (currrentUserId == null) return; final SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if( theme == Helper.THEME_DARK || theme == Helper.THEME_BLACK){ - changeDrawableColor(activity, R.drawable.ic_person_add,R.color.dark_text); - changeDrawableColor(activity, R.drawable.ic_person,R.color.dark_text); - changeDrawableColor(activity, R.drawable.ic_cancel,R.color.dark_text); - }else { - changeDrawableColor(activity, R.drawable.ic_person_add,R.color.black); - changeDrawableColor(activity, R.drawable.ic_person,R.color.black); - changeDrawableColor(activity, R.drawable.ic_cancel,R.color.black); + if (theme == Helper.THEME_DARK || theme == Helper.THEME_BLACK) { + changeDrawableColor(activity, R.drawable.ic_person_add, R.color.dark_text); + changeDrawableColor(activity, R.drawable.ic_person, R.color.dark_text); + changeDrawableColor(activity, R.drawable.ic_cancel, R.color.dark_text); + } else { + changeDrawableColor(activity, R.drawable.ic_person_add, R.color.black); + changeDrawableColor(activity, R.drawable.ic_person, R.color.black); + changeDrawableColor(activity, R.drawable.ic_cancel, R.color.black); } - if( !menuAccountsOpened ){ + if (!menuAccountsOpened) { arrow.setImageResource(R.drawable.ic_arrow_drop_up); SQLiteDatabase db = Sqlite.getInstance(activity, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); final List accounts = new AccountDAO(activity, db).getAllAccount(); @@ -1402,94 +1425,94 @@ public class Helper { navigationView.inflateMenu(R.menu.menu_accounts); Menu mainMenu = navigationView.getMenu(); SubMenu currentSubmenu = null; - if( accounts != null) - for(final Account account: accounts) { + if (accounts != null) + for (final Account account : accounts) { - if( !currrentUserId.equals(account.getId()) || !getLiveInstance(activity).equals(account.getInstance()) ) { - if( !lastInstance.trim().toUpperCase().equals(account.getInstance().trim().toUpperCase())){ - lastInstance = account.getInstance().toUpperCase(); - currentSubmenu = mainMenu.addSubMenu(account.getInstance().toUpperCase()); - } - if( currentSubmenu == null) - continue; - final MenuItem item = currentSubmenu.add("@" + account.getAcct()); - item.setIcon(R.drawable.ic_person); - String url = account.getAvatar(); - if( url.startsWith("/") ){ - url = "https://" + account.getInstance() + account.getAvatar(); - } - if(!url.equals("null")) - Glide.with(navigationView.getContext()) - .asBitmap() - .load(url) - .into(new SimpleTarget() { - @Override - public void onResourceReady(@NonNull Bitmap resource, Transition transition) { - item.setIcon(new BitmapDrawable(activity.getResources(), resource)); - item.getIcon().setColorFilter(0xFFFFFFFF, PorterDuff.Mode.MULTIPLY); + if (!currrentUserId.equals(account.getId()) || !getLiveInstance(activity).equals(account.getInstance())) { + if (!lastInstance.trim().toUpperCase().equals(account.getInstance().trim().toUpperCase())) { + lastInstance = account.getInstance().toUpperCase(); + currentSubmenu = mainMenu.addSubMenu(account.getInstance().toUpperCase()); + } + if (currentSubmenu == null) + continue; + final MenuItem item = currentSubmenu.add("@" + account.getAcct()); + item.setIcon(R.drawable.ic_person); + String url = account.getAvatar(); + if (url.startsWith("/")) { + url = "https://" + account.getInstance() + account.getAvatar(); + } + if (!url.equals("null")) + Glide.with(navigationView.getContext()) + .asBitmap() + .load(url) + .into(new SimpleTarget() { + @Override + public void onResourceReady(@NonNull Bitmap resource, Transition transition) { + item.setIcon(new BitmapDrawable(activity.getResources(), resource)); + item.getIcon().setColorFilter(0xFFFFFFFF, PorterDuff.Mode.MULTIPLY); + } + }); + else + Glide.with(navigationView.getContext()) + .asBitmap() + .load(R.drawable.missing_peertube) + .into(new SimpleTarget() { + @Override + public void onResourceReady(@NonNull Bitmap resource, Transition transition) { + item.setIcon(new BitmapDrawable(activity.getResources(), resource)); + item.getIcon().setColorFilter(0xFFFFFFFF, PorterDuff.Mode.MULTIPLY); + } + }); + + item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { + @Override + public boolean onMenuItemClick(MenuItem item) { + if (!activity.isFinishing()) { + menuAccountsOpened = false; + Toasty.info(activity.getApplicationContext(), activity.getString(R.string.toast_account_changed, "@" + account.getAcct() + "@" + account.getInstance()), Toast.LENGTH_LONG).show(); + changeUser(activity, account.getId(), account.getInstance(), false); + arrow.setImageResource(R.drawable.ic_arrow_drop_down); + return true; } - }); - else - Glide.with(navigationView.getContext()) - .asBitmap() - .load(R.drawable.missing_peertube) - .into(new SimpleTarget() { - @Override - public void onResourceReady(@NonNull Bitmap resource, Transition transition) { - item.setIcon(new BitmapDrawable(activity.getResources(), resource)); - item.getIcon().setColorFilter(0xFFFFFFFF, PorterDuff.Mode.MULTIPLY); - } - }); - - item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { - @Override - public boolean onMenuItemClick(MenuItem item) { - if( ! activity.isFinishing() ) { - menuAccountsOpened = false; - Toasty.info(activity.getApplicationContext(), activity.getString(R.string.toast_account_changed, "@" + account.getAcct() + "@" + account.getInstance()), Toast.LENGTH_LONG).show(); - changeUser(activity, account.getId(), account.getInstance(), false); - arrow.setImageResource(R.drawable.ic_arrow_drop_down); - return true; + return false; } - return false; - } - }); - item.setActionView(R.layout.update_account); - ImageView deleteButton = item.getActionView().findViewById(R.id.account_remove_button); - deleteButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - final SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - int style; - if (theme == Helper.THEME_DARK) { - style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ - style = R.style.DialogBlack; - }else { - style = R.style.Dialog; + }); + item.setActionView(R.layout.update_account); + ImageView deleteButton = item.getActionView().findViewById(R.id.account_remove_button); + deleteButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + final SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); + int style; + if (theme == Helper.THEME_DARK) { + style = R.style.DialogDark; + } else if (theme == Helper.THEME_BLACK) { + style = R.style.DialogBlack; + } else { + style = R.style.Dialog; + } + new AlertDialog.Builder(activity, style) + .setTitle(activity.getString(R.string.delete_account_title)) + .setMessage(activity.getString(R.string.delete_account_message, "@" + account.getAcct() + "@" + account.getInstance())) + .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + new RemoveAccountAsyncTask(activity, account).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + item.setVisible(false); + } + }) + .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + // do nothing + } + }) + .setIcon(android.R.drawable.ic_dialog_alert) + .show(); } - new AlertDialog.Builder(activity, style) - .setTitle(activity.getString(R.string.delete_account_title)) - .setMessage(activity.getString(R.string.delete_account_message, "@" + account.getAcct() + "@" + account.getInstance())) - .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - new RemoveAccountAsyncTask(activity, account).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - item.setVisible(false); - } - }) - .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - // do nothing - } - }) - .setIcon(android.R.drawable.ic_dialog_alert) - .show(); - } - }); + }); + } } - } currentSubmenu = mainMenu.addSubMenu(""); MenuItem addItem = currentSubmenu.add(R.string.add_account); addItem.setIcon(R.drawable.ic_person_add); @@ -1502,7 +1525,7 @@ public class Helper { return true; } }); - }else{ + } else { navigationView.getMenu().clear(); navigationView.inflateMenu(R.menu.activity_main_drawer); hideMenuItem(activity, navigationView.getMenu()); @@ -1513,119 +1536,119 @@ public class Helper { } - public static void hideMenuItem(Activity activity, Menu menu){ + public static void hideMenuItem(Activity activity, Menu menu) { - if( BaseMainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE){ + if (BaseMainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { MenuItem itemCom = menu.findItem(R.id.nav_main_com); - if( itemCom != null) + if (itemCom != null) itemCom.setVisible(false); MenuItem itemOpt = menu.findItem(R.id.nav_main_opt); - if( itemOpt != null) + if (itemOpt != null) itemOpt.setVisible(false); MenuItem itemPFCom = menu.findItem(R.id.nav_pixelfed_comm); - if( itemPFCom != null) + if (itemPFCom != null) itemPFCom.setVisible(false); - }else if( BaseMainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED){ + } else if (BaseMainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) { MenuItem itemCom = menu.findItem(R.id.nav_main_com); - if( itemCom != null) + if (itemCom != null) itemCom.setVisible(false); MenuItem itemOpt = menu.findItem(R.id.nav_main_opt); - if( itemOpt != null) + if (itemOpt != null) itemOpt.setVisible(false); MenuItem itemPCom = menu.findItem(R.id.nav_peertube_comm); - if( itemPCom != null) + if (itemPCom != null) itemPCom.setVisible(false); - }else if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA || BaseMainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || BaseMainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || BaseMainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA){ + } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA || BaseMainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || BaseMainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || BaseMainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { MenuItem itemCom = menu.findItem(R.id.nav_peertube_comm); - if( itemCom != null) + if (itemCom != null) itemCom.setVisible(false); MenuItem itemPFCom = menu.findItem(R.id.nav_pixelfed_comm); - if( itemPFCom != null) + if (itemPFCom != null) itemPFCom.setVisible(false); - if( BaseMainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA){ + if (BaseMainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { MenuItem nav_list = menu.findItem(R.id.nav_list); - if( nav_list != null) + if (nav_list != null) nav_list.setVisible(false); MenuItem nav_peertube = menu.findItem(R.id.nav_peertube); - if( nav_peertube != null) + if (nav_peertube != null) nav_peertube.setVisible(false); MenuItem nav_filters = menu.findItem(R.id.nav_filters); - if( nav_filters != null) + if (nav_filters != null) nav_filters.setVisible(false); MenuItem nav_follow_request = menu.findItem(R.id.nav_follow_request); - if( nav_follow_request != null) + if (nav_follow_request != null) nav_follow_request.setVisible(false); MenuItem nav_who_to_follow = menu.findItem(R.id.nav_who_to_follow); - if( nav_who_to_follow != null) + if (nav_who_to_follow != null) nav_who_to_follow.setVisible(false); MenuItem nav_blocked = menu.findItem(R.id.nav_blocked); - if( nav_blocked != null) + if (nav_blocked != null) nav_blocked.setVisible(false); MenuItem nav_muted = menu.findItem(R.id.nav_muted); - if( nav_muted != null) + if (nav_muted != null) nav_muted.setVisible(false); MenuItem nav_blocked_domains = menu.findItem(R.id.nav_blocked_domains); - if( nav_blocked_domains != null) + if (nav_blocked_domains != null) nav_blocked_domains.setVisible(false); - if(BaseMainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU ){ + if (BaseMainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU) { MenuItem nav_group = menu.findItem(R.id.nav_group); - if( nav_group != null) + if (nav_group != null) nav_group.setVisible(true); } - }else{ + } else { SQLiteDatabase db = Sqlite.getInstance(activity, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); MainMenuItem mainMenuItem = new MainMenuDAO(activity, db).getMainMenu(); - if (mainMenuItem == null){ + if (mainMenuItem == null) { mainMenuItem = new MainMenuItem(); } - if( !mainMenuItem.isNav_list()){ + if (!mainMenuItem.isNav_list()) { menu.findItem(R.id.nav_list).setVisible(false); } - if( !mainMenuItem.isNav_archive()){ + if (!mainMenuItem.isNav_archive()) { menu.findItem(R.id.nav_archive).setVisible(false); } - if( !mainMenuItem.isNav_archive_notifications()){ + if (!mainMenuItem.isNav_archive_notifications()) { menu.findItem(R.id.nav_archive_notifications).setVisible(false); } - if( !mainMenuItem.isNav_blocked()){ + if (!mainMenuItem.isNav_blocked()) { menu.findItem(R.id.nav_blocked).setVisible(false); } - if( !mainMenuItem.isNav_blocked_domains()){ + if (!mainMenuItem.isNav_blocked_domains()) { menu.findItem(R.id.nav_blocked_domains).setVisible(false); } - if( !mainMenuItem.isNav_filters()){ + if (!mainMenuItem.isNav_filters()) { menu.findItem(R.id.nav_filters).setVisible(false); } - if( !mainMenuItem.isNav_how_to_follow()){ + if (!mainMenuItem.isNav_how_to_follow()) { menu.findItem(R.id.nav_who_to_follow).setVisible(false); } - if( !mainMenuItem.isNav_howto()){ + if (!mainMenuItem.isNav_howto()) { menu.findItem(R.id.nav_how_to).setVisible(false); } - if( !mainMenuItem.isNav_muted()){ + if (!mainMenuItem.isNav_muted()) { menu.findItem(R.id.nav_muted).setVisible(false); } - if( !mainMenuItem.isNav_news()){ + if (!mainMenuItem.isNav_news()) { menu.findItem(R.id.nav_news).setVisible(false); } - if( !mainMenuItem.isNav_peertube()){ + if (!mainMenuItem.isNav_peertube()) { menu.findItem(R.id.nav_peertube).setVisible(false); } - if( !mainMenuItem.isNav_scheduled()){ + if (!mainMenuItem.isNav_scheduled()) { menu.findItem(R.id.nav_scheduled).setVisible(false); } } } if (!BuildConfig.DONATIONS) { MenuItem openCollectiveItem = menu.findItem(R.id.nav_opencollective); - if( openCollectiveItem != null){ + if (openCollectiveItem != null) { openCollectiveItem.setVisible(false); } MenuItem partnerShipItem = menu.findItem(R.id.nav_partnership); - if( partnerShipItem != null){ + if (partnerShipItem != null) { partnerShipItem.setVisible(false); } } @@ -1634,8 +1657,9 @@ public class Helper { /** * Changes the user in shared preferences + * * @param activity Activity - * @param userID String - the new user id + * @param userID String - the new user id */ public static void changeUser(Activity activity, String userID, String instance, boolean notificationIntent) { @@ -1648,15 +1672,15 @@ public class Helper { hideMenuItem(activity, navigationView.getMenu()); SQLiteDatabase db = Sqlite.getInstance(activity, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - Account account = new AccountDAO(activity,db).getUniqAccount(userID, instance); + Account account = new AccountDAO(activity, db).getUniqAccount(userID, instance); //Can happen when an account has been deleted and there is a click on an old notification - if( account == null) + if (account == null) return; String token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); - if( !account.getToken().equals(token)){ + if (!account.getToken().equals(token)) { FragmentManager fm = activity.getFragmentManager(); - for(int i = 0; i < fm.getBackStackEntryCount(); ++i) { + for (int i = 0; i < fm.getBackStackEntryCount(); ++i) { fm.popBackStack(); } } @@ -1670,7 +1694,7 @@ public class Helper { editor.commit(); Intent changeAccount = new Intent(activity, MainActivity.class); changeAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); - if( notificationIntent) + if (notificationIntent) changeAccount.putExtra(INTENT_ACTION, NOTIFICATION_INTENT); activity.finish(); activity.startActivity(changeAccount); @@ -1704,7 +1728,7 @@ public class Helper { }); Map result = new LinkedHashMap<>(); - for (Iterator> it = list.iterator(); it.hasNext();) { + for (Iterator> it = list.iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry) it.next(); result.put(entry.getKey(), entry.getValue()); } @@ -1713,21 +1737,22 @@ public class Helper { /** * Load the profile picture at the place of hamburger icon + * * @param activity Activity The current activity - * @param account Account for the profile picture + * @param account Account for the profile picture */ - public static void loadPictureIcon(final Activity activity, Account account, final ImageView imageView){ - loadGiF(activity,account.getAvatar(), imageView); + public static void loadPictureIcon(final Activity activity, Account account, final ImageView imageView) { + loadGiF(activity, account.getAvatar(), imageView); } - public static SpannableString makeMentionsClick(final Context context, List mentions){ + public static SpannableString makeMentionsClick(final Context context, List mentions) { String cw_mention = ""; - if( mentions == null) + if (mentions == null) return new SpannableString(cw_mention); - for(Mention mention:mentions){ - cw_mention = String.format("@%s %s",mention.getUsername(),cw_mention); + for (Mention mention : mentions) { + cw_mention = String.format("@%s %s", mention.getUsername(), cw_mention); } SpannableString spannableString = new SpannableString(cw_mention); final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); @@ -1737,29 +1762,30 @@ public class Helper { if (spannableString.toString().contains(targetedAccount)) { //Accounts can be mentioned several times so we have to loop - for(int startPosition = -1 ; (startPosition = spannableString.toString().indexOf(targetedAccount, startPosition + 1)) != -1 ; startPosition++){ + for (int startPosition = -1; (startPosition = spannableString.toString().indexOf(targetedAccount, startPosition + 1)) != -1; startPosition++) { int endPosition = startPosition + targetedAccount.length(); spannableString.setSpan(new ClickableSpan() { - @Override - public void onClick(@NotNull View textView) { - Intent intent = new Intent(context, ShowAccountActivity.class); - Bundle b = new Bundle(); - b.putString("accountId", mention.getId()); - intent.putExtras(b); - context.startActivity(intent); - } - @Override - public void updateDrawState(@NotNull TextPaint ds) { - super.updateDrawState(ds); - ds.setUnderlineText(false); - if (theme == THEME_DARK) - ds.setColor(ContextCompat.getColor(context, R.color.dark_link_toot)); - else if (theme == THEME_BLACK) - ds.setColor(ContextCompat.getColor(context, R.color.black_link_toot)); - else if (theme == THEME_LIGHT) - ds.setColor(ContextCompat.getColor(context, R.color.mastodonC4)); - } - }, + @Override + public void onClick(@NotNull View textView) { + Intent intent = new Intent(context, ShowAccountActivity.class); + Bundle b = new Bundle(); + b.putString("accountId", mention.getId()); + intent.putExtras(b); + context.startActivity(intent); + } + + @Override + public void updateDrawState(@NotNull TextPaint ds) { + super.updateDrawState(ds); + ds.setUnderlineText(false); + if (theme == THEME_DARK) + ds.setColor(ContextCompat.getColor(context, R.color.dark_link_toot)); + else if (theme == THEME_BLACK) + ds.setColor(ContextCompat.getColor(context, R.color.black_link_toot)); + else if (theme == THEME_LIGHT) + ds.setColor(ContextCompat.getColor(context, R.color.mastodonC4)); + } + }, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); } @@ -1771,11 +1797,12 @@ public class Helper { /** * Update the header with the new selected account - * @param activity Activity - * @param account Account - new account in use + * + * @param activity Activity + * @param account Account - new account in use * @param headerLayout View - the menu header */ - public static void updateHeaderAccountInfo(Activity activity, final Account account, final View headerLayout){ + public static void updateHeaderAccountInfo(Activity activity, final Account account, final View headerLayout) { ImageView profilePicture = headerLayout.findViewById(R.id.profilePicture); @@ -1789,32 +1816,32 @@ public class Helper { ImageView icon = new ImageView(activity); - FloatingActionButton.LayoutParams layoutparmans = new FloatingActionButton.LayoutParams((int)Helper.convertDpToPixel(35,activity),(int)Helper.convertDpToPixel(35,activity)); - FloatingActionButton.LayoutParams layoutparmanImg = new FloatingActionButton.LayoutParams((int)Helper.convertDpToPixel(25,activity),(int)Helper.convertDpToPixel(25,activity)); + FloatingActionButton.LayoutParams layoutparmans = new FloatingActionButton.LayoutParams((int) Helper.convertDpToPixel(35, activity), (int) Helper.convertDpToPixel(35, activity)); + FloatingActionButton.LayoutParams layoutparmanImg = new FloatingActionButton.LayoutParams((int) Helper.convertDpToPixel(25, activity), (int) Helper.convertDpToPixel(25, activity)); MenuFloating actionButton = null; - if( theme == THEME_LIGHT) { + if (theme == THEME_LIGHT) { icon.setImageDrawable(ContextCompat.getDrawable(activity, R.drawable.ic_brush)); actionButton = new MenuFloating.Builder(activity) .setContentView(icon, layoutparmanImg) - .setBackgroundDrawable(activity.getResources().getDrawable( R.drawable.circular)) + .setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.circular)) .setLayoutParams(layoutparmans) .setTag("THEME") .intoView(more_option_container) .build(); - }else if( theme == THEME_DARK) { + } else if (theme == THEME_DARK) { icon.setImageDrawable(ContextCompat.getDrawable(activity, R.drawable.ic_brush_white)); actionButton = new MenuFloating.Builder(activity) .setContentView(icon, layoutparmanImg) - .setBackgroundDrawable(activity.getResources().getDrawable( R.drawable.circular_dark)) + .setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.circular_dark)) .setLayoutParams(layoutparmans) .setTag("THEME") .intoView(more_option_container) .build(); - }else if( theme == THEME_BLACK) { + } else if (theme == THEME_BLACK) { icon.setImageDrawable(ContextCompat.getDrawable(activity, R.drawable.ic_brush_white)); actionButton = new MenuFloating.Builder(activity) .setContentView(icon, layoutparmanImg) - .setBackgroundDrawable(activity.getResources().getDrawable( R.drawable.circular_black)) + .setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.circular_black)) .setLayoutParams(layoutparmans) .setTag("THEME") .intoView(more_option_container) @@ -1827,19 +1854,19 @@ public class Helper { ImageView itemIconLight = new ImageView(activity); itemIconLight.setImageDrawable(ContextCompat.getDrawable(activity, R.drawable.ic_brush)); SubActionButton buttonLight = itemBuilder - .setBackgroundDrawable(activity.getResources().getDrawable( R.drawable.circular)) + .setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.circular)) .setContentView(itemIconLight).build(); ImageView itemDark = new ImageView(activity); itemDark.setImageDrawable(ContextCompat.getDrawable(activity, R.drawable.ic_brush_white)); SubActionButton buttonDark = itemBuilder - .setBackgroundDrawable(activity.getResources().getDrawable( R.drawable.circular_dark)) + .setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.circular_dark)) .setContentView(itemDark).build(); ImageView itemBlack = new ImageView(activity); itemBlack.setImageDrawable(ContextCompat.getDrawable(activity, R.drawable.ic_brush_white)); SubActionButton buttonBlack = itemBuilder - .setBackgroundDrawable(activity.getResources().getDrawable( R.drawable.circular_black)) + .setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.circular_black)) .setContentView(itemBlack).build(); FloatingActionMenu actionMenu = new FloatingActionMenu.Builder(activity) @@ -1851,13 +1878,13 @@ public class Helper { .setEndAngle(90) .build(); - if( actionButton != null) { + if (actionButton != null) { actionButton.setFocusableInTouchMode(true); actionButton.setFocusable(true); actionButton.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { - if(actionMenu.isOpen()) + if (actionMenu.isOpen()) actionMenu.close(true); else actionMenu.open(true); @@ -1869,7 +1896,8 @@ public class Helper { public void onFocusChange(View v, boolean hasFocus) { try { actionMenu.close(true); - }catch (Exception ignored){} + } catch (Exception ignored) { + } } }); @@ -1908,17 +1936,17 @@ public class Helper { SQLiteDatabase db = Sqlite.getInstance(activity, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); final List accounts = new AccountDAO(activity, db).getAllAccount(); - if( activity.isFinishing()) + if (activity.isFinishing()) return; - if( accounts != null && accounts.size() > 1) { + if (accounts != null && accounts.size() > 1) { FloatingActionButton.LayoutParams layoutparmansAcc = new FloatingActionButton.LayoutParams((int) Helper.convertDpToPixel(37, activity), (int) Helper.convertDpToPixel(37, activity)); FloatingActionButton.LayoutParams layoutparmanImgAcc = new FloatingActionButton.LayoutParams((int) Helper.convertDpToPixel(35, activity), (int) Helper.convertDpToPixel(35, activity)); MenuFloating actionButtonAcc = null; SharedPreferences mSharedPreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String currrentUserId = mSharedPreferences.getString(Helper.PREF_KEY_ID, null); - for(final Account accountChoice: accounts) { - if( !accountChoice.getAvatar().startsWith("http")) + for (final Account accountChoice : accounts) { + if (!accountChoice.getAvatar().startsWith("http")) accountChoice.setAvatar("https://" + accountChoice.getInstance() + accountChoice.getAvatar()); if (currrentUserId != null && (!currrentUserId.equals(accountChoice.getId()) || !getLiveInstance(activity).equals(accountChoice.getInstance()))) { icon = new ImageView(activity); @@ -1926,17 +1954,18 @@ public class Helper { Glide.with(activity.getApplicationContext()) .asBitmap() .apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(270))) - .listener(new RequestListener(){ + .listener(new RequestListener() { @Override public boolean onResourceReady(Bitmap resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) { return false; } + @Override public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) { - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) finalIcon.setImageResource(R.drawable.missing); - else if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) + else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) finalIcon.setImageResource(R.drawable.missing_peertube); return false; } @@ -1949,12 +1978,12 @@ public class Helper { } }); MenuFloating.Builder actionButtonAccBuild = new MenuFloating.Builder(activity); - if( theme == THEME_LIGHT) { - actionButtonAccBuild.setBackgroundDrawable(activity.getResources().getDrawable( R.drawable.circular)); - }else if( theme == THEME_DARK) { - actionButtonAccBuild.setBackgroundDrawable(activity.getResources().getDrawable( R.drawable.circular_dark)); - }else if( theme == THEME_BLACK) { - actionButtonAccBuild.setBackgroundDrawable(activity.getResources().getDrawable( R.drawable.circular_black)); + if (theme == THEME_LIGHT) { + actionButtonAccBuild.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.circular)); + } else if (theme == THEME_DARK) { + actionButtonAccBuild.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.circular_dark)); + } else if (theme == THEME_BLACK) { + actionButtonAccBuild.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.circular_black)); } actionButtonAcc = actionButtonAccBuild @@ -1970,27 +1999,28 @@ public class Helper { FloatingActionMenu.Builder actionMenuAccBuilder = new FloatingActionMenu.Builder(activity); - for(final Account accountChoice: accounts) { + for (final Account accountChoice : accounts) { if (currrentUserId != null && !currrentUserId.equals(accountChoice.getId())) { SubActionButton.Builder itemBuilderAcc = new SubActionButton.Builder(activity); - if( !accountChoice.getAvatar().startsWith("http")) + if (!accountChoice.getAvatar().startsWith("http")) accountChoice.setAvatar("https://" + accountChoice.getInstance() + accountChoice.getAvatar()); ImageView itemIconAcc = new ImageView(activity); Glide.with(activity.getApplicationContext()) .asBitmap() .apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(270))) .load(accountChoice.getAvatar()) - .listener(new RequestListener(){ + .listener(new RequestListener() { @Override public boolean onResourceReady(Bitmap resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) { return false; } + @Override public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) { - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) itemIconAcc.setImageResource(R.drawable.missing); - else if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) + else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) itemIconAcc.setImageResource(R.drawable.missing_peertube); return false; } @@ -2002,8 +2032,8 @@ public class Helper { } }); - if( accounts.size() > 2 ) { - if(accountChoice.getSocial() != null && accountChoice.getSocial().equals("PEERTUBE")) + if (accounts.size() > 2) { + if (accountChoice.getSocial() != null && accountChoice.getSocial().equals("PEERTUBE")) itemBuilderAcc.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.circular_peertube)); else itemBuilderAcc.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.circular_mastodon)); @@ -2014,7 +2044,7 @@ public class Helper { subActionButtonAcc.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - if( !accountChoice.getToken().equals("null")) { + if (!accountChoice.getToken().equals("null")) { SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, accountChoice.getToken()); editor.putString(Helper.PREF_KEY_ID, accountChoice.getId()); @@ -2030,7 +2060,7 @@ public class Helper { changeAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); activity.finish(); activity.startActivity(changeAccount); - }else{ //The account was logged out + } else { //The account was logged out Intent intent = new Intent(activity, LoginActivity.class); intent.putExtra("instance", accountChoice.getInstance()); intent.putExtra("social", accountChoice.getSocial()); @@ -2043,18 +2073,18 @@ public class Helper { } } - if( actionButtonAcc != null) { + if (actionButtonAcc != null) { FloatingActionMenu actionMenuAcc = actionMenuAccBuilder.attachTo(actionButtonAcc) .setStartAngle(0) .setEndAngle(135) .build(); - if( accounts.size() > 2){ + if (accounts.size() > 2) { actionButtonAcc.setFocusableInTouchMode(true); actionButtonAcc.setFocusable(true); actionButtonAcc.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { - if(actionMenuAcc.isOpen()) + if (actionMenuAcc.isOpen()) actionMenuAcc.close(true); else actionMenuAcc.open(true); @@ -2066,17 +2096,18 @@ public class Helper { public void onFocusChange(View v, boolean hasFocus) { try { actionMenuAcc.close(true); - }catch (Exception ignored){} + } catch (Exception ignored) { + } } }); - }else{ + } else { actionButtonAcc.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - for(final Account accountChoice: accounts) { + for (final Account accountChoice : accounts) { if (!currrentUserId.equals(accountChoice.getId())) { - if( !accountChoice.getToken().equals("null")) { + if (!accountChoice.getToken().equals("null")) { SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, accountChoice.getToken()); editor.putString(Helper.PREF_KEY_ID, accountChoice.getId()); @@ -2088,7 +2119,7 @@ public class Helper { changeAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); activity.finish(); activity.startActivity(changeAccount); - }else{ //The account was logged out + } else { //The account was logged out Intent intent = new Intent(activity, LoginActivity.class); intent.putExtra("instance", accountChoice.getInstance()); intent.putExtra("social", accountChoice.getSocial()); @@ -2103,32 +2134,32 @@ public class Helper { } } - if( account == null ) { + if (account == null) { Helper.logout(activity); Intent myIntent = new Intent(activity, LoginActivity.class); - Toasty.error(activity.getApplicationContext(),activity.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); + Toasty.error(activity.getApplicationContext(), activity.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); activity.startActivity(myIntent); activity.finish(); //User is logged out to get a new token - }else { - Account.makeAccountNameEmoji(activity, ((BaseMainActivity)activity), account); - username.setText(String.format("@%s",account.getUsername() + "@" + account.getInstance())); + } else { + Account.makeAccountNameEmoji(activity, ((BaseMainActivity) activity), account); + username.setText(String.format("@%s", account.getUsername() + "@" + account.getInstance())); displayedName.setText(account.getdisplayNameSpan(), TextView.BufferType.SPANNABLE); loadGiF(activity, account.getAvatar(), profilePicture); String urlHeader = account.getHeader(); - if( urlHeader.startsWith("/") ){ + if (urlHeader.startsWith("/")) { urlHeader = Helper.getLiveInstanceWithProtocol(activity) + account.getHeader(); } ImageView owner_accounts = headerLayout.findViewById(R.id.owner_accounts); ImageView header_option_info = headerLayout.findViewById(R.id.header_option_info); ImageView header_option_menu = headerLayout.findViewById(R.id.header_option_menu); - if( theme == Helper.THEME_DARK || theme == Helper.THEME_BLACK){ - changeDrawableColor(activity, owner_accounts,R.color.dark_text); - changeDrawableColor(activity, header_option_info,R.color.dark_text); - changeDrawableColor(activity, header_option_menu,R.color.dark_text); - }else { - changeDrawableColor(activity, owner_accounts,R.color.light_black); - changeDrawableColor(activity, header_option_info,R.color.light_black); - changeDrawableColor(activity, header_option_menu,R.color.light_black); + if (theme == Helper.THEME_DARK || theme == Helper.THEME_BLACK) { + changeDrawableColor(activity, owner_accounts, R.color.dark_text); + changeDrawableColor(activity, header_option_info, R.color.dark_text); + changeDrawableColor(activity, header_option_menu, R.color.dark_text); + } else { + changeDrawableColor(activity, owner_accounts, R.color.light_black); + changeDrawableColor(activity, header_option_info, R.color.light_black); + changeDrawableColor(activity, header_option_menu, R.color.light_black); } if (!urlHeader.contains("missing.png")) { ImageView backgroundImage = headerLayout.findViewById(R.id.back_ground_image); @@ -2140,16 +2171,16 @@ public class Helper { public void onResourceReady(@NonNull Bitmap resource, Transition transition) { backgroundImage.setImageBitmap(resource); - if( theme == THEME_LIGHT){ + if (theme == THEME_LIGHT) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { backgroundImage.setImageAlpha(80); - }else { + } else { backgroundImage.setAlpha(80); } - }else{ + } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { backgroundImage.setImageAlpha(60); - }else { + } else { backgroundImage.setAlpha(60); } } @@ -2165,10 +2196,10 @@ public class Helper { if (account != null) { Intent intent = new Intent(activity, ShowAccountActivity.class); Bundle b = new Bundle(); - if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { b.putBoolean("peertubeaccount", true); b.putString("accountId", account.getAcct()); - }else + } else b.putString("accountId", account.getId()); intent.putExtras(b); activity.startActivity(intent); @@ -2180,22 +2211,23 @@ public class Helper { /** * Retrieves the cache size + * * @param directory File * @return long value in Mo */ public static long cacheSize(File directory) { long length = 0; - if( directory == null || directory.length() == 0 ) + if (directory == null || directory.length() == 0) return -1; for (File file : directory.listFiles()) { - if (file.isFile()){ + if (file.isFile()) { try { length += file.length(); } catch (NullPointerException e) { return -1; } - }else { - if( !file.getName().equals("databases") && !file.getName().equals("shared_prefs")) { + } else { + if (!file.getName().equals("databases") && !file.getName().equals("shared_prefs")) { length += cacheSize(file); } } @@ -2215,14 +2247,12 @@ public class Helper { } } return dir.delete(); - } else{ + } else { return dir != null && dir.isFile() && dir.delete(); } } - - /*** * Check if the account bio contents urls & tags and fills the content with ClickableSpan * Click on url => webview or external app @@ -2240,8 +2270,8 @@ public class Helper { Pattern aLink = Pattern.compile("(<\\s?a\\s?href=\"https?:\\/\\/([\\da-z\\.-]+\\.[a-z\\.]{2,10})\\/(@[\\/\\w._-]*)\"\\s?[^.]*<\\s?\\/\\s?a\\s?>)"); Matcher matcherALink = aLink.matcher(spannableStringT.toString()); ArrayList accountsMentionUnknown = new ArrayList<>(); - while (matcherALink.find()){ - String acct = matcherALink.group(3).replace("@",""); + while (matcherALink.find()) { + String acct = matcherALink.group(3).replace("@", ""); String instance = matcherALink.group(2); Account account = new Account(); account.setAcct(acct); @@ -2255,7 +2285,7 @@ public class Helper { spannableString = new SpannableString(Html.fromHtml(spannableStringT.toString())); URLSpan[] urls = spannableString.getSpans(0, spannableString.length(), URLSpan.class); - for(URLSpan span : urls) + for (URLSpan span : urls) spannableString.removeSpan(span); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); @@ -2264,18 +2294,19 @@ public class Helper { matcher = Patterns.WEB_URL.matcher(spannableString); else matcher = urlPattern.matcher(spannableString); - while (matcher.find()){ + while (matcher.find()) { int matchStart = matcher.start(1); int matchEnd = matcher.end(); final String url = spannableString.toString().substring(matchStart, matchEnd); - if( url.startsWith("http")) - if( matchEnd <= spannableString.toString().length() && matchEnd >= matchStart) + if (url.startsWith("http")) + if (matchEnd <= spannableString.toString().length() && matchEnd >= matchStart) spannableString.setSpan(new ClickableSpan() { @Override public void onClick(@NotNull View textView) { Helper.openBrowser(context, url); } + @Override public void updateDrawState(@NotNull TextPaint ds) { super.updateDrawState(ds); @@ -2290,11 +2321,11 @@ public class Helper { }, matchStart, matchEnd, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); } matcher = hashtagPattern.matcher(spannableString); - while (matcher.find()){ + while (matcher.find()) { int matchStart = matcher.start(1); int matchEnd = matcher.end(); final String tag = spannableString.toString().substring(matchStart, matchEnd); - if( matchEnd <= spannableString.toString().length() && matchEnd >= matchStart) + if (matchEnd <= spannableString.toString().length() && matchEnd >= matchStart) spannableString.setSpan(new ClickableSpan() { @Override public void onClick(View textView) { @@ -2304,6 +2335,7 @@ public class Helper { intent.putExtras(b); context.startActivity(intent); } + @Override public void updateDrawState(@NotNull TextPaint ds) { super.updateDrawState(ds); @@ -2317,45 +2349,46 @@ public class Helper { } }, matchStart, matchEnd, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); } - if( accountsMentionUnknown.size() > 0 ) { - for(Account account: accountsMentionUnknown){ + if (accountsMentionUnknown.size() > 0) { + for (Account account : accountsMentionUnknown) { String targetedAccount = "@" + account.getAcct(); if (spannableString.toString().toLowerCase().contains(targetedAccount.toLowerCase())) { //Accounts can be mentioned several times so we have to loop - for(int startPosition = -1 ; (startPosition = spannableString.toString().toLowerCase().indexOf(targetedAccount.toLowerCase(), startPosition + 1)) != -1 ; startPosition++){ + for (int startPosition = -1; (startPosition = spannableString.toString().toLowerCase().indexOf(targetedAccount.toLowerCase(), startPosition + 1)) != -1; startPosition++) { int endPosition = startPosition + targetedAccount.length(); - if( endPosition <= spannableString.toString().length() && endPosition >= startPosition) + if (endPosition <= spannableString.toString().length() && endPosition >= startPosition) spannableString.setSpan(new ClickableSpan() { - @Override - public void onClick(@NotNull View textView) { - CrossActions.doCrossProfile(context,account); - } - @Override - public void updateDrawState(@NotNull TextPaint ds) { - super.updateDrawState(ds); - ds.setUnderlineText(false); - if (theme == THEME_DARK) - ds.setColor(ContextCompat.getColor(context, R.color.dark_link_toot)); - else if (theme == THEME_BLACK) - ds.setColor(ContextCompat.getColor(context, R.color.black_link_toot)); - else if (theme == THEME_LIGHT) - ds.setColor(ContextCompat.getColor(context, R.color.mastodonC4)); - } - }, - startPosition, endPosition, - Spanned.SPAN_INCLUSIVE_EXCLUSIVE); + @Override + public void onClick(@NotNull View textView) { + CrossActions.doCrossProfile(context, account); + } + + @Override + public void updateDrawState(@NotNull TextPaint ds) { + super.updateDrawState(ds); + ds.setUnderlineText(false); + if (theme == THEME_DARK) + ds.setColor(ContextCompat.getColor(context, R.color.dark_link_toot)); + else if (theme == THEME_BLACK) + ds.setColor(ContextCompat.getColor(context, R.color.black_link_toot)); + else if (theme == THEME_LIGHT) + ds.setColor(ContextCompat.getColor(context, R.color.mastodonC4)); + } + }, + startPosition, endPosition, + Spanned.SPAN_INCLUSIVE_EXCLUSIVE); } } } } matcher = android.util.Patterns.EMAIL_ADDRESS.matcher(spannableString); - while (matcher.find()){ + while (matcher.find()) { int matchStart = matcher.start(0); int matchEnd = matcher.end(); final String email = spannableString.toString().substring(matchStart, matchEnd); - if( matchEnd <= spannableString.toString().length() && matchEnd >= matchStart) { + if (matchEnd <= spannableString.toString().length() && matchEnd >= matchStart) { urls = spannableString.getSpans(matchStart, matchEnd, URLSpan.class); - for(URLSpan span : urls) + for (URLSpan span : urls) spannableString.removeSpan(span); spannableString.setSpan(new ClickableSpan() { @Override @@ -2365,10 +2398,11 @@ public class Helper { emailIntent.setType("plain/text"); emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{email}); context.startActivity(Intent.createChooser(emailIntent, context.getString(R.string.send_email))); - }catch (Exception e){ + } catch (Exception e) { Toasty.error(context, context.getString(R.string.toast_no_apps), Toast.LENGTH_LONG).show(); } } + @Override public void updateDrawState(@NotNull TextPaint ds) { super.updateDrawState(ds); @@ -2385,13 +2419,13 @@ public class Helper { } matcher = Helper.xmppPattern.matcher(spannableString); - while (matcher.find()){ + while (matcher.find()) { int matchStart = matcher.start(0); int matchEnd = matcher.end(); final String url = spannableString.toString().substring(matchStart, matchEnd); - if( matchEnd <= spannableString.toString().length() && matchEnd >= matchStart) { + if (matchEnd <= spannableString.toString().length() && matchEnd >= matchStart) { urls = spannableString.getSpans(matchStart, matchEnd, URLSpan.class); - for(URLSpan span : urls) + for (URLSpan span : urls) spannableString.removeSpan(span); spannableString.setSpan(new ClickableSpan() { @Override @@ -2399,10 +2433,11 @@ public class Helper { try { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); context.startActivity(intent); - }catch (Exception e){ + } catch (Exception e) { Toasty.error(context, context.getString(R.string.toast_no_apps), Toast.LENGTH_LONG).show(); } } + @Override public void updateDrawState(@NotNull TextPaint ds) { super.updateDrawState(ds); @@ -2422,7 +2457,7 @@ public class Helper { } - public static WebView initializeWebview(Activity activity, int webviewId){ + public static WebView initializeWebview(Activity activity, int webviewId) { WebView webView = activity.findViewById(webviewId); final SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); @@ -2480,16 +2515,18 @@ public class Helper { } return hexString.toString(); - } catch (NoSuchAlgorithmException ignored) {} + } catch (NoSuchAlgorithmException ignored) { + } return ""; } /** * change color of a drawable - * @param drawable int the drawable + * + * @param drawable int the drawable * @param hexaColor example 0xffff00 */ - public static Drawable changeDrawableColor(Context context, int drawable, int hexaColor){ + public static Drawable changeDrawableColor(Context context, int drawable, int hexaColor) { Drawable mDrawable = ContextCompat.getDrawable(context, drawable); int color = Color.parseColor(context.getString(hexaColor)); assert mDrawable != null; @@ -2497,40 +2534,46 @@ public class Helper { DrawableCompat.setTint(mDrawable, ContextCompat.getColor(context, hexaColor)); return mDrawable; } + /** * change color of a drawable + * * @param imageView int the ImageView * @param hexaColor example 0xffff00 */ - public static void changeDrawableColor(Context context, ImageView imageView, int hexaColor){ - if( imageView == null) + public static void changeDrawableColor(Context context, ImageView imageView, int hexaColor) { + if (imageView == null) return; imageView.setColorFilter(context.getResources().getColor(hexaColor)); } /** * change color of a drawable + * * @param imageButton int the ImageButton - * @param hexaColor example 0xffff00 + * @param hexaColor example 0xffff00 */ - public static void changeDrawableColor(Context context, ImageButton imageButton, int hexaColor){ - if( imageButton == null) + public static void changeDrawableColor(Context context, ImageButton imageButton, int hexaColor) { + if (imageButton == null) return; imageButton.setColorFilter(context.getResources().getColor(hexaColor)); } /** * change color of a drawable - * @param button int the button + * + * @param button int the button * @param hexaColor example 0xffff00 */ - public static void changeButtonTextColor(Context context, Button button, int hexaColor){ - if( button == null) + public static void changeButtonTextColor(Context context, Button button, int hexaColor) { + if (button == null) return; button.setTextColor(context.getResources().getColor(hexaColor)); } + /** * Returns the current locale of the device + * * @param context Context * @return String locale */ @@ -2551,20 +2594,21 @@ public class Helper { /** * Compare date with these in shared pref. - * @param context Context - * @param newDate String + * + * @param context Context + * @param newDate String * @param shouldBeGreater boolean if date passed as a parameter should be greater * @return boolean */ - public static boolean compareDate(Context context, String newDate, boolean shouldBeGreater){ + public static boolean compareDate(Context context, String newDate, boolean shouldBeGreater) { String dateRef; final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); if (shouldBeGreater) { dateRef = sharedpreferences.getString(Helper.SET_TIME_FROM, "07:00"); - }else { + } else { dateRef = sharedpreferences.getString(Helper.SET_TIME_TO, "22:00"); } - try{ + try { Locale userLocale; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { userLocale = context.getResources().getConfiguration().getLocales().get(0); @@ -2576,7 +2620,7 @@ public class Helper { Date dateRefD = formatter.parse(dateRef); if (shouldBeGreater) { return (newDateD.after(dateRefD)); - }else { + } else { return (newDateD.before(dateRefD)); } } catch (java.text.ParseException e) { @@ -2587,16 +2631,17 @@ public class Helper { /** * Tells if the the service can notify depending of the current hour and minutes + * * @param context Context * @return boolean */ - public static boolean canNotify(Context context){ + public static boolean canNotify(Context context) { final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); boolean notify = sharedpreferences.getBoolean(Helper.SET_NOTIFY, true); - if( !notify) + if (!notify) return false; boolean enable_time_slot = sharedpreferences.getBoolean(Helper.SET_ENABLE_TIME_SLOT, true); - if( ! enable_time_slot) + if (!enable_time_slot) return true; String dateIni = sharedpreferences.getString(Helper.SET_TIME_FROM, "07:00"); String dateEnd = sharedpreferences.getString(Helper.SET_TIME_TO, "22:00"); @@ -2604,10 +2649,10 @@ public class Helper { Calendar now = Calendar.getInstance(); int hour = now.get(Calendar.HOUR_OF_DAY); int minute = now.get(Calendar.MINUTE); - String hourS = String.valueOf(hour).length() == 1?"0"+String.valueOf(hour):String.valueOf(hour); - String minuteS = String.valueOf(minute).length() == 1?"0"+String.valueOf(minute):String.valueOf(minute); + String hourS = String.valueOf(hour).length() == 1 ? "0" + String.valueOf(hour) : String.valueOf(hour); + String minuteS = String.valueOf(minute).length() == 1 ? "0" + String.valueOf(minute) : String.valueOf(minute); String currentDate = hourS + ":" + minuteS; - try{ + try { Locale userLocale; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { userLocale = context.getResources().getConfiguration().getLocales().get(0); @@ -2619,9 +2664,9 @@ public class Helper { Date dateEndD = formatter.parse(dateEnd); Date currentDateD = formatter.parse(currentDate); boolean canNotify = false; - if( currentDateD.before(dateEndD) && currentDateD.after(dateIniD) && notification == Helper.ACTION_ACTIVE) + if (currentDateD.before(dateEndD) && currentDateD.after(dateIniD) && notification == Helper.ACTION_ACTIVE) canNotify = true; - else if ( currentDateD.after(dateEndD) && currentDateD.before(dateIniD) && notification == Helper.ACTION_SILENT ) + else if (currentDateD.after(dateEndD) && currentDateD.before(dateIniD) && notification == Helper.ACTION_SILENT) canNotify = true; return canNotify; } catch (java.text.ParseException e) { @@ -2632,28 +2677,30 @@ public class Helper { /** * Unserialized a + * * @param serializedListTimeline String serialized List * @return List */ - public static app.fedilab.android.client.Entities.List restoreListtimelineFromString(String serializedListTimeline){ + public static app.fedilab.android.client.Entities.List restoreListtimelineFromString(String serializedListTimeline) { Gson gson = new Gson(); try { return gson.fromJson(serializedListTimeline, app.fedilab.android.client.Entities.List.class); - }catch (Exception e){ + } catch (Exception e) { return null; } } /** * Serialized a List class + * * @param listTimeline List to serialize * @return String serialized List */ - public static String listTimelineToStringStorage(app.fedilab.android.client.Entities.List listTimeline){ + public static String listTimelineToStringStorage(app.fedilab.android.client.Entities.List listTimeline) { Gson gson = new Gson(); try { return gson.toJson(listTimeline); - }catch (Exception e){ + } catch (Exception e) { return null; } } @@ -2661,28 +2708,30 @@ public class Helper { /** * Unserialized a TagTimeline + * * @param serializedTagTimeline String serialized TagTimeline * @return TagTimeline */ - public static TagTimeline restoreTagTimelineFromString(String serializedTagTimeline){ + public static TagTimeline restoreTagTimelineFromString(String serializedTagTimeline) { Gson gson = new Gson(); try { return gson.fromJson(serializedTagTimeline, TagTimeline.class); - }catch (Exception e){ + } catch (Exception e) { return null; } } /** * Serialized a TagTimeline class + * * @param tagTimeline TagTimeline to serialize * @return String serialized TagTimeline */ - public static String tagTimelineToStringStorage(TagTimeline tagTimeline){ + public static String tagTimelineToStringStorage(TagTimeline tagTimeline) { Gson gson = new Gson(); try { return gson.toJson(tagTimeline); - }catch (Exception e){ + } catch (Exception e) { return null; } } @@ -2690,28 +2739,30 @@ public class Helper { /** * Unserialized a RemoteInstance + * * @param serializedRemoteInstance String serialized RemoteInstance * @return RemoteInstance */ - public static RemoteInstance restoreRemoteInstanceFromString(String serializedRemoteInstance){ + public static RemoteInstance restoreRemoteInstanceFromString(String serializedRemoteInstance) { Gson gson = new Gson(); try { return gson.fromJson(serializedRemoteInstance, RemoteInstance.class); - }catch (Exception e){ + } catch (Exception e) { return null; } } /** * Serialized a RemoteInstance class + * * @param remoteInstance RemoteInstance to serialize * @return String serialized RemoteInstance */ - public static String remoteInstanceToStringStorage(RemoteInstance remoteInstance){ + public static String remoteInstanceToStringStorage(RemoteInstance remoteInstance) { Gson gson = new Gson(); try { return gson.toJson(remoteInstance); - }catch (Exception e){ + } catch (Exception e) { return null; } } @@ -2719,140 +2770,150 @@ public class Helper { /** * Unserialized a Locale + * * @param serializedLocale String serialized locale * @return Locale */ - public static Locale restoreLocaleFromString(String serializedLocale){ + public static Locale restoreLocaleFromString(String serializedLocale) { Gson gson = new Gson(); try { return gson.fromJson(serializedLocale, Locale.class); - }catch (Exception e){ + } catch (Exception e) { return null; } } /** * Serialized a Locale class + * * @param locale Locale to serialize * @return String serialized Locale */ - public static String localeToStringStorage(Locale locale){ + public static String localeToStringStorage(Locale locale) { Gson gson = new Gson(); try { return gson.toJson(locale); - }catch (Exception e){ + } catch (Exception e) { return null; } } /** * Serialized a Status class + * * @param status Status to serialize * @return String serialized Status */ - public static String statusToStringStorage(Status status){ + public static String statusToStringStorage(Status status) { Gson gson = new Gson(); try { return gson.toJson(status); - }catch (Exception e){ + } catch (Exception e) { return null; } } /** * Unserialized a Card + * * @param serializedCard String serialized card * @return Card */ - public static Card restoreCardFromString(String serializedCard){ + public static Card restoreCardFromString(String serializedCard) { Gson gson = new Gson(); try { return gson.fromJson(serializedCard, Card.class); - }catch (Exception e){ + } catch (Exception e) { return null; } } /** * Serialized a Card class + * * @param card Card to serialize * @return String serialized Status */ - public static String cardToStringStorage(Card card){ + public static String cardToStringStorage(Card card) { Gson gson = new Gson(); try { return gson.toJson(card); - }catch (Exception e){ + } catch (Exception e) { return null; } } /** * Unserialized a Status + * * @param serializedStatus String serialized status * @return Status */ - public static Status restoreStatusFromString(String serializedStatus){ + public static Status restoreStatusFromString(String serializedStatus) { Gson gson = new Gson(); try { return gson.fromJson(serializedStatus, Status.class); - }catch (Exception e){ + } catch (Exception e) { return null; } } /** * Serialized a List + * * @param list List to serialize * @return String serialized List */ - public static String arrayToStringStorage(List list){ + public static String arrayToStringStorage(List list) { Gson gson = new Gson(); try { return gson.toJson(list); - }catch (Exception e){ + } catch (Exception e) { return null; } } /** * Unserialized a List + * * @param serializedArray String serialized array * @return List list */ - public static List restoreArrayFromString(String serializedArray){ + public static List restoreArrayFromString(String serializedArray) { Gson gson = new Gson(); try { return gson.fromJson(serializedArray, List.class); - }catch (Exception e){ + } catch (Exception e) { return null; } } /** * Serialized an Application class + * * @param application Application to serialize * @return String serialized Application */ - public static String applicationToStringStorage(Application application){ + public static String applicationToStringStorage(Application application) { Gson gson = new Gson(); try { return gson.toJson(application); - }catch (Exception e){ + } catch (Exception e) { return null; } } /** * Unserialized an Application + * * @param serializedApplication String serialized application * @return Application */ - public static Application restoreApplicationFromString(String serializedApplication){ + public static Application restoreApplicationFromString(String serializedApplication) { Gson gson = new Gson(); try { return gson.fromJson(serializedApplication, Application.class); - }catch (Exception e){ + } catch (Exception e) { return null; } } @@ -2860,14 +2921,15 @@ public class Helper { /** * Serialized a Account class + * * @param account Account to serialize * @return String serialized Account */ - public static String accountToStringStorage(Account account){ + public static String accountToStringStorage(Account account) { Gson gson = new Gson(); try { return gson.toJson(account); - }catch (Exception e){ + } catch (Exception e) { e.printStackTrace(); return null; } @@ -2876,14 +2938,15 @@ public class Helper { /** * Unserialized an Account + * * @param serializedAccount String serialized account * @return Account */ - public static Account restoreAccountFromString(String serializedAccount){ + public static Account restoreAccountFromString(String serializedAccount) { Gson gson = new Gson(); try { return gson.fromJson(serializedAccount, Account.class); - }catch (Exception e){ + } catch (Exception e) { return null; } } @@ -2891,28 +2954,31 @@ public class Helper { /** * Serialized a List of Emojis class + * * @param emojis Emojis List to serialize * @return String serialized List of Emojis */ - public static String emojisToStringStorage(List emojis){ + public static String emojisToStringStorage(List emojis) { Gson gson = new Gson(); try { return gson.toJson(emojis); - }catch (Exception e){ + } catch (Exception e) { return null; } } /** * Unserialized a list of Emojis + * * @param serializedEmojis String serialized emojis * @return List */ - public static List restoreEmojisFromString(String serializedEmojis){ - Type listType = new TypeToken>(){}.getType(); + public static List restoreEmojisFromString(String serializedEmojis) { + Type listType = new TypeToken>() { + }.getType(); try { return new Gson().fromJson(serializedEmojis, listType); - }catch (Exception e){ + } catch (Exception e) { return null; } } @@ -2920,59 +2986,64 @@ public class Helper { /** * Serialized a List of a Attachment class + * * @param attachments Attachment List to serialize * @return String serialized List of Attachment */ - public static String attachmentToStringStorage(List attachments){ + public static String attachmentToStringStorage(List attachments) { Gson gson = new Gson(); try { return gson.toJson(attachments); - }catch (Exception e){ + } catch (Exception e) { return null; } } /** * Unserialized a list of Attachment + * * @param serializedAttachment String serialized attachment * @return List */ - public static ArrayList restoreAttachmentFromString(String serializedAttachment){ - Type listType = new TypeToken>(){}.getType(); + public static ArrayList restoreAttachmentFromString(String serializedAttachment) { + Type listType = new TypeToken>() { + }.getType(); try { return new Gson().fromJson(serializedAttachment, listType); - }catch (Exception e){ + } catch (Exception e) { e.printStackTrace(); return null; } } - /** * Serialized a List of a Mention class + * * @param mentions Mention List to serialize * @return String serialized List of Mention */ - public static String mentionToStringStorage(List mentions){ + public static String mentionToStringStorage(List mentions) { Gson gson = new Gson(); try { return gson.toJson(mentions); - }catch (Exception e){ + } catch (Exception e) { return null; } } /** * Unserialized a list of Mention + * * @param serializedMention String serialized mention * @return String serialized List of Mention */ - public static List restoreMentionFromString(String serializedMention){ - Type listType = new TypeToken>(){}.getType(); + public static List restoreMentionFromString(String serializedMention) { + Type listType = new TypeToken>() { + }.getType(); try { return new Gson().fromJson(serializedMention, listType); - }catch (Exception e){ + } catch (Exception e) { return null; } } @@ -2980,50 +3051,54 @@ public class Helper { /** * Serialized a List of a Tag class + * * @param tags Tag List to serialize * @return String serialized List of Tag */ - public static String tagToStringStorage(List tags){ + public static String tagToStringStorage(List tags) { Gson gson = new Gson(); try { return gson.toJson(tags); - }catch (Exception e){ + } catch (Exception e) { return null; } } /** * Unserialized a list of Tag + * * @param serializedTag String serialized tag * @return String serialized List of Tag */ - public static List restoreTagFromString(String serializedTag){ - Type listType = new TypeToken>(){}.getType(); + public static List restoreTagFromString(String serializedTag) { + Type listType = new TypeToken>() { + }.getType(); try { return new Gson().fromJson(serializedTag, listType); - }catch (Exception e){ + } catch (Exception e) { return null; } } - /** * Check if a job id is in array of ids + * * @param jobIds int[] - * @param id int id to check + * @param id int id to check * @return boolean */ - public static boolean isJobPresent(int[] jobIds, int id){ - for(int x:jobIds) { - if (x == id) {return true;} + public static boolean isJobPresent(int[] jobIds, int id) { + for (int x : jobIds) { + if (x == id) { + return true; + } } return false; } - - public static void unCheckAllMenuItems(NavigationView navigationView){ + public static void unCheckAllMenuItems(NavigationView navigationView) { navigationView.setCheckedItem(R.id.menu_none); unCheckAllMenuItemsRec(navigationView.getMenu()); } @@ -3032,7 +3107,7 @@ public class Helper { int size = menu.size(); for (int i = 0; i < size; i++) { final MenuItem item = menu.getItem(i); - if(item.hasSubMenu()) { + if (item.hasSubMenu()) { unCheckAllMenuItemsRec(item.getSubMenu()); } else { item.setChecked(false); @@ -3043,9 +3118,10 @@ public class Helper { /** * Changes the menu layout + * * @param activity Activity must be an instance of MainActivity */ - public static void switchLayout(Activity activity){ + public static void switchLayout(Activity activity) { //Check if the class calling the method is an instance of MainActivity final SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); final NavigationView navigationView = activity.findViewById(R.id.nav_view); @@ -3053,19 +3129,19 @@ public class Helper { String userID = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, null); SQLiteDatabase db = Sqlite.getInstance(activity, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - Account account = new AccountDAO(activity,db).getUniqAccount(userID, instance); - if( account != null) { + Account account = new AccountDAO(activity, db).getUniqAccount(userID, instance); + if (account != null) { if (account.isLocked()) { - if( navigationView.getMenu().findItem(R.id.nav_follow_request) != null) + if (navigationView.getMenu().findItem(R.id.nav_follow_request) != null) navigationView.getMenu().findItem(R.id.nav_follow_request).setVisible(true); } else { - if( navigationView.getMenu().findItem(R.id.nav_follow_request) != null) + if (navigationView.getMenu().findItem(R.id.nav_follow_request) != null) navigationView.getMenu().findItem(R.id.nav_follow_request).setVisible(false); } - if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.MASTODON && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA){ + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.MASTODON && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { MenuItem adminItem = navigationView.getMenu().findItem(R.id.nav_administration); - if( adminItem != null){ + if (adminItem != null) { adminItem.setVisible(false); } } @@ -3074,23 +3150,23 @@ public class Helper { } - /** * Get a bitmap from a view + * * @param view The view to convert * @return Bitmap */ public static Bitmap convertTootIntoBitmap(Context context, String name, View view) { - if( view.getWidth() == 0 || view.getHeight() == 0){ - Toasty.error(context, context.getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + if (view.getWidth() == 0 || view.getHeight() == 0) { + Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); return null; } - Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth()+(int)Helper.convertDpToPixel(10, context), view.getHeight()+(int)Helper.convertDpToPixel(30, context), Bitmap.Config.ARGB_8888); + Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth() + (int) Helper.convertDpToPixel(10, context), view.getHeight() + (int) Helper.convertDpToPixel(30, context), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(returnedBitmap); - canvas.drawBitmap(returnedBitmap, view.getWidth()+(int)Helper.convertDpToPixel(10, context), 0, null); - Drawable bgDrawable =view.getBackground(); - if (bgDrawable!=null) + canvas.drawBitmap(returnedBitmap, view.getWidth() + (int) Helper.convertDpToPixel(10, context), 0, null); + Drawable bgDrawable = view.getBackground(); + if (bgDrawable != null) bgDrawable.draw(canvas); else { final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); @@ -3098,10 +3174,9 @@ public class Helper { if (theme == Helper.THEME_DARK) { canvas.drawColor(ContextCompat.getColor(context, R.color.mastodonC1)); - }else if( theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { canvas.drawColor(ContextCompat.getColor(context, R.color.black)); - } - else { + } else { canvas.drawColor(Color.WHITE); } } @@ -3111,9 +3186,9 @@ public class Helper { int mastodonC4 = ContextCompat.getColor(context, R.color.mastodonC4); paint.setColor(mastodonC4); paint.setStrokeWidth(12); - paint.setTextSize((int)Helper.convertDpToPixel(14, context)); + paint.setTextSize((int) Helper.convertDpToPixel(14, context)); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER)); - canvas.drawText(name +" - #Fedilab", 0, view.getHeight() +(int)Helper.convertDpToPixel(15, context), paint); + canvas.drawText(name + " - #Fedilab", 0, view.getHeight() + (int) Helper.convertDpToPixel(15, context), paint); return returnedBitmap; } @@ -3126,15 +3201,16 @@ public class Helper { Locale locale = null; try { locale = Locale.getDefault(); - }catch (Exception ignored){} - if(locale != null) - return String.format(locale, "%.1f %c", - count / Math.pow(1000, exp), - "kMGTPE".charAt(exp-1)); - else - return String.format( "%.1f %c", + } catch (Exception ignored) { + } + if (locale != null) + return String.format(locale, "%.1f %c", count / Math.pow(1000, exp), - "kMGTPE".charAt(exp-1)); + "kMGTPE".charAt(exp - 1)); + else + return String.format("%.1f %c", + count / Math.pow(1000, exp), + "kMGTPE".charAt(exp - 1)); } @@ -3161,32 +3237,32 @@ public class Helper { public static String secondsToString(int pTime) { - int hour = pTime/3600; - int min = (pTime -(hour*3600))/60; - int sec = pTime -(hour*3600)-(min*60); - String strHour="0", strMin="0", strSec="0"; + int hour = pTime / 3600; + int min = (pTime - (hour * 3600)) / 60; + int sec = pTime - (hour * 3600) - (min * 60); + String strHour = "0", strMin = "0", strSec = "0"; - if( hour > 0 ) + if (hour > 0) strHour = String.format(Locale.getDefault(), "%02d", hour); - if( min > 0 ) + if (min > 0) strMin = String.format(Locale.getDefault(), "%02d", min); strSec = String.format(Locale.getDefault(), "%02d", sec); - if( hour > 0 ) - return String.format(Locale.getDefault(),"%s:%s:%s",strHour, strMin,strSec); + if (hour > 0) + return String.format(Locale.getDefault(), "%s:%s:%s", strHour, strMin, strSec); else - return String.format(Locale.getDefault(), "%s:%s",strMin,strSec); + return String.format(Locale.getDefault(), "%s:%s", strMin, strSec); } - public static void loadGiF(final Context context, String url, final ImageView imageView){ + public static void loadGiF(final Context context, String url, final ImageView imageView) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); boolean disableGif = sharedpreferences.getBoolean(SET_DISABLE_GIF, false); - if( url != null && url.startsWith("/")){ + if (url != null && url.startsWith("/")) { url = Helper.getLiveInstanceWithProtocol(context) + url; } - if( !(context instanceof MainApplication) && ((Activity)context).isFinishing()){ + if (!(context instanceof MainApplication) && ((Activity) context).isFinishing()) { return; } - if( disableGif){ + if (disableGif) { try { Glide.with(imageView.getContext()) .asBitmap() @@ -3194,7 +3270,7 @@ public class Helper { .thumbnail(0.1f) .apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(10))) .into(imageView); - }catch (Exception e){ + } catch (Exception e) { try { if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || BaseMainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { Glide.with(imageView.getContext()) @@ -3215,16 +3291,17 @@ public class Helper { .apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(10))) .into(imageView); } - }catch (Exception ignored){} + } catch (Exception ignored) { + } } - }else{ + } else { try { Glide.with(imageView.getContext()) .load(url) .thumbnail(0.1f) .apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(10))) .into(imageView); - }catch (Exception e){ + } catch (Exception e) { try { if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || BaseMainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { Glide.with(imageView.getContext()) @@ -3245,7 +3322,8 @@ public class Helper { .apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(10))) .into(imageView); } - }catch (Exception ignored){} + } catch (Exception ignored) { + } } } @@ -3254,13 +3332,14 @@ public class Helper { /** * Manage URLs to open (built-in or external app) + * * @param context Context - * @param url String url to open + * @param url String url to open */ - public static void openBrowser(Context context, String url){ + public static void openBrowser(Context context, String url) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); boolean embedded_browser = sharedpreferences.getBoolean(Helper.SET_EMBEDDED_BROWSER, true); - if( embedded_browser) { + if (embedded_browser) { Intent intent = new Intent(context, WebviewActivity.class); Bundle b = new Bundle(); String finalUrl = url; @@ -3269,22 +3348,24 @@ public class Helper { b.putString("url", finalUrl); intent.putExtras(b); context.startActivity(intent); - }else { + } else { boolean custom_tabs = sharedpreferences.getBoolean(Helper.SET_CUSTOM_TABS, true); - if( custom_tabs){ + if (custom_tabs) { CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(); CustomTabsIntent customTabsIntent = builder.build(); builder.setToolbarColor(ContextCompat.getColor(context, R.color.mastodonC1)); try { customTabsIntent.launchUrl(context, Uri.parse(url)); - }catch (Exception ignored){Toasty.error(context, context.getString(R.string.toast_error),Toast.LENGTH_LONG).show();} - }else{ + } catch (Exception ignored) { + Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); + } + } else { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); try { context.startActivity(intent); - }catch (Exception e){ - Toasty.error(context, context.getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + } catch (Exception e) { + Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); } } @@ -3292,40 +3373,44 @@ public class Helper { } - public static void installProvider(){ + public static void installProvider() { boolean patch_provider = true; try { Context ctx = MainApplication.getApp(); SharedPreferences sharedpreferences = ctx.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); patch_provider = sharedpreferences.getBoolean(Helper.SET_SECURITY_PROVIDER, true); - }catch (Exception ignored){} - if( patch_provider) + } catch (Exception ignored) { + } + if (patch_provider) try { - Security.insertProviderAt(Conscrypt.newProvider(),1); - }catch (Exception ignored){} + Security.insertProviderAt(Conscrypt.newProvider(), 1); + } catch (Exception ignored) { + } } - public enum MediaType{ + public enum MediaType { MEDIA, PROFILE } - - public static ByteArrayInputStream compressImage(Context context, android.net.Uri uriFile, MediaType mediaType){ + + public static ByteArrayInputStream compressImage(Context context, android.net.Uri uriFile, MediaType mediaType) { ContentResolver cr = context.getContentResolver(); String mime = cr.getType(uriFile); ByteArrayInputStream bs = null; - if(mime != null && mime.toLowerCase().contains("image")){ + if (mime != null && mime.toLowerCase().contains("image")) { Bitmap takenImage; try { takenImage = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uriFile); } catch (IOException e) { try { Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); - }catch (Exception ignored){}; + } catch (Exception ignored) { + } + ; return null; } ExifInterface exif = null; @@ -3336,105 +3421,111 @@ public class Helper { e.printStackTrace(); } Matrix matrix = null; - if( takenImage != null ){ + if (takenImage != null) { int size = takenImage.getByteCount(); - if( exif != null) { + if (exif != null) { int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); int rotationDegree = 0; - if (rotation == ExifInterface.ORIENTATION_ROTATE_90) { rotationDegree = 90; } - else if (rotation == ExifInterface.ORIENTATION_ROTATE_180) { rotationDegree = 180; } - else if (rotation == ExifInterface.ORIENTATION_ROTATE_270) { rotationDegree = 270; } + if (rotation == ExifInterface.ORIENTATION_ROTATE_90) { + rotationDegree = 90; + } else if (rotation == ExifInterface.ORIENTATION_ROTATE_180) { + rotationDegree = 180; + } else if (rotation == ExifInterface.ORIENTATION_ROTATE_270) { + rotationDegree = 270; + } matrix = new Matrix(); - if (rotation != 0f) {matrix.preRotate(rotationDegree);} + if (rotation != 0f) { + matrix.preRotate(rotationDegree); + } } SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); int resizeSet = sharedpreferences.getInt(Helper.SET_PICTURE_RESIZE, Helper.S_4MO); - if( mediaType == MediaType.PROFILE) + if (mediaType == MediaType.PROFILE) resizeSet = Helper.S_1MO; double resizeby = size; - if( resizeSet == Helper.S_512KO){ + if (resizeSet == Helper.S_512KO) { resizeby = 4194304; - }else if(resizeSet == Helper.S_1MO){ + } else if (resizeSet == Helper.S_1MO) { resizeby = 8388608; - }else if(resizeSet == Helper.S_2MO){ + } else if (resizeSet == Helper.S_2MO) { resizeby = 16777216; - }else if(resizeSet == Helper.S_4MO){ + } else if (resizeSet == Helper.S_4MO) { resizeby = 33554432; - }else if(resizeSet == Helper.S_6MO){ + } else if (resizeSet == Helper.S_6MO) { resizeby = 50331648; - }else if(resizeSet == Helper.S_8MO) { + } else if (resizeSet == Helper.S_8MO) { resizeby = 67108864; } - double resize = ((double)size)/resizeby; - if( resize > 1 ){ + double resize = ((double) size) / resizeby; + if (resize > 1) { Bitmap newBitmap = Bitmap.createScaledBitmap(takenImage, (int) (takenImage.getWidth() / resize), (int) (takenImage.getHeight() / resize), true); Bitmap adjustedBitmap; - if( matrix != null) + if (matrix != null) try { adjustedBitmap = Bitmap.createBitmap(newBitmap, 0, 0, newBitmap.getWidth(), newBitmap.getHeight(), matrix, true); - }catch (Exception e){ + } catch (Exception e) { adjustedBitmap = newBitmap; } else adjustedBitmap = newBitmap; ByteArrayOutputStream bos = new ByteArrayOutputStream(); - if( mime.contains("png") || mime.contains(".PNG")) + if (mime.contains("png") || mime.contains(".PNG")) adjustedBitmap.compress(Bitmap.CompressFormat.PNG, 0, bos); else adjustedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos); byte[] bitmapdata = bos.toByteArray(); bs = new ByteArrayInputStream(bitmapdata); - }else { + } else { try { InputStream inputStream = context.getContentResolver().openInputStream(uriFile); byte[] buff = new byte[8 * 1024]; int bytesRead; ByteArrayOutputStream bao = new ByteArrayOutputStream(); assert inputStream != null; - while((bytesRead = inputStream.read(buff)) != -1) { + while ((bytesRead = inputStream.read(buff)) != -1) { bao.write(buff, 0, bytesRead); } byte[] data = bao.toByteArray(); - bs = new ByteArrayInputStream(data); + bs = new ByteArrayInputStream(data); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } - }else { + } else { try { InputStream inputStream = context.getContentResolver().openInputStream(uriFile); byte[] buff = new byte[8 * 1024]; int bytesRead; ByteArrayOutputStream bao = new ByteArrayOutputStream(); assert inputStream != null; - while((bytesRead = inputStream.read(buff)) != -1) { + while ((bytesRead = inputStream.read(buff)) != -1) { bao.write(buff, 0, bytesRead); } byte[] data = bao.toByteArray(); - bs = new ByteArrayInputStream(data); + bs = new ByteArrayInputStream(data); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } - }else{ + } else { try { InputStream inputStream = context.getContentResolver().openInputStream(uriFile); byte[] buff = new byte[8 * 1024]; int bytesRead; ByteArrayOutputStream bao = new ByteArrayOutputStream(); assert inputStream != null; - while((bytesRead = inputStream.read(buff)) != -1) { + while ((bytesRead = inputStream.read(buff)) != -1) { bao.write(buff, 0, bytesRead); } byte[] data = bao.toByteArray(); - bs = new ByteArrayInputStream(data); + bs = new ByteArrayInputStream(data); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { @@ -3457,25 +3548,25 @@ public class Helper { returnCursor.close(); Random r = new Random(); int suf = r.nextInt(9999 - 1000) + 1000; - return String.valueOf(suf)+name; - }catch (Exception e){ + return String.valueOf(suf) + name; + } catch (Exception e) { Random r = new Random(); int suf = r.nextInt(9999 - 1000) + 1000; ContentResolver cr = context.getContentResolver(); String mime = cr.getType(uri); - if( mime != null && mime.split("/").length > 1) - return "__" + String.valueOf(suf)+"."+mime.split("/")[1]; + if (mime != null && mime.split("/").length > 1) + return "__" + String.valueOf(suf) + "." + mime.split("/")[1]; else - return "__" + String.valueOf(suf)+".jpg"; + return "__" + String.valueOf(suf) + ".jpg"; } } - public static Bitmap compressImageIfNeeded(Context context, Bitmap bmToCompress){ + public static Bitmap compressImageIfNeeded(Context context, Bitmap bmToCompress) { int size = bmToCompress.getByteCount(); - double resizeby = 33554432; //4Mo - double resize = ((double)size)/resizeby; - if( resize > 1 ) { + double resizeby = 33554432; //4Mo + double resize = ((double) size) / resizeby; + if (resize > 1) { Bitmap newBitmap = Bitmap.createScaledBitmap(bmToCompress, (int) (bmToCompress.getWidth() / resize), (int) (bmToCompress.getHeight() / resize), true); ByteArrayOutputStream bos = new ByteArrayOutputStream(); @@ -3497,17 +3588,14 @@ public class Helper { } - - - - /** * Allows to split the toot by dot "." for sentences - adds number at the end automatically - * @param content String initial content + * + * @param content String initial content * @param maxChars int the max chars per toot (minus 10 to write the page: 1/x, 2/x etc.) * @return ArrayList split toot */ - public static ArrayList splitToots(String content, int maxChars){ + public static ArrayList splitToots(String content, int maxChars) { String[] splitContent = content.split("\\s"); @@ -3520,32 +3608,32 @@ public class Helper { matcher = mentionLongPattern.matcher(content); while (matcher.find()) { String mentionLong = matcher.group(1); - if( !mentions.contains(mentionLong)) { + if (!mentions.contains(mentionLong)) { mentions.add(mentionLong); } } matcher = mentionPattern.matcher(content); while (matcher.find()) { String mention = matcher.group(1); - if( !mentions.contains(mention)) { + if (!mentions.contains(mention)) { mentions.add(mention); } } StringBuilder mentionString = new StringBuilder(); - for(String mention: mentions){ + for (String mention : mentions) { mentionString.append(mention).append(" "); } - int mentionLength = mentionString.length()+1; - int maxCharsPerMessage = (maxChars-10) - mentionLength; + int mentionLength = mentionString.length() + 1; + int maxCharsPerMessage = (maxChars - 10) - mentionLength; int totalCurrent = 0; ArrayList reply = new ArrayList<>(); int index = 0; - for(int i= 0 ; i < splitContent.length ; i++) { - if ((totalCurrent + splitContent[i].length()+1) < maxCharsPerMessage) { - totalCurrent += (splitContent[i].length()+1); + for (int i = 0; i < splitContent.length; i++) { + if ((totalCurrent + splitContent[i].length() + 1) < maxCharsPerMessage) { + totalCurrent += (splitContent[i].length() + 1); } else { if (content.length() > totalCurrent && totalCurrent > 0) { - String tempContent = content.substring(0, (totalCurrent-1)); + String tempContent = content.substring(0, (totalCurrent - 1)); content = content.substring(totalCurrent); reply.add(index, tempContent); @@ -3554,16 +3642,16 @@ public class Helper { } } } - if( totalCurrent > 0 ){ + if (totalCurrent > 0) { reply.add(index, content); } - if( reply.size() > 1 ){ + if (reply.size() > 1) { int i = 0; - for(String r: reply){ - if( mentions.size() > 0 ){ - reply.set(i, r + " " + mentionString + " - " + (i+1) + "/" + reply.size()); - }else{ - reply.set(i, r + " - " + (i+1) + "/" + reply.size()); + for (String r : reply) { + if (mentions.size() > 0) { + reply.set(i, r + " " + mentionString + " - " + (i + 1) + "/" + reply.size()); + } else { + reply.set(i, r + " - " + (i + 1) + "/" + reply.size()); } i++; } @@ -3572,19 +3660,19 @@ public class Helper { } - public static int countLength(String text){ - if( text == null) { + public static int countLength(String text) { + if (text == null) { return 0; } - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA ){ + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { Matcher matcherALink = Patterns.WEB_URL.matcher(text); - while (matcherALink.find()){ + while (matcherALink.find()) { int matchStart = matcherALink.start(); int matchEnd = matcherALink.end(); final String url = text.substring(matcherALink.start(1), matcherALink.end(1)); - if( matchEnd <= text.length() && matchEnd >= matchStart){ - if( url.length() > 23){ - text = text.replaceFirst(url,"abcdefghijklmnopkrstuvw"); + if (matchEnd <= text.length() && matchEnd >= matchStart) { + if (url.length() > 23) { + text = text.replaceFirst(url, "abcdefghijklmnopkrstuvw"); } } } @@ -3593,7 +3681,7 @@ public class Helper { } - public static int countWithEmoji(String text){ + public static int countWithEmoji(String text) { int emojiCount = 0; for (int i = 0; i < text.length(); i++) { int type = Character.getType(text.charAt(i)); @@ -3601,65 +3689,67 @@ public class Helper { emojiCount++; } } - return emojiCount/2; + return emojiCount / 2; } - public static boolean filterToots(Status status, RetrieveFeedsAsyncTask.Type type, boolean showAccountActivity, boolean showAccountActivityBoost, boolean showAccountActivityReplies){ + public static boolean filterToots(Status status, RetrieveFeedsAsyncTask.Type type, boolean showAccountActivity, boolean showAccountActivityBoost, boolean showAccountActivityReplies) { String filter; - if( status == null) + if (status == null) return true; - if( type != null) { + if (type != null) { if (type == RetrieveFeedsAsyncTask.Type.HOME) filter = regex_home; else if (type == RetrieveFeedsAsyncTask.Type.LOCAL) filter = regex_local; else filter = regex_public; - }else { + } else { filter = regex_public; } String content = status.getContent(); - if( status.getSpoiler_text() != null) - content += " "+ status.getSpoiler_text(); - if( status.getAccount() == null) + if (status.getSpoiler_text() != null) + content += " " + status.getSpoiler_text(); + if (status.getAccount() == null) return false; - if( type == RetrieveFeedsAsyncTask.Type.ART && !MainActivity.show_art_nsfw && status.isSensitive()) + if (type == RetrieveFeedsAsyncTask.Type.ART && !MainActivity.show_art_nsfw && status.isSensitive()) return false; - if(MainActivity.filters != null){ - for(Filters mfilter: filters){ + if (MainActivity.filters != null) { + for (Filters mfilter : filters) { ArrayList filterContext = mfilter.getContext(); - if( + if ( (type == RetrieveFeedsAsyncTask.Type.HOME && filterContext.contains("home")) || (type == RetrieveFeedsAsyncTask.Type.LOCAL && filterContext.contains("public")) || (type == RetrieveFeedsAsyncTask.Type.PUBLIC && filterContext.contains("public")) - ) { + ) { if (mfilter.isWhole_word() && content.contains(mfilter.getPhrase())) { return false; } else { try { - if( mfilter.getPhrase().contains("#")) + if (mfilter.getPhrase().contains("#")) mfilter.setPhrase(mfilter.getPhrase().replaceAll("\\#", "\\#")); Pattern filterPattern = Pattern.compile("(" + mfilter.getPhrase() + ")", Pattern.CASE_INSENSITIVE); Matcher matcher = filterPattern.matcher(content); if (matcher.find()) return false; - } catch (Exception ignored) { } + } catch (Exception ignored) { + } } } } } - if(filter != null && filter.length() > 0){ + if (filter != null && filter.length() > 0) { try { Pattern filterPattern = Pattern.compile("(" + filter + ")", Pattern.CASE_INSENSITIVE); Matcher matcher = filterPattern.matcher(content); if (matcher.find()) return false; - }catch (Exception ignored){ } + } catch (Exception ignored) { + } } if (type == RetrieveFeedsAsyncTask.Type.HOME) { if (status.getReblog() != null && !MainActivity.show_boosts) @@ -3668,7 +3758,7 @@ public class Helper { return false; } } else { - if( showAccountActivity) { + if (showAccountActivity) { if (status.getReblog() != null && !showAccountActivityBoost) return false; else if (status.getIn_reply_to_id() != null && !status.getIn_reply_to_id().equals("null") && !showAccountActivityReplies) @@ -3677,7 +3767,7 @@ public class Helper { } if (mutedAccount != null && mutedAccount.size() > 0 && mutedAccount.contains(status.getAccount().getId())) return false; - if( status.isNotice()) + if (status.isNotice()) return false; return true; } @@ -3685,7 +3775,7 @@ public class Helper { public static void colorizeIconMenu(Menu menu, int toolbarIconsColor) { final PorterDuffColorFilter colorFilter = new PorterDuffColorFilter(toolbarIconsColor, PorterDuff.Mode.MULTIPLY); - for(int i = 0; i < menu.size(); i++) { + for (int i = 0; i < menu.size(); i++) { MenuItem v = menu.getItem(i); v.getIcon().setColorFilter(colorFilter); } @@ -3694,41 +3784,42 @@ public class Helper { /** * Code from "Michal Pawlowski" * https://snow.dog/blog/how-to-dynamicaly-change-android-toolbar-icons-color - * @param toolbarView toolbar view being colored + * + * @param toolbarView toolbar view being colored * @param toolbarIconsColor the target color of toolbar icons - * @param activity reference to activity needed to register observers + * @param activity reference to activity needed to register observers */ public static void colorizeToolbar(Toolbar toolbarView, int toolbarIconsColor, Activity activity) { final PorterDuffColorFilter colorFilter = new PorterDuffColorFilter(toolbarIconsColor, PorterDuff.Mode.SRC_ATOP); - for(int i = 0; i < toolbarView.getChildCount(); i++) { + for (int i = 0; i < toolbarView.getChildCount(); i++) { final View v = toolbarView.getChildAt(i); //Step 1 : Changing the color of back button (or open drawer button). - if(v instanceof ImageButton) { + if (v instanceof ImageButton) { //Action Bar back button - ((ImageButton)v).getDrawable().setColorFilter(colorFilter); + ((ImageButton) v).getDrawable().setColorFilter(colorFilter); } - if(v instanceof ImageView) { + if (v instanceof ImageView) { //Action Bar back button - if( v.getId() != R.id.pp_actionBar) - ((ImageView)v).setColorFilter(colorFilter); + if (v.getId() != R.id.pp_actionBar) + ((ImageView) v).setColorFilter(colorFilter); } - if(v instanceof MenuItem) { - ((MenuItem)v).getIcon().setColorFilter(colorFilter); + if (v instanceof MenuItem) { + ((MenuItem) v).getIcon().setColorFilter(colorFilter); } - if(v instanceof ActionMenuView) { - for(int j = 0; j < ((ActionMenuView)v).getChildCount(); j++) { + if (v instanceof ActionMenuView) { + for (int j = 0; j < ((ActionMenuView) v).getChildCount(); j++) { //Step 2: Changing the color of any ActionMenuViews - icons that //are not back button, nor text, nor overflow menu icon. - final View innerView = ((ActionMenuView)v).getChildAt(j); + final View innerView = ((ActionMenuView) v).getChildAt(j); - if(innerView instanceof ActionMenuItemView) { - int drawablesCount = ((ActionMenuItemView)innerView).getCompoundDrawables().length; - for(int k = 0; k < drawablesCount; k++) { - if(((ActionMenuItemView)innerView).getCompoundDrawables()[k] != null) { + if (innerView instanceof ActionMenuItemView) { + int drawablesCount = ((ActionMenuItemView) innerView).getCompoundDrawables().length; + for (int k = 0; k < drawablesCount; k++) { + if (((ActionMenuItemView) innerView).getCompoundDrawables()[k] != null) { final int finalK = k; //Important to set the color filter in seperate thread, @@ -3745,11 +3836,11 @@ public class Helper { } } } - if(v instanceof LinearLayout) { - for(int j = 0; j < ((LinearLayout)v).getChildCount(); j++) { + if (v instanceof LinearLayout) { + for (int j = 0; j < ((LinearLayout) v).getChildCount(); j++) { //Action Bar back button if (((LinearLayout) v).getChildAt(j) instanceof ImageView) - ((ImageView)((LinearLayout) v).getChildAt(j)).setColorFilter(colorFilter); + ((ImageView) ((LinearLayout) v).getChildAt(j)).setColorFilter(colorFilter); } } //Step 3: Changing the color of title and subtitle. @@ -3764,12 +3855,12 @@ public class Helper { /** * It's important to set overflowDescription atribute in styles, so we can grab the reference * to the overflow icon. Check: res/values/styles.xml + * * @param activity * @param colorFilter */ private static void setOverflowButtonColor(final Activity activity, final PorterDuffColorFilter colorFilter) { - @SuppressLint("PrivateResource") - final String overflowDescription = activity.getString(R.string.abc_action_menu_overflow_description); + @SuppressLint("PrivateResource") final String overflowDescription = activity.getString(R.string.abc_action_menu_overflow_description); final ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); final ViewTreeObserver viewTreeObserver = decorView.getViewTreeObserver(); viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @@ -3781,9 +3872,9 @@ public class Helper { if (outViews.isEmpty()) { return; } - androidx.appcompat.widget.AppCompatImageView overflow=(androidx.appcompat.widget.AppCompatImageView) outViews.get(0); + androidx.appcompat.widget.AppCompatImageView overflow = (androidx.appcompat.widget.AppCompatImageView) outViews.get(0); overflow.setColorFilter(colorFilter); - removeOnGlobalLayoutListener(decorView,this); + removeOnGlobalLayoutListener(decorView, this); } }); } @@ -3791,17 +3882,14 @@ public class Helper { private static void removeOnGlobalLayoutListener(View v, ViewTreeObserver.OnGlobalLayoutListener listener) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { v.getViewTreeObserver().removeGlobalOnLayoutListener(listener); - } - else { + } else { v.getViewTreeObserver().removeOnGlobalLayoutListener(listener); } } - - - public static String getLocalesTwoChars(int stringLocaleId){ - switch (stringLocaleId){ + public static String getLocalesTwoChars(int stringLocaleId) { + switch (stringLocaleId) { case R.string.default_language: return Locale.getDefault().getLanguage(); case R.string.english: @@ -3856,14 +3944,10 @@ public class Helper { } - - - - - public static int languageSpinnerPosition(Context context){ + public static int languageSpinnerPosition(Context context) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); String defaultLocaleString = sharedpreferences.getString(Helper.SET_DEFAULT_LOCALE_NEW, "NOT_DEFINED"); - switch (defaultLocaleString){ + switch (defaultLocaleString) { case "NOT_DEFINED": return 0; case "en": @@ -3911,7 +3995,7 @@ public class Helper { } } - public static String[] getLocales(Context context){ + public static String[] getLocales(Context context) { String[] locale = new String[21]; locale[0] = context.getString(R.string.default_language); locale[1] = context.getString(R.string.english); @@ -3937,32 +4021,32 @@ public class Helper { return locale; } - public static boolean containsCaseInsensitive(String s, List l){ - for (String string : l){ - if (string.equalsIgnoreCase(s)){ + public static boolean containsCaseInsensitive(String s, List l) { + for (String string : l) { + if (string.equalsIgnoreCase(s)) { return true; } } return false; } - public static boolean isTablet(Context context){ + public static boolean isTablet(Context context) { return context.getResources().getBoolean(R.bool.isTablet); } - public static void changeMaterialSpinnerColor(Context context, MaterialSpinner materialSpinner){ + public static void changeMaterialSpinnerColor(Context context, MaterialSpinner materialSpinner) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if( theme == THEME_BLACK) { + if (theme == THEME_BLACK) { materialSpinner.setBackgroundColor(ContextCompat.getColor(context, R.color.black_3)); materialSpinner.setArrowColor(ContextCompat.getColor(context, R.color.dark_text)); materialSpinner.setTextColor(ContextCompat.getColor(context, R.color.dark_text)); - }else if( theme == THEME_DARK){ + } else if (theme == THEME_DARK) { materialSpinner.setBackgroundColor(ContextCompat.getColor(context, R.color.mastodonC1)); materialSpinner.setArrowColor(ContextCompat.getColor(context, R.color.dark_text)); materialSpinner.setTextColor(ContextCompat.getColor(context, R.color.dark_text)); - }else { + } else { materialSpinner.setBackgroundColor(ContextCompat.getColor(context, R.color.white)); materialSpinner.setArrowColor(ContextCompat.getColor(context, R.color.black)); materialSpinner.setTextColor(ContextCompat.getColor(context, R.color.black)); @@ -4001,8 +4085,8 @@ public class Helper { style = R.style.Dialog; } AlertDialog.Builder builder = new AlertDialog.Builder(contextReference.get(), style); - LayoutInflater inflater = ((MainActivity)contextReference.get()).getLayoutInflater(); - View dialogView = inflater.inflate(R.layout.popup_cache, new LinearLayout((MainActivity)contextReference.get()), false); + LayoutInflater inflater = ((MainActivity) contextReference.get()).getLayoutInflater(); + View dialogView = inflater.inflate(R.layout.popup_cache, new LinearLayout((MainActivity) contextReference.get()), false); TextView message = dialogView.findViewById(R.id.message); message.setText(contextReference.get().getString(R.string.cache_message, String.format("%s %s", String.format(Locale.getDefault(), "%.2f", cacheSize), contextReference.get().getString(R.string.cache_units)))); builder.setView(dialogView); @@ -4027,24 +4111,24 @@ public class Helper { } SQLiteDatabase db = Sqlite.getInstance(contextReference.get(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); new StatusCacheDAO(contextReference.get(), db).removeDuplicate(); - if( clean_all.isChecked()){ - if( cache_timeline.isChecked()){ + if (clean_all.isChecked()) { + if (cache_timeline.isChecked()) { new TimelineCacheDAO(contextReference.get(), db).removeAll(); } - if( cache_owntoots.isChecked()){ + if (cache_owntoots.isChecked()) { new StatusCacheDAO(contextReference.get(), db).removeAll(ARCHIVE_CACHE); } - if( cache_bookmarks.isChecked()){ + if (cache_bookmarks.isChecked()) { new StatusCacheDAO(contextReference.get(), db).removeAll(BOOKMARK_CACHE); } - }else{ - if( cache_timeline.isChecked()){ + } else { + if (cache_timeline.isChecked()) { new TimelineCacheDAO(contextReference.get(), db).removeAllConnected(); } - if( cache_owntoots.isChecked()){ + if (cache_owntoots.isChecked()) { new StatusCacheDAO(contextReference.get(), db).removeAllStatus(ARCHIVE_CACHE); } - if( cache_bookmarks.isChecked()){ + if (cache_bookmarks.isChecked()) { new StatusCacheDAO(contextReference.get(), db).removeAllStatus(BOOKMARK_CACHE); } } @@ -4067,7 +4151,6 @@ public class Helper { } - public static String getFilePathFromURI(Context context, Uri contentUri) { //copy file and send new file path String fileName = getFileName(contentUri); @@ -4135,14 +4218,14 @@ public class Helper { }; - public static String remove_tracking_param(String original_content){ - if( original_content == null) + public static String remove_tracking_param(String original_content) { + if (original_content == null) return original_content; String cleaned_content = original_content; - for(String utm: UTM_PARAMS){ - cleaned_content = cleaned_content.replaceAll("&"+utm+"=[0-9a-zA-Z._-]*", ""); - cleaned_content = cleaned_content.replaceAll("&"+utm+"=[0-9a-zA-Z._-]*", ""); - cleaned_content = cleaned_content.replaceAll("\\?"+utm+"=[0-9a-zA-Z._-]*", "?"); + for (String utm : UTM_PARAMS) { + cleaned_content = cleaned_content.replaceAll("&" + utm + "=[0-9a-zA-Z._-]*", ""); + cleaned_content = cleaned_content.replaceAll("&" + utm + "=[0-9a-zA-Z._-]*", ""); + cleaned_content = cleaned_content.replaceAll("\\?" + utm + "=[0-9a-zA-Z._-]*", "?"); } return cleaned_content; } @@ -4160,7 +4243,7 @@ public class Helper { } - public static void download(Context context, String file, String url){ + public static void download(Context context, String file, String url) { FetchConfiguration fetchConfiguration = new FetchConfiguration.Builder(context) @@ -4171,37 +4254,47 @@ public class Helper { @Override public void onWaitingNetwork(@NotNull Download download) { } + @Override public void onStarted(@NotNull Download download, @NotNull List list, int i) { } + @Override public void onResumed(@NotNull Download download) { } + @Override public void onRemoved(@NotNull Download download) { } + @Override public void onQueued(@NotNull Download download, boolean b) { } + @Override public void onProgress(@NotNull Download download, long l, long l1) { } + @Override public void onPaused(@NotNull Download download) { } + @Override public void onError(@NotNull Download download, @NotNull Error error, @org.jetbrains.annotations.Nullable Throwable throwable) { - Toasty.error(context, context.getString(R.string.toast_error),Toast.LENGTH_LONG).show(); + Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); } + @Override public void onDownloadBlockUpdated(@NotNull Download download, @NotNull DownloadBlock downloadBlock, int i) { } + @Override public void onDeleted(@NotNull Download download) { } + @Override public void onCompleted(@NotNull Download download) { - if( download.getFileUri().getPath() != null) { + if (download.getFileUri().getPath() != null) { String url = download.getUrl(); final String fileName = URLUtil.guessFileName(url, null, null); final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); @@ -4209,19 +4302,21 @@ public class Helper { File file = new File(download.getFileUri().getPath()); final Intent intent = new Intent(); intent.setAction(android.content.Intent.ACTION_VIEW); - Uri uri = Uri.parse("file://" + file.getAbsolutePath() ); + Uri uri = Uri.parse("file://" + file.getAbsolutePath()); intent.setDataAndType(uri, mime); SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(context)); Account account = new AccountDAO(context, db).getUniqAccount(userId, instance); Helper.notify_user(context, account, intent, BitmapFactory.decodeResource(context.getResources(), - R.mipmap.ic_launcher), Helper.NotifType.STORE, context.getString(R.string.save_over), context.getString(R.string.download_from, fileName)); + R.mipmap.ic_launcher), Helper.NotifType.STORE, context.getString(R.string.save_over), context.getString(R.string.download_from, fileName)); } } + @Override public void onCancelled(@NotNull Download download) { } + @Override public void onAdded(@NotNull Download download) { } @@ -4276,7 +4371,8 @@ public class Helper { orbotConnected = false; } }); - } catch (Exception ignored) { } + } catch (Exception ignored) { + } } @@ -4309,17 +4405,18 @@ public class Helper { specs.add(ConnectionSpec.CLEARTEXT); client.connectionSpecs(specs); - } catch (Exception ignored) {} + } catch (Exception ignored) { + } } return client; } - public static void exportInstanceBlock(Context context, String username){ + public static void exportInstanceBlock(Context context, String username) { String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ENGLISH).format(new Date()); - String backupDBPath = "instance_mute_"+timeStamp+".csv"; + String backupDBPath = "instance_mute_" + timeStamp + ".csv"; File sd = Environment.getExternalStorageDirectory(); final String filename = sd + "/" + backupDBPath; @@ -4337,9 +4434,10 @@ public class Helper { apiResponse = new API(contextReference.get()).getBlockedDomain(null); return apiResponse.getDomains(); } + @Override - protected void onPostExecute( List domains) { - if( domains == null){ + protected void onPostExecute(List domains) { + if (domains == null) { return; } final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); @@ -4347,21 +4445,21 @@ public class Helper { int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, style); - LayoutInflater inflater = ((MutedInstanceActivity)context).getLayoutInflater(); + LayoutInflater inflater = ((MutedInstanceActivity) context).getLayoutInflater(); ScrollView scrollView = new ScrollView(context); LinearLayout linearLayout_main = new LinearLayout(context); linearLayout_main.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); linearLayout_main.setOrientation(LinearLayout.VERTICAL); - for(String domain: domains){ - View item = inflater.inflate(R.layout.muted_instance_popup, new LinearLayout(context), false); + for (String domain : domains) { + View item = inflater.inflate(R.layout.muted_instance_popup, new LinearLayout(context), false); CheckBox checkBox = item.findViewById(R.id.popup_domain); checkBox.setText(domain); linearLayout_main.addView(item); @@ -4372,20 +4470,20 @@ public class Helper { dialogBuilder.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { - for( int i = 0; i < linearLayout_main.getChildCount() ; i++){ + for (int i = 0; i < linearLayout_main.getChildCount(); i++) { LinearLayout linearLayout = (LinearLayout) linearLayout_main.getChildAt(i); CheckBox checkBox = linearLayout.findViewById(R.id.popup_domain); EditText editText = linearLayout.findViewById(R.id.popup_comment); - if( checkBox.isChecked()){ + if (checkBox.isChecked()) { String comment = null; String domain = checkBox.getText().toString().trim(); - if( editText.getText() != null) { + if (editText.getText() != null) { comment = editText.getText().toString().trim(); } domainBlocked.put(domain, comment); } } - if( domainBlocked.size() > 0 ){ + if (domainBlocked.size() > 0) { new Thread() { public void run() { try { @@ -4397,10 +4495,10 @@ public class Helper { fw.append('\n'); Iterator it = domainBlocked.entrySet().iterator(); while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - fw.append((String)pair.getKey()); + Map.Entry pair = (Map.Entry) it.next(); + fw.append((String) pair.getKey()); fw.append(','); - fw.append((String)pair.getValue()); + fw.append((String) pair.getValue()); fw.append('\n'); it.remove(); } @@ -4415,8 +4513,8 @@ public class Helper { String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(context)); Account account = new AccountDAO(context, db).getUniqAccount(userId, instance); - Helper.notify_user(context, account,intent, BitmapFactory.decodeResource(context.getResources(), - R.mipmap.ic_launcher), Helper.NotifType.STORE, context.getString(R.string.muted_instance_exported), context.getString(R.string.download_from, backupDBPath)); + Helper.notify_user(context, account, intent, BitmapFactory.decodeResource(context.getResources(), + R.mipmap.ic_launcher), Helper.NotifType.STORE, context.getString(R.string.muted_instance_exported), context.getString(R.string.download_from, backupDBPath)); } }.start(); } @@ -4432,12 +4530,11 @@ public class Helper { AlertDialog alertDialog = dialogBuilder.create(); alertDialog.show(); } - }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR ); + }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } - - public static void importInstanceBlock(Context context, HashMap instances){ + public static void importInstanceBlock(Context context, HashMap instances) { final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); @@ -4445,13 +4542,13 @@ public class Helper { int style; if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; - } else if (theme == Helper.THEME_BLACK){ + } else if (theme == Helper.THEME_BLACK) { style = R.style.DialogBlack; - }else { + } else { style = R.style.Dialog; } AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, style); - LayoutInflater inflater = ((MutedInstanceActivity)context).getLayoutInflater(); + LayoutInflater inflater = ((MutedInstanceActivity) context).getLayoutInflater(); ScrollView scrollView = new ScrollView(context); LinearLayout linearLayout_main = new LinearLayout(context); @@ -4459,12 +4556,12 @@ public class Helper { linearLayout_main.setOrientation(LinearLayout.VERTICAL); Iterator it = instances.entrySet().iterator(); while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - View item = inflater.inflate(R.layout.muted_instance_popup, new LinearLayout(context), false); + Map.Entry pair = (Map.Entry) it.next(); + View item = inflater.inflate(R.layout.muted_instance_popup, new LinearLayout(context), false); CheckBox checkBox = item.findViewById(R.id.popup_domain); checkBox.setText(pair.getKey().toString().trim()); item.findViewById(R.id.popup_comment).setVisibility(View.GONE); - if( pair.getValue() != null) { + if (pair.getValue() != null) { TextView textView = item.findViewById(R.id.comment_text); textView.setText(pair.getValue().toString()); textView.setVisibility(View.VISIBLE); @@ -4478,26 +4575,26 @@ public class Helper { dialogBuilder.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { - for( int i = 0; i < linearLayout_main.getChildCount() ; i++){ + for (int i = 0; i < linearLayout_main.getChildCount(); i++) { LinearLayout linearLayout = (LinearLayout) linearLayout_main.getChildAt(i); CheckBox checkBox = linearLayout.findViewById(R.id.popup_domain); - if( checkBox.isChecked()){ + if (checkBox.isChecked()) { String domain = checkBox.getText().toString().trim(); domainBlocked.put(domain, null); } } - if( domainBlocked.size() > 0 ){ + if (domainBlocked.size() > 0) { new Thread() { public void run() { Iterator it = domainBlocked.entrySet().iterator(); while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); + Map.Entry pair = (Map.Entry) it.next(); try { sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } - new PostActionAsyncTask(context, API.StatusAction.BLOCK_DOMAIN, pair.getKey().toString().trim(), ((MutedInstanceActivity)context)).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new PostActionAsyncTask(context, API.StatusAction.BLOCK_DOMAIN, pair.getKey().toString().trim(), ((MutedInstanceActivity) context)).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); it.remove(); } } @@ -4528,38 +4625,39 @@ public class Helper { apiResponse = new API(contextReference.get()).getBlockedDomain(null); return apiResponse.getDomains(); } + @Override - protected void onPostExecute( List domains) { - if( domains == null){ + protected void onPostExecute(List domains) { + if (domains == null) { return; } } - }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR ); + }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } - public static String[] ALPHA = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", + public static String[] ALPHA = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "!", ",", "?", - ".", "'" }; - public static String[] MORSE = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", + ".", "'"}; + public static String[] MORSE = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.", "-----", "-.-.--", "--..--", - "..--..", ".-.-.-", ".----.", }; + "..--..", ".-.-.-", ".----.",}; - public static Bitmap drawableToBitmap (Drawable drawable) { + public static Bitmap drawableToBitmap(Drawable drawable) { Bitmap bitmap; if (drawable instanceof BitmapDrawable) { BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; - if(bitmapDrawable.getBitmap() != null) { + if (bitmapDrawable.getBitmap() != null) { return bitmapDrawable.getBitmap(); } } - if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) { + if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) { bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); } else { bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); diff --git a/app/src/main/java/app/fedilab/android/helper/MastalabAutoCompleteTextView.java b/app/src/main/java/app/fedilab/android/helper/MastalabAutoCompleteTextView.java index 37d87be65..8f58ed311 100644 --- a/app/src/main/java/app/fedilab/android/helper/MastalabAutoCompleteTextView.java +++ b/app/src/main/java/app/fedilab/android/helper/MastalabAutoCompleteTextView.java @@ -5,9 +5,11 @@ import android.content.Context; import android.content.SharedPreferences; import android.content.res.TypedArray; import android.graphics.Paint; + import androidx.annotation.CallSuper; import androidx.annotation.DimenRes; import androidx.annotation.Px; + import android.util.AttributeSet; import android.view.KeyEvent; @@ -58,7 +60,7 @@ public class MastalabAutoCompleteTextView extends androidx.appcompat.widget.AppC protected void onTextChanged(final CharSequence text, final int start, final int lengthBefore, final int lengthAfter) { final Paint.FontMetrics fontMetrics = getPaint().getFontMetrics(); final float defaultEmojiSize = fontMetrics.descent - fontMetrics.ascent; - if( emoji && !autocomplete) { + if (emoji && !autocomplete) { EmojiManager.getInstance().replaceWithImages(getContext(), getText(), emojiSize, defaultEmojiSize); } } @@ -75,7 +77,9 @@ public class MastalabAutoCompleteTextView extends androidx.appcompat.widget.AppC return emojiSize; } - @Override @CallSuper public void input(final Emoji emoji) { + @Override + @CallSuper + public void input(final Emoji emoji) { if (emoji != null && !autocomplete) { final int start = getSelectionStart(); final int end = getSelectionEnd(); diff --git a/app/src/main/java/app/fedilab/android/helper/MenuFloating.java b/app/src/main/java/app/fedilab/android/helper/MenuFloating.java index e89950372..73109a68b 100644 --- a/app/src/main/java/app/fedilab/android/helper/MenuFloating.java +++ b/app/src/main/java/app/fedilab/android/helper/MenuFloating.java @@ -24,16 +24,16 @@ public class MenuFloating extends com.oguzdev.circularfloatingactionmenu.library super.detach(); setPosition(position, layoutParams); // If no custom backgroundDrawable is specified, use the background drawable of the theme. - if(backgroundDrawable == null) { - if(theme == THEME_LIGHT) + if (backgroundDrawable == null) { + if (theme == THEME_LIGHT) backgroundDrawable = activity.getResources().getDrawable(R.drawable.button_action_selector); else backgroundDrawable = activity.getResources().getDrawable(R.drawable.button_action_dark_selector); } setBackgroundResource(backgroundDrawable); - if(tags == null || !tags.contains(tag)) { - if( tags == null) + if (tags == null || !tags.contains(tag)) { + if (tags == null) tags = new ArrayList<>(); if (contentView != null) { setContentView(contentView, contentParams); @@ -47,19 +47,19 @@ public class MenuFloating extends com.oguzdev.circularfloatingactionmenu.library /** * Attaches it to the content view with specified LayoutParams. + * * @param layoutParams */ public void attach(View view, ViewGroup.LayoutParams layoutParams) { - if(this.getParent()!=null) - ((ViewGroup)this.getParent()).removeView(this); - ((ViewGroup)view).addView(this, layoutParams); + if (this.getParent() != null) + ((ViewGroup) this.getParent()).removeView(this); + ((ViewGroup) view).addView(this, layoutParams); } private void setBackgroundResource(Drawable drawable) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { setBackground(drawable); - } - else { + } else { setBackgroundDrawable(drawable); } } @@ -92,7 +92,7 @@ public class MenuFloating extends com.oguzdev.circularfloatingactionmenu.library setPosition(FloatingActionButton.POSITION_BOTTOM_RIGHT); } - public Builder intoView(View view){ + public Builder intoView(View view) { this.targetedView = view; return this; } @@ -130,6 +130,7 @@ public class MenuFloating extends com.oguzdev.circularfloatingactionmenu.library this.contentParams = contentParams; return this; } + public Builder setTag(String tag) { this.tag = tag; return this; diff --git a/app/src/main/java/app/fedilab/android/helper/RecyclerItemClickListener.java b/app/src/main/java/app/fedilab/android/helper/RecyclerItemClickListener.java index f9c813849..9ea08407a 100644 --- a/app/src/main/java/app/fedilab/android/helper/RecyclerItemClickListener.java +++ b/app/src/main/java/app/fedilab/android/helper/RecyclerItemClickListener.java @@ -26,7 +26,8 @@ public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListen public RecyclerItemClickListener(Context context, OnItemClickListener listener) { mListener = listener; mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { - @Override public boolean onSingleTapUp(MotionEvent e) { + @Override + public boolean onSingleTapUp(MotionEvent e) { return true; } }); @@ -42,7 +43,8 @@ public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListen } @Override - public void onTouchEvent(@NotNull RecyclerView view, @NotNull MotionEvent motionEvent) { } + public void onTouchEvent(@NotNull RecyclerView view, @NotNull MotionEvent motionEvent) { + } @Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { diff --git a/app/src/main/java/app/fedilab/android/helper/SwipeControledViewPager.java b/app/src/main/java/app/fedilab/android/helper/SwipeControledViewPager.java index dc749c9d6..5627e1f2c 100644 --- a/app/src/main/java/app/fedilab/android/helper/SwipeControledViewPager.java +++ b/app/src/main/java/app/fedilab/android/helper/SwipeControledViewPager.java @@ -14,8 +14,11 @@ package app.fedilab.android.helper; * * You should have received a copy of the GNU General Public License along with Fedilab; if not, * see . */ + import android.content.Context; + import androidx.viewpager.widget.ViewPager; + import android.util.AttributeSet; @@ -47,7 +50,6 @@ public class SwipeControledViewPager extends ViewPager { } - public void setEnableSwipe(boolean enableSwipe) { this.enableSwipe = enableSwipe; } diff --git a/app/src/main/java/app/fedilab/android/helper/itemtouchhelper/ItemTouchHelperAdapter.java b/app/src/main/java/app/fedilab/android/helper/itemtouchhelper/ItemTouchHelperAdapter.java index 6dc4bdbcd..68f72b9e3 100644 --- a/app/src/main/java/app/fedilab/android/helper/itemtouchhelper/ItemTouchHelperAdapter.java +++ b/app/src/main/java/app/fedilab/android/helper/itemtouchhelper/ItemTouchHelperAdapter.java @@ -37,7 +37,6 @@ public interface ItemTouchHelperAdapter { * @param fromPosition The start position of the moved item. * @param toPosition Then resolved position of the moved item. * @return True if the item was moved to the new adapter position. - * * @see RecyclerView#getAdapterPositionFor(RecyclerView.ViewHolder) * @see RecyclerView.ViewHolder#getAdapterPosition() */ @@ -51,7 +50,6 @@ public interface ItemTouchHelperAdapter { * adjusting the underlying data to reflect this removal. * * @param position The position of the item dismissed. - * * @see RecyclerView#getAdapterPositionFor(RecyclerView.ViewHolder) * @see RecyclerView.ViewHolder#getAdapterPosition() */ diff --git a/app/src/main/java/app/fedilab/android/helper/itemtouchhelper/OnUndoListener.java b/app/src/main/java/app/fedilab/android/helper/itemtouchhelper/OnUndoListener.java index 0d2da8f92..eb1834138 100644 --- a/app/src/main/java/app/fedilab/android/helper/itemtouchhelper/OnUndoListener.java +++ b/app/src/main/java/app/fedilab/android/helper/itemtouchhelper/OnUndoListener.java @@ -27,7 +27,7 @@ public interface OnUndoListener { * Called when an item is removed * * @param timelines The timeline ManageTimelines - * @param position The position of the item in tablayout + * @param position The position of the item in tablayout */ void onUndo(ManageTimelines timelines, int position); diff --git a/app/src/main/java/app/fedilab/android/helper/itemtouchhelper/SimpleItemTouchHelperCallback.java b/app/src/main/java/app/fedilab/android/helper/itemtouchhelper/SimpleItemTouchHelperCallback.java index 36cb0765d..9b38b06b5 100644 --- a/app/src/main/java/app/fedilab/android/helper/itemtouchhelper/SimpleItemTouchHelperCallback.java +++ b/app/src/main/java/app/fedilab/android/helper/itemtouchhelper/SimpleItemTouchHelperCallback.java @@ -18,6 +18,7 @@ package app.fedilab.android.helper.itemtouchhelper; import android.graphics.Canvas; + import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.ItemTouchHelper; diff --git a/app/src/main/java/app/fedilab/android/imageeditor/ColorPickerAdapter.java b/app/src/main/java/app/fedilab/android/imageeditor/ColorPickerAdapter.java index aa16c3922..33c9f4156 100644 --- a/app/src/main/java/app/fedilab/android/imageeditor/ColorPickerAdapter.java +++ b/app/src/main/java/app/fedilab/android/imageeditor/ColorPickerAdapter.java @@ -7,9 +7,11 @@ import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.OvalShape; + import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.RecyclerView; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; diff --git a/app/src/main/java/app/fedilab/android/imageeditor/EmojiBSFragment.java b/app/src/main/java/app/fedilab/android/imageeditor/EmojiBSFragment.java index 6e71c256c..fb2bbfd1a 100644 --- a/app/src/main/java/app/fedilab/android/imageeditor/EmojiBSFragment.java +++ b/app/src/main/java/app/fedilab/android/imageeditor/EmojiBSFragment.java @@ -2,12 +2,16 @@ package app.fedilab.android.imageeditor; import android.annotation.SuppressLint; import android.app.Dialog; + import androidx.annotation.NonNull; + import com.google.android.material.bottomsheet.BottomSheetBehavior; import com.google.android.material.bottomsheet.BottomSheetDialogFragment; + import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; diff --git a/app/src/main/java/app/fedilab/android/imageeditor/PropertiesBSFragment.java b/app/src/main/java/app/fedilab/android/imageeditor/PropertiesBSFragment.java index 2b523ae82..235af1689 100644 --- a/app/src/main/java/app/fedilab/android/imageeditor/PropertiesBSFragment.java +++ b/app/src/main/java/app/fedilab/android/imageeditor/PropertiesBSFragment.java @@ -1,11 +1,15 @@ package app.fedilab.android.imageeditor; import android.os.Bundle; + import androidx.annotation.NonNull; import androidx.annotation.Nullable; + import com.google.android.material.bottomsheet.BottomSheetDialogFragment; + import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; diff --git a/app/src/main/java/app/fedilab/android/imageeditor/StickerBSFragment.java b/app/src/main/java/app/fedilab/android/imageeditor/StickerBSFragment.java index ea4345ff7..b652877c7 100644 --- a/app/src/main/java/app/fedilab/android/imageeditor/StickerBSFragment.java +++ b/app/src/main/java/app/fedilab/android/imageeditor/StickerBSFragment.java @@ -5,13 +5,17 @@ import android.app.Dialog; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; + import androidx.annotation.NonNull; import androidx.annotation.Nullable; + import com.google.android.material.bottomsheet.BottomSheetBehavior; import com.google.android.material.bottomsheet.BottomSheetDialogFragment; + import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; diff --git a/app/src/main/java/app/fedilab/android/imageeditor/TextEditorDialogFragment.java b/app/src/main/java/app/fedilab/android/imageeditor/TextEditorDialogFragment.java index 97db1fde2..368e15384 100644 --- a/app/src/main/java/app/fedilab/android/imageeditor/TextEditorDialogFragment.java +++ b/app/src/main/java/app/fedilab/android/imageeditor/TextEditorDialogFragment.java @@ -4,6 +4,7 @@ import android.app.Dialog; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; + import androidx.annotation.ColorInt; import androidx.annotation.NonNull; import androidx.annotation.Nullable; @@ -12,6 +13,7 @@ import androidx.core.content.ContextCompat; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; + import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; diff --git a/app/src/main/java/app/fedilab/android/imageeditor/filters/FilterViewAdapter.java b/app/src/main/java/app/fedilab/android/imageeditor/filters/FilterViewAdapter.java index ec28d68e3..73d8dd11e 100644 --- a/app/src/main/java/app/fedilab/android/imageeditor/filters/FilterViewAdapter.java +++ b/app/src/main/java/app/fedilab/android/imageeditor/filters/FilterViewAdapter.java @@ -4,8 +4,10 @@ import android.content.Context; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; + import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; + import android.util.Pair; import android.view.LayoutInflater; import android.view.View; diff --git a/app/src/main/java/app/fedilab/android/imageeditor/tools/EditingToolsAdapter.java b/app/src/main/java/app/fedilab/android/imageeditor/tools/EditingToolsAdapter.java index 7ce4203e3..fd3e39780 100644 --- a/app/src/main/java/app/fedilab/android/imageeditor/tools/EditingToolsAdapter.java +++ b/app/src/main/java/app/fedilab/android/imageeditor/tools/EditingToolsAdapter.java @@ -2,6 +2,7 @@ package app.fedilab.android.imageeditor.tools; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; + import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -28,7 +29,7 @@ public class EditingToolsAdapter extends RecyclerView.Adapter. */ package app.fedilab.android.interfaces; + import app.fedilab.android.client.Entities.Account; diff --git a/app/src/main/java/app/fedilab/android/interfaces/OnRetrieveEmojiInterface.java b/app/src/main/java/app/fedilab/android/interfaces/OnRetrieveEmojiInterface.java index 700dc0ff2..becefd2f8 100644 --- a/app/src/main/java/app/fedilab/android/interfaces/OnRetrieveEmojiInterface.java +++ b/app/src/main/java/app/fedilab/android/interfaces/OnRetrieveEmojiInterface.java @@ -27,6 +27,8 @@ import app.fedilab.android.client.Entities.Status; */ public interface OnRetrieveEmojiInterface { void onRetrieveEmoji(Status status, boolean fromTranslation); + void onRetrieveEmoji(Notification notification); + void onRetrieveSearchEmoji(List emojis); } diff --git a/app/src/main/java/app/fedilab/android/interfaces/OnRetrievePeertubeInterface.java b/app/src/main/java/app/fedilab/android/interfaces/OnRetrievePeertubeInterface.java index b50de47cb..10164ed78 100644 --- a/app/src/main/java/app/fedilab/android/interfaces/OnRetrievePeertubeInterface.java +++ b/app/src/main/java/app/fedilab/android/interfaces/OnRetrievePeertubeInterface.java @@ -22,6 +22,8 @@ import app.fedilab.android.client.APIResponse; */ public interface OnRetrievePeertubeInterface { void onRetrievePeertube(APIResponse apiResponse); + void onRetrievePeertubeComments(APIResponse apiResponse); + void onRetrievePeertubeChannels(APIResponse apiResponse); } diff --git a/app/src/main/java/app/fedilab/android/interfaces/OnRetrieveSearcAccountshInterface.java b/app/src/main/java/app/fedilab/android/interfaces/OnRetrieveSearcAccountshInterface.java index f0b542e61..4431e3223 100644 --- a/app/src/main/java/app/fedilab/android/interfaces/OnRetrieveSearcAccountshInterface.java +++ b/app/src/main/java/app/fedilab/android/interfaces/OnRetrieveSearcAccountshInterface.java @@ -23,5 +23,6 @@ import app.fedilab.android.client.APIResponse; */ public interface OnRetrieveSearcAccountshInterface { void onRetrieveSearchAccounts(APIResponse apiResponse); + void onRetrieveContact(APIResponse apiResponse); } diff --git a/app/src/main/java/app/fedilab/android/interfaces/OnRetrieveWhoToFollowInterface.java b/app/src/main/java/app/fedilab/android/interfaces/OnRetrieveWhoToFollowInterface.java index b7e13fe62..13d1411f9 100644 --- a/app/src/main/java/app/fedilab/android/interfaces/OnRetrieveWhoToFollowInterface.java +++ b/app/src/main/java/app/fedilab/android/interfaces/OnRetrieveWhoToFollowInterface.java @@ -25,5 +25,6 @@ import app.fedilab.android.client.Entities.TrunkAccount; */ public interface OnRetrieveWhoToFollowInterface { void onRetrieveWhoToFollowList(List list); + void onRetrieveWhoToFollowAccount(List trunkAccounts); } diff --git a/app/src/main/java/app/fedilab/android/jobs/ApplicationJob.java b/app/src/main/java/app/fedilab/android/jobs/ApplicationJob.java index 91e203ec1..5235493b6 100644 --- a/app/src/main/java/app/fedilab/android/jobs/ApplicationJob.java +++ b/app/src/main/java/app/fedilab/android/jobs/ApplicationJob.java @@ -13,6 +13,7 @@ package app.fedilab.android.jobs; * * You should have received a copy of the GNU General Public License along with Fedilab; if not, * see . */ + import androidx.annotation.NonNull; import com.evernote.android.job.Job; @@ -44,7 +45,7 @@ public class ApplicationJob implements JobCreator { } @SuppressWarnings("unused") - public static void cancelAllJob(String TAG){ + public static void cancelAllJob(String TAG) { JobManager.instance().cancelAllForTag(TAG); } diff --git a/app/src/main/java/app/fedilab/android/jobs/BackupNotificationsSyncJob.java b/app/src/main/java/app/fedilab/android/jobs/BackupNotificationsSyncJob.java index 883c33280..3ac7059bd 100644 --- a/app/src/main/java/app/fedilab/android/jobs/BackupNotificationsSyncJob.java +++ b/app/src/main/java/app/fedilab/android/jobs/BackupNotificationsSyncJob.java @@ -44,6 +44,7 @@ import app.fedilab.android.sqlite.Sqlite; public class BackupNotificationsSyncJob extends Job { static final String BACKUP_NOTIFICATIONS_SYNC = "job_backup_notification"; + static { Helper.installProvider(); } @@ -74,7 +75,8 @@ public class BackupNotificationsSyncJob extends Job { .setRequirementsEnforced(false) .build() .schedule(); - }catch (Exception ignored){} + } catch (Exception ignored) { + } return jobRequestschedule; } @@ -87,15 +89,16 @@ public class BackupNotificationsSyncJob extends Job { SQLiteDatabase db = Sqlite.getInstance(getContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); final List accounts = new AccountDAO(getContext(), db).getAllAccount(); SharedPreferences sharedpreferences = getContext().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - for(Account account: accounts) { - boolean autobackup = sharedpreferences.getBoolean(Helper.SET_AUTO_BACKUP_NOTIFICATIONS + account.getId() + account.getInstance(), false); - if( autobackup) { + for (Account account : accounts) { + boolean autobackup = sharedpreferences.getBoolean(Helper.SET_AUTO_BACKUP_NOTIFICATIONS + account.getId() + account.getInstance(), false); + if (autobackup) { try { Intent backupIntent = new Intent(getContext(), BackupNotificationInDataBaseService.class); backupIntent.putExtra("userid", account.getId()); backupIntent.putExtra("instance", account.getInstance()); getContext().startService(backupIntent); - }catch (Exception ignored){} + } catch (Exception ignored) { + } } } } diff --git a/app/src/main/java/app/fedilab/android/jobs/BackupStatusesSyncJob.java b/app/src/main/java/app/fedilab/android/jobs/BackupStatusesSyncJob.java index 0aa4b7464..a7a39262b 100644 --- a/app/src/main/java/app/fedilab/android/jobs/BackupStatusesSyncJob.java +++ b/app/src/main/java/app/fedilab/android/jobs/BackupStatusesSyncJob.java @@ -74,6 +74,7 @@ import static app.fedilab.android.helper.Helper.notify_user; public class BackupStatusesSyncJob extends Job { static final String BACKUP_SYNC = "job_backup"; + static { Helper.installProvider(); } @@ -104,7 +105,8 @@ public class BackupStatusesSyncJob extends Job { .setRequirementsEnforced(false) .build() .schedule(); - }catch (Exception ignored){} + } catch (Exception ignored) { + } return jobRequestschedule; } @@ -117,15 +119,16 @@ public class BackupStatusesSyncJob extends Job { SQLiteDatabase db = Sqlite.getInstance(getContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); final List accounts = new AccountDAO(getContext(), db).getAllAccount(); SharedPreferences sharedpreferences = getContext().getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); - for(Account account: accounts) { - boolean autobackup = sharedpreferences.getBoolean(Helper.SET_AUTO_BACKUP_STATUSES + account.getId() + account.getInstance(), false); - if( autobackup) { + for (Account account : accounts) { + boolean autobackup = sharedpreferences.getBoolean(Helper.SET_AUTO_BACKUP_STATUSES + account.getId() + account.getInstance(), false); + if (autobackup) { try { Intent backupIntent = new Intent(getContext(), BackupStatusInDataBaseService.class); backupIntent.putExtra("userid", account.getId()); backupIntent.putExtra("instance", account.getInstance()); getContext().startService(backupIntent); - }catch (Exception ignored){} + } catch (Exception ignored) { + } } } } diff --git a/app/src/main/java/app/fedilab/android/jobs/NotificationsSyncJob.java b/app/src/main/java/app/fedilab/android/jobs/NotificationsSyncJob.java index 69144d162..a148eb6ea 100644 --- a/app/src/main/java/app/fedilab/android/jobs/NotificationsSyncJob.java +++ b/app/src/main/java/app/fedilab/android/jobs/NotificationsSyncJob.java @@ -22,6 +22,7 @@ import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Handler; import android.os.Looper; + import androidx.annotation.NonNull; import androidx.annotation.Nullable; @@ -70,6 +71,7 @@ import static app.fedilab.android.helper.Helper.notify_user; public class NotificationsSyncJob extends Job { static final String NOTIFICATION_REFRESH = "job_notification"; + static { Helper.installProvider(); } @@ -99,7 +101,8 @@ public class NotificationsSyncJob extends Job { .setRequirementsEnforced(false) .build() .schedule(); - }catch (Exception ignored){} + } catch (Exception ignored) { + } return jobRequestschedule; } @@ -109,7 +112,7 @@ public class NotificationsSyncJob extends Job { * Task in background starts here. */ private void callAsynchronousTask() { - if( !canNotify(getContext())) + if (!canNotify(getContext())) return; SQLiteDatabase db = Sqlite.getInstance(getContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); //If an Internet connection and user agrees with notification refresh @@ -121,20 +124,20 @@ public class NotificationsSyncJob extends Job { boolean notif_share = sharedpreferences.getBoolean(Helper.SET_NOTIF_SHARE, true); boolean notif_poll = sharedpreferences.getBoolean(Helper.SET_NOTIF_POLL, true); //User disagree with all notifications - if( !notif_follow && !notif_add && !notif_mention && !notif_share && !notif_poll) + if (!notif_follow && !notif_add && !notif_mention && !notif_share && !notif_poll) return; //Nothing is done //No account connected, the service is stopped - if(!Helper.isLoggedIn(getContext())) + if (!Helper.isLoggedIn(getContext())) return; //If WIFI only and on WIFI OR user defined any connections to use the service. - if(!sharedpreferences.getBoolean(Helper.SET_WIFI_ONLY, false) || Helper.isOnWIFI(getContext())) { - List accounts = new AccountDAO(getContext(),db).getAllAccountCrossAction(); + if (!sharedpreferences.getBoolean(Helper.SET_WIFI_ONLY, false) || Helper.isOnWIFI(getContext())) { + List accounts = new AccountDAO(getContext(), db).getAllAccountCrossAction(); //It means there is no user in DB. - if( accounts == null ) + if (accounts == null) return; //Retrieve users in db that owner has. - for (Account account: accounts) { - if( account.getSocial() == null || account.getSocial().equals("MASTODON")|| account.getSocial().equals("PLEROMA")) { + for (Account account : accounts) { + if (account.getSocial() == null || account.getSocial().equals("MASTODON") || account.getSocial().equals("PLEROMA")) { API api = new API(getContext(), account.getInstance(), account.getToken()); APIResponse apiResponse = api.getNotificationsSince(DisplayNotificationsFragment.Type.ALL, null, false); onRetrieveNotifications(apiResponse, account); @@ -146,7 +149,7 @@ public class NotificationsSyncJob extends Job { private void onRetrieveNotifications(APIResponse apiResponse, final Account account) { List notificationsReceived = apiResponse.getNotifications(); - if( apiResponse.getError() != null || notificationsReceived == null || notificationsReceived.size() == 0 || account == null) + if (apiResponse.getError() != null || notificationsReceived == null || notificationsReceived.size() == 0 || account == null) return; final SharedPreferences sharedpreferences = getContext().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); boolean notif_follow = sharedpreferences.getBoolean(Helper.SET_NOTIF_FOLLOW, true); @@ -155,15 +158,15 @@ public class NotificationsSyncJob extends Job { boolean notif_share = sharedpreferences.getBoolean(Helper.SET_NOTIF_SHARE, true); boolean notif_poll = sharedpreferences.getBoolean(Helper.SET_NOTIF_POLL, true); final String max_id = sharedpreferences.getString(Helper.LAST_NOTIFICATION_MAX_ID + account.getId() + account.getInstance(), null); - final List notifications = new ArrayList<>(); + final List notifications = new ArrayList<>(); int pos = 0; - for(Notification notif: notificationsReceived){ - if( max_id == null || notif.getId().compareTo(max_id) > 0 ) { + for (Notification notif : notificationsReceived) { + if (max_id == null || notif.getId().compareTo(max_id) > 0) { notifications.add(pos, notif); pos++; } } - if( notifications.size() == 0 ) + if (notifications.size() == 0) return; //No previous notifications in cache, so no notification will be sent int newFollows = 0; @@ -177,67 +180,67 @@ public class NotificationsSyncJob extends Job { String targeted_account = null; Helper.NotifType notifType = Helper.NotifType.MENTION; - for(Notification notification: notifications){ - switch (notification.getType()){ + for (Notification notification : notifications) { + switch (notification.getType()) { case "mention": notifType = Helper.NotifType.MENTION; - if(notif_mention){ + if (notif_mention) { newMentions++; - if( notificationUrl == null){ + if (notificationUrl == null) { notificationUrl = notification.getAccount().getAvatar(); - if( notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0 ) - title = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true),getContext().getString(R.string.notif_mention)); + if (notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) + title = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true), getContext().getString(R.string.notif_mention)); else - title = String.format("@%s %s", notification.getAccount().getAcct(),getContext().getString(R.string.notif_mention)); + title = String.format("@%s %s", notification.getAccount().getAcct(), getContext().getString(R.string.notif_mention)); } } break; case "reblog": notifType = Helper.NotifType.BOOST; - if(notif_share){ + if (notif_share) { newShare++; - if( notificationUrl == null){ + if (notificationUrl == null) { notificationUrl = notification.getAccount().getAvatar(); - if( notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0 ) - title = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true),getContext().getString(R.string.notif_reblog)); + if (notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) + title = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true), getContext().getString(R.string.notif_reblog)); else - title = String.format("@%s %s", notification.getAccount().getAcct(),getContext().getString(R.string.notif_reblog)); + title = String.format("@%s %s", notification.getAccount().getAcct(), getContext().getString(R.string.notif_reblog)); } } break; case "favourite": notifType = Helper.NotifType.FAV; - if(notif_add){ + if (notif_add) { newAdds++; - if( notificationUrl == null){ + if (notificationUrl == null) { notificationUrl = notification.getAccount().getAvatar(); - if( notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0 ) - title = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true),getContext().getString(R.string.notif_favourite)); + if (notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) + title = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true), getContext().getString(R.string.notif_favourite)); else - title = String.format("@%s %s", notification.getAccount().getAcct(),getContext().getString(R.string.notif_favourite)); + title = String.format("@%s %s", notification.getAccount().getAcct(), getContext().getString(R.string.notif_favourite)); } } break; case "follow": notifType = Helper.NotifType.FOLLLOW; - if(notif_follow){ + if (notif_follow) { newFollows++; - if( notificationUrl == null){ + if (notificationUrl == null) { notificationUrl = notification.getAccount().getAvatar(); - if( notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0 ) - title = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true),getContext().getString(R.string.notif_follow)); + if (notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) + title = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true), getContext().getString(R.string.notif_follow)); else - title = String.format("@%s %s", notification.getAccount().getAcct(),getContext().getString(R.string.notif_follow)); + title = String.format("@%s %s", notification.getAccount().getAcct(), getContext().getString(R.string.notif_follow)); targeted_account = notification.getAccount().getId(); } } break; case "poll": notifType = Helper.NotifType.POLL; - if(notif_poll){ + if (notif_poll) { newPolls++; - if( notificationUrl == null){ + if (notificationUrl == null) { notificationUrl = notification.getAccount().getAvatar(); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); if (notification.getAccount().getId() != null && notification.getAccount().getId().equals(userId)) @@ -252,21 +255,21 @@ public class NotificationsSyncJob extends Job { } int allNotifCount = newFollows + newAdds + newMentions + newShare + newPolls; - if( allNotifCount > 0){ + if (allNotifCount > 0) { //Some others notification - int other = allNotifCount -1; - if(other > 0 ) + int other = allNotifCount - 1; + if (other > 0) message = getContext().getResources().getQuantityString(R.plurals.other_notifications, other, other); else message = ""; final Intent intent = new Intent(getContext(), MainActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK ); + intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra(INTENT_ACTION, NOTIFICATION_INTENT); intent.putExtra(PREF_KEY_ID, account.getId()); - if( targeted_account != null && notifType == Helper.NotifType.FOLLLOW) + if (targeted_account != null && notifType == Helper.NotifType.FOLLLOW) intent.putExtra(INTENT_TARGETED_ACCOUNT, targeted_account); intent.putExtra(PREF_INSTANCE, account.getInstance()); - if( notificationUrl != null ){ + if (notificationUrl != null) { final String finalTitle = title; Handler mainHandler = new Handler(Looper.getMainLooper()); @@ -290,7 +293,7 @@ public class NotificationsSyncJob extends Job { notify_user(getContext(), account, intent, BitmapFactory.decodeResource(getContext().getResources(), R.drawable.mastodonlogo), finalNotifType, finalTitle, message); String lastNotif = sharedpreferences.getString(Helper.LAST_NOTIFICATION_MAX_ID + account.getId() + account.getInstance(), null); - if( lastNotif == null || notifications.get(0).getId().compareTo(lastNotif) > 0){ + if (lastNotif == null || notifications.get(0).getId().compareTo(lastNotif) > 0) { SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(Helper.LAST_NOTIFICATION_MAX_ID + account.getId() + account.getInstance(), notifications.get(0).getId()); editor.apply(); @@ -303,7 +306,7 @@ public class NotificationsSyncJob extends Job { public void onResourceReady(@NonNull Bitmap resource, Transition transition) { notify_user(getContext(), account, intent, resource, finalNotifType, finalTitle, message); String lastNotif = sharedpreferences.getString(Helper.LAST_NOTIFICATION_MAX_ID + account.getId() + account.getInstance(), null); - if( lastNotif == null || notifications.get(0).getId().compareTo(lastNotif) > 0){ + if (lastNotif == null || notifications.get(0).getId().compareTo(lastNotif) > 0) { SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(Helper.LAST_NOTIFICATION_MAX_ID + account.getId() + account.getInstance(), notifications.get(0).getId()); editor.apply(); diff --git a/app/src/main/java/app/fedilab/android/jobs/ScheduledBoostsSyncJob.java b/app/src/main/java/app/fedilab/android/jobs/ScheduledBoostsSyncJob.java index 6839ae202..f5affe7ff 100644 --- a/app/src/main/java/app/fedilab/android/jobs/ScheduledBoostsSyncJob.java +++ b/app/src/main/java/app/fedilab/android/jobs/ScheduledBoostsSyncJob.java @@ -16,6 +16,7 @@ package app.fedilab.android.jobs; import android.content.Context; import android.database.sqlite.SQLiteDatabase; + import androidx.annotation.NonNull; import com.evernote.android.job.Job; @@ -42,6 +43,7 @@ import app.fedilab.android.sqlite.Sqlite; public class ScheduledBoostsSyncJob extends Job { public static final String SCHEDULED_BOOST = "job_scheduled_boost"; + static { Helper.installProvider(); } @@ -54,19 +56,19 @@ public class ScheduledBoostsSyncJob extends Job { SQLiteDatabase db = Sqlite.getInstance(getContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); //Retrieves the stored status StoredStatus storedStatus = new BoostScheduleDAO(getContext(), db).getStatusScheduled(jobId); - if( storedStatus != null){ + if (storedStatus != null) { String userId = storedStatus.getUserId(); String instance = storedStatus.getInstance(); - if( instance != null && userId != null){ + if (instance != null && userId != null) { Account account = new AccountDAO(getContext(), db).getUniqAccount(userId, instance); - if( account != null){ + if (account != null) { //Retrieves the linked status to toot Status status = storedStatus.getStatus(); - if( status != null){ - int statusCode = new API(getContext(), account.getInstance(), account.getToken()).postAction( API.StatusAction.REBLOG, status.getId()); + if (status != null) { + int statusCode = new API(getContext(), account.getInstance(), account.getToken()).postAction(API.StatusAction.REBLOG, status.getId()); //Toot was sent - if( statusCode == 200){ + if (statusCode == 200) { new BoostScheduleDAO(getContext(), db).updateScheduledDone(jobId, new Date()); } } @@ -77,13 +79,13 @@ public class ScheduledBoostsSyncJob extends Job { } - public static int schedule(Context context, Status status, long timestampScheduling){ + public static int schedule(Context context, Status status, long timestampScheduling) { - long startMs = (timestampScheduling - new Date().getTime()); + long startMs = (timestampScheduling - new Date().getTime()); long endMs = startMs + TimeUnit.MINUTES.toMillis(5); SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - int jobId = new JobRequest.Builder(ScheduledBoostsSyncJob.SCHEDULED_BOOST) + int jobId = new JobRequest.Builder(ScheduledBoostsSyncJob.SCHEDULED_BOOST) .setExecutionWindow(startMs, endMs) .setUpdateCurrent(false) .setRequiredNetworkType(JobRequest.NetworkType.METERED) @@ -95,13 +97,13 @@ public class ScheduledBoostsSyncJob extends Job { } - public static int scheduleUpdate(Context context, int tootStoredId, long timestampScheduling){ + public static int scheduleUpdate(Context context, int tootStoredId, long timestampScheduling) { - long startMs = (timestampScheduling - new Date().getTime()); + long startMs = (timestampScheduling - new Date().getTime()); long endMs = startMs + TimeUnit.MINUTES.toMillis(5); SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - int jobId = new JobRequest.Builder(ScheduledTootsSyncJob.SCHEDULED_TOOT) + int jobId = new JobRequest.Builder(ScheduledTootsSyncJob.SCHEDULED_TOOT) .setExecutionWindow(startMs, endMs) .setUpdateCurrent(false) .setRequiredNetworkType(JobRequest.NetworkType.METERED) diff --git a/app/src/main/java/app/fedilab/android/jobs/ScheduledTootsSyncJob.java b/app/src/main/java/app/fedilab/android/jobs/ScheduledTootsSyncJob.java index 74c5a4182..9452724a7 100644 --- a/app/src/main/java/app/fedilab/android/jobs/ScheduledTootsSyncJob.java +++ b/app/src/main/java/app/fedilab/android/jobs/ScheduledTootsSyncJob.java @@ -16,6 +16,7 @@ package app.fedilab.android.jobs; import android.content.Context; import android.database.sqlite.SQLiteDatabase; + import androidx.annotation.NonNull; import com.evernote.android.job.Job; @@ -42,6 +43,7 @@ import app.fedilab.android.sqlite.StatusStoredDAO; public class ScheduledTootsSyncJob extends Job { public static final String SCHEDULED_TOOT = "job_scheduled_toot"; + static { Helper.installProvider(); } @@ -54,18 +56,18 @@ public class ScheduledTootsSyncJob extends Job { SQLiteDatabase db = Sqlite.getInstance(getContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); //Retrieves the stored status StoredStatus storedStatus = new StatusStoredDAO(getContext(), db).getStatusScheduled(jobId); - if( storedStatus != null){ + if (storedStatus != null) { String userId = storedStatus.getUserId(); String instance = storedStatus.getInstance(); - if( instance != null && userId != null){ + if (instance != null && userId != null) { Account account = new AccountDAO(getContext(), db).getUniqAccount(userId, instance); - if( account != null){ + if (account != null) { //Retrieves the linked status to toot Status status = storedStatus.getStatus(); - if( status != null){ + if (status != null) { int statusCode = new API(getContext(), account.getInstance(), account.getToken()).statusAction(status); //Toot was sent - if( statusCode == 200){ + if (statusCode == 200) { new StatusStoredDAO(getContext(), db).updateScheduledDone(jobId, new Date()); } } @@ -76,13 +78,13 @@ public class ScheduledTootsSyncJob extends Job { } - public static int schedule(Context context, long id, long timestampScheduling){ + public static int schedule(Context context, long id, long timestampScheduling) { - long startMs = (timestampScheduling - new Date().getTime()); + long startMs = (timestampScheduling - new Date().getTime()); long endMs = startMs + TimeUnit.MINUTES.toMillis(5); SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - int jobId = new JobRequest.Builder(ScheduledTootsSyncJob.SCHEDULED_TOOT) + int jobId = new JobRequest.Builder(ScheduledTootsSyncJob.SCHEDULED_TOOT) .setExecutionWindow(startMs, endMs) .setUpdateCurrent(false) .setRequiredNetworkType(JobRequest.NetworkType.METERED) diff --git a/app/src/main/java/app/fedilab/android/services/BackupNotificationInDataBaseService.java b/app/src/main/java/app/fedilab/android/services/BackupNotificationInDataBaseService.java index 2172efa3c..1da3d7bd6 100644 --- a/app/src/main/java/app/fedilab/android/services/BackupNotificationInDataBaseService.java +++ b/app/src/main/java/app/fedilab/android/services/BackupNotificationInDataBaseService.java @@ -53,6 +53,7 @@ public class BackupNotificationInDataBaseService extends IntentService { private static int instanceRunning = 0; + /** * Creates an IntentService. Invoked by your subclass's constructor. * @@ -62,13 +63,13 @@ public class BackupNotificationInDataBaseService extends IntentService { public BackupNotificationInDataBaseService(String name) { super(name); } + @SuppressWarnings("unused") public BackupNotificationInDataBaseService() { super("BackupNotificationInDataBaseService"); } - public void onCreate() { super.onCreate(); } @@ -80,31 +81,31 @@ public class BackupNotificationInDataBaseService extends IntentService { String userId = null; String instance = null; - if( intent != null && intent.hasExtra("userid") && intent.hasExtra("instance")){ + if (intent != null && intent.hasExtra("userid") && intent.hasExtra("instance")) { userId = intent.getStringExtra("userid"); instance = intent.getStringExtra("instance"); toastMessage = false; } SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - if( userId == null || instance == null) { + if (userId == null || instance == null) { userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); instance = sharedpreferences.getString(Helper.PREF_INSTANCE, null); } boolean finalToastMessage = toastMessage; - if( instanceRunning == 0 ){ + if (instanceRunning == 0) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { - if(finalToastMessage) { + if (finalToastMessage) { Toasty.info(getApplicationContext(), getString(R.string.data_export_start), Toast.LENGTH_LONG).show(); } } }); - }else { + } else { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { - if(finalToastMessage) { + if (finalToastMessage) { Toasty.info(getApplicationContext(), getString(R.string.data_export_running), Toast.LENGTH_LONG).show(); } } @@ -127,8 +128,8 @@ public class BackupNotificationInDataBaseService extends IntentService { max_id = apiResponse.getMax_id(); List notifications = apiResponse.getNotifications(); - for(Notification tmpNotification : notifications) { - if(lastId != null && tmpNotification.getId().compareTo(lastId) <= 0){ + for (Notification tmpNotification : notifications) { + if (lastId != null && tmpNotification.getId().compareTo(lastId) <= 0) { canContinue = false; break; } @@ -137,9 +138,9 @@ public class BackupNotificationInDataBaseService extends IntentService { backupNotifications.add(tmpNotification); } SystemClock.sleep(500); - }while (max_id != null && canContinue); + } while (max_id != null && canContinue); - if(backupNotifications.size() > 0){ + if (backupNotifications.size() > 0) { Intent backupIntent = new Intent(Helper.INTENT_BACKUP_FINISH); LocalBroadcastManager.getInstance(this).sendBroadcast(backupIntent); } @@ -147,7 +148,7 @@ public class BackupNotificationInDataBaseService extends IntentService { Intent mainActivity = new Intent(BackupNotificationInDataBaseService.this, MainActivity.class); mainActivity.putExtra(Helper.INTENT_ACTION, Helper.BACKUP_NOTIFICATION_INTENT); String title = getString(R.string.data_backup_toots, account.getAcct()); - if(finalToastMessage) { + if (finalToastMessage) { Helper.notify_user(getApplicationContext(), account, mainActivity, BitmapFactory.decodeResource(getResources(), R.drawable.mastodonlogo), Helper.NotifType.BACKUP, title, message); } @@ -158,7 +159,7 @@ public class BackupNotificationInDataBaseService extends IntentService { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { - if(finalToastMessage) { + if (finalToastMessage) { Toasty.error(getApplicationContext(), finalMessage, Toast.LENGTH_LONG).show(); } } diff --git a/app/src/main/java/app/fedilab/android/services/BackupStatusInDataBaseService.java b/app/src/main/java/app/fedilab/android/services/BackupStatusInDataBaseService.java index d939c8c12..711f85db8 100644 --- a/app/src/main/java/app/fedilab/android/services/BackupStatusInDataBaseService.java +++ b/app/src/main/java/app/fedilab/android/services/BackupStatusInDataBaseService.java @@ -22,6 +22,7 @@ import android.database.sqlite.SQLiteDatabase; import android.graphics.BitmapFactory; import android.os.Handler; import android.os.Looper; + import androidx.annotation.Nullable; import androidx.localbroadcastmanager.content.LocalBroadcastManager; @@ -54,6 +55,7 @@ public class BackupStatusInDataBaseService extends IntentService { private static int instanceRunning = 0; + /** * Creates an IntentService. Invoked by your subclass's constructor. * @@ -63,13 +65,13 @@ public class BackupStatusInDataBaseService extends IntentService { public BackupStatusInDataBaseService(String name) { super(name); } + @SuppressWarnings("unused") public BackupStatusInDataBaseService() { super("BackupStatusInDataBaseService"); } - public void onCreate() { super.onCreate(); } @@ -81,31 +83,31 @@ public class BackupStatusInDataBaseService extends IntentService { String userId = null; String instance = null; - if( intent != null && intent.hasExtra("userid") && intent.hasExtra("instance")){ + if (intent != null && intent.hasExtra("userid") && intent.hasExtra("instance")) { userId = intent.getStringExtra("userid"); instance = intent.getStringExtra("instance"); toastMessage = false; } SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - if( userId == null || instance == null) { + if (userId == null || instance == null) { userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); instance = sharedpreferences.getString(Helper.PREF_INSTANCE, null); } boolean finalToastMessage = toastMessage; - if( instanceRunning == 0 ){ + if (instanceRunning == 0) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { - if(finalToastMessage) { + if (finalToastMessage) { Toasty.info(getApplicationContext(), getString(R.string.data_export_start), Toast.LENGTH_LONG).show(); } } }); - }else { + } else { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { - if(finalToastMessage) { + if (finalToastMessage) { Toasty.info(getApplicationContext(), getString(R.string.data_export_running), Toast.LENGTH_LONG).show(); } } @@ -127,8 +129,8 @@ public class BackupStatusInDataBaseService extends IntentService { APIResponse apiResponse = api.getStatus(userId, max_id); max_id = apiResponse.getMax_id(); List statuses = apiResponse.getStatuses(); - for(Status tmpStatus : statuses) { - if(sinceDate != null && max_id != null && tmpStatus.getCreated_at().before(sinceDate)){ + for (Status tmpStatus : statuses) { + if (sinceDate != null && max_id != null && tmpStatus.getCreated_at().before(sinceDate)) { canContinue = false; break; } @@ -136,9 +138,9 @@ public class BackupStatusInDataBaseService extends IntentService { backupStatus.add(tmpStatus); } SystemClock.sleep(500); - }while (max_id != null && canContinue); + } while (max_id != null && canContinue); - if(backupStatus.size() > 0){ + if (backupStatus.size() > 0) { Intent backupIntent = new Intent(Helper.INTENT_BACKUP_FINISH); LocalBroadcastManager.getInstance(this).sendBroadcast(backupIntent); } @@ -146,7 +148,7 @@ public class BackupStatusInDataBaseService extends IntentService { Intent mainActivity = new Intent(BackupStatusInDataBaseService.this, MainActivity.class); mainActivity.putExtra(Helper.INTENT_ACTION, Helper.BACKUP_INTENT); String title = getString(R.string.data_backup_toots, account.getAcct()); - if(finalToastMessage) { + if (finalToastMessage) { Helper.notify_user(getApplicationContext(), account, mainActivity, BitmapFactory.decodeResource(getResources(), R.drawable.mastodonlogo), Helper.NotifType.BACKUP, title, message); } @@ -157,7 +159,7 @@ public class BackupStatusInDataBaseService extends IntentService { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { - if(finalToastMessage) { + if (finalToastMessage) { Toasty.error(getApplicationContext(), finalMessage, Toast.LENGTH_LONG).show(); } } diff --git a/app/src/main/java/app/fedilab/android/services/BackupStatusService.java b/app/src/main/java/app/fedilab/android/services/BackupStatusService.java index 3d01076ae..31f18aab7 100644 --- a/app/src/main/java/app/fedilab/android/services/BackupStatusService.java +++ b/app/src/main/java/app/fedilab/android/services/BackupStatusService.java @@ -25,6 +25,7 @@ import android.os.Build; import android.os.Environment; import android.os.Handler; import android.os.Looper; + import androidx.annotation.Nullable; import android.os.SystemClock; @@ -60,6 +61,7 @@ public class BackupStatusService extends IntentService { private static int instanceRunning = 0; + /** * Creates an IntentService. Invoked by your subclass's constructor. * @@ -69,13 +71,13 @@ public class BackupStatusService extends IntentService { public BackupStatusService(String name) { super(name); } + @SuppressWarnings("unused") public BackupStatusService() { super("BackupStatusService"); } - public void onCreate() { super.onCreate(); } @@ -83,14 +85,14 @@ public class BackupStatusService extends IntentService { @Override protected void onHandleIntent(@Nullable Intent intent) { - if( instanceRunning == 0 ){ + if (instanceRunning == 0) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { Toasty.info(getApplicationContext(), getString(R.string.data_export_start), Toast.LENGTH_LONG).show(); } }); - }else { + } else { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { @@ -120,11 +122,11 @@ public class BackupStatusService extends IntentService { if (statuses.size() > 0) backupStatus.addAll(statuses); SystemClock.sleep(500); - }while (max_id != null); + } while (max_id != null); - String fileName = account.getAcct()+"@"+account.getInstance()+ Helper.dateFileToString(getApplicationContext(), new Date())+".csv"; + String fileName = account.getAcct() + "@" + account.getInstance() + Helper.dateFileToString(getApplicationContext(), new Date()) + ".csv"; String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(); - fullPath = filePath+"/"+fileName; + fullPath = filePath + "/" + fileName; PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(fullPath)), "UTF-8")); StringBuilder builder = new StringBuilder(); builder.append("id").append(','); @@ -142,9 +144,9 @@ public class BackupStatusService extends IntentService { builder.append("visibility").append(','); builder.append("media_attachments"); builder.append('\n'); - for( Status status: backupStatus){ + for (Status status : backupStatus) { //excludes reblog - if( status.getReblog() != null){ + if (status.getReblog() != null) { statusToBackUp = statusToBackUp - 1; continue; } @@ -160,20 +162,20 @@ public class BackupStatusService extends IntentService { else //noinspection deprecation content = Html.fromHtml(status.getContent()).toString(); - builder.append("\"").append(content.replace("\"", "'").replace("\n"," ")).append("\"").append(','); + builder.append("\"").append(content.replace("\"", "'").replace("\n", " ")).append("\"").append(','); builder.append("\"").append(Helper.shortDateTime(getApplicationContext(), status.getCreated_at())).append("\"").append(','); builder.append("\"").append(String.valueOf(status.getReblogs_count())).append("\"").append(','); builder.append("\"").append(String.valueOf(status.getFavourites_count())).append("\"").append(','); builder.append("\"").append(String.valueOf(status.isSensitive())).append("\"").append(','); - builder.append("\"").append(status.getSpoiler_text() !=null?status.getSpoiler_text():"").append("\"").append(','); + builder.append("\"").append(status.getSpoiler_text() != null ? status.getSpoiler_text() : "").append("\"").append(','); builder.append("\"").append(status.getVisibility()).append("\"").append(','); - if( status.getMedia_attachments() != null && status.getMedia_attachments().size() > 0){ + if (status.getMedia_attachments() != null && status.getMedia_attachments().size() > 0) { builder.append("\""); - for(Attachment attachment: status.getMedia_attachments()){ + for (Attachment attachment : status.getMedia_attachments()) { builder.append(attachment.getUrl()).append(" "); } builder.append("\""); - }else { + } else { builder.append("\"\""); } builder.append('\n'); @@ -187,7 +189,7 @@ public class BackupStatusService extends IntentService { intentOpen.setDataAndType(uri, "text/csv"); String title = getString(R.string.data_export_toots, account.getAcct()); Helper.notify_user(getApplicationContext(), account, intentOpen, BitmapFactory.decodeResource(getResources(), - R.drawable.mastodonlogo),Helper.NotifType.BACKUP, title, message); + R.drawable.mastodonlogo), Helper.NotifType.BACKUP, title, message); } catch (Exception e) { e.printStackTrace(); message = getString(R.string.data_export_error, account.getAcct()); diff --git a/app/src/main/java/app/fedilab/android/services/LiveNotificationService.java b/app/src/main/java/app/fedilab/android/services/LiveNotificationService.java index e621ac0f9..c67b209b4 100644 --- a/app/src/main/java/app/fedilab/android/services/LiveNotificationService.java +++ b/app/src/main/java/app/fedilab/android/services/LiveNotificationService.java @@ -41,6 +41,7 @@ import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.NotificationCompat; import androidx.localbroadcastmanager.content.LocalBroadcastManager; + import com.bumptech.glide.Glide; import com.bumptech.glide.load.DataSource; import com.bumptech.glide.load.engine.GlideException; @@ -91,11 +92,12 @@ public class LiveNotificationService extends Service implements NetworkStateRece static { Helper.installProvider(); } - public static String CHANNEL_ID = "live_notifications"; + + public static String CHANNEL_ID = "live_notifications"; protected Account account; boolean backgroundProcess; - private static HashMap threads = new HashMap<>(); - private static HashMap lastNotification = new HashMap<>(); + private static HashMap threads = new HashMap<>(); + private static HashMap lastNotification = new HashMap<>(); private NetworkStateReceiver networkStateReceiver; private static HashMap webSocketFutures = new HashMap<>(); private NotificationChannel channel; @@ -112,31 +114,31 @@ public class LiveNotificationService extends Service implements NetworkStateRece backgroundProcess = sharedpreferences.getBoolean(Helper.SET_KEEP_BACKGROUND_PROCESS, true); } - private void startStream(){ + private void startStream() { SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); backgroundProcess = sharedpreferences.getBoolean(Helper.SET_KEEP_BACKGROUND_PROCESS, true); boolean liveNotifications = sharedpreferences.getBoolean(Helper.SET_LIVE_NOTIFICATIONS, true); SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - if( liveNotifications ){ + if (liveNotifications) { List accountStreams = new AccountDAO(getApplicationContext(), db).getAllAccountCrossAction(); if (accountStreams != null) { for (final Account accountStream : accountStreams) { - if( accountStream.getSocial() == null || accountStream.getSocial().equals("MASTODON")|| accountStream.getSocial().equals("PLEROMA")) { + if (accountStream.getSocial() == null || accountStream.getSocial().equals("MASTODON") || accountStream.getSocial().equals("PLEROMA")) { startWork(accountStream); } } } } } - + @Override public int onStartCommand(Intent intent, int flags, int startId) { - if( intent == null || intent.getBooleanExtra("stop", false) ) { + if (intent == null || intent.getBooleanExtra("stop", false)) { stopSelf(); } - if( backgroundProcess) { + if (backgroundProcess) { if (Build.VERSION.SDK_INT >= 26) { channel = new NotificationChannel(CHANNEL_ID, "Live notifications", @@ -146,11 +148,11 @@ public class LiveNotificationService extends Service implements NetworkStateRece SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); List accountStreams = new AccountDAO(getApplicationContext(), db).getAllAccountCrossAction(); totalAccount = 0; - for(Account account: accountStreams){ - if( account.getSocial() == null || account.getSocial().equals("MASTODON")|| account.getSocial().equals("PLEROMA")) { + for (Account account : accountStreams) { + if (account.getSocial() == null || account.getSocial().equals("MASTODON") || account.getSocial().equals("PLEROMA")) { final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - boolean allowStream = sharedpreferences.getBoolean(Helper.SET_ALLOW_STREAM+account.getId()+account.getInstance(), true); - if( allowStream){ + boolean allowStream = sharedpreferences.getBoolean(Helper.SET_ALLOW_STREAM + account.getId() + account.getInstance(), true); + if (allowStream) { totalAccount++; } } @@ -159,12 +161,12 @@ public class LiveNotificationService extends Service implements NetworkStateRece android.app.Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle(getString(R.string.top_notification)) .setSmallIcon(R.drawable.fedilab_notification_icon) - .setContentText(getString(R.string.top_notification_message, String.valueOf(totalAccount),String.valueOf(eventsCount))).build(); + .setContentText(getString(R.string.top_notification_message, String.valueOf(totalAccount), String.valueOf(eventsCount))).build(); startForeground(1, notification); } return START_STICKY; - }else { + } else { return START_NOT_STICKY; } } @@ -177,8 +179,6 @@ public class LiveNotificationService extends Service implements NetworkStateRece } - - @Nullable @Override public IBinder onBind(Intent intent) { @@ -186,14 +186,14 @@ public class LiveNotificationService extends Service implements NetworkStateRece } @Override - public void onTaskRemoved(Intent rootIntent){ + public void onTaskRemoved(Intent rootIntent) { super.onTaskRemoved(rootIntent); - if(backgroundProcess){ + if (backgroundProcess) { restart(); } } - private void restart(){ + private void restart() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { Intent restartServiceIntent = new Intent(LiveNotificationService.this, LiveNotificationService.class); restartServiceIntent.setPackage(getPackageName()); @@ -216,12 +216,12 @@ public class LiveNotificationService extends Service implements NetworkStateRece headers.add("method", "GET"); headers.add("scheme", "https"); String notif_url = "user:notification"; - if( account.getSocial().toUpperCase().equals("PLEROMA")) + if (account.getSocial().toUpperCase().equals("PLEROMA")) notif_url = "user"; - String urlKey = "wss://" + account.getInstance() + "/api/v1/streaming/?stream="+notif_url+"&access_token=" + account.getToken(); + String urlKey = "wss://" + account.getInstance() + "/api/v1/streaming/?stream=" + notif_url + "&access_token=" + account.getToken(); Uri url = Uri.parse(urlKey); AsyncHttpRequest.setDefaultHeaders(headers, url); - if( Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT ) { + if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) { try { AsyncHttpClient.getDefaultInstance().getSSLSocketMiddleware().setSSLContext(new TLSSocketFactory(account.getInstance()).getSSLContext()); AsyncHttpClient.getDefaultInstance().getSSLSocketMiddleware().setConnectAllAddresses(true); @@ -233,10 +233,10 @@ public class LiveNotificationService extends Service implements NetworkStateRece } String key = account.getAcct() + "@" + account.getInstance(); if (webSocketFutures.get(key) == null || !Objects.requireNonNull(webSocketFutures.get(key)).isOpen()) { - AsyncHttpClient.getDefaultInstance().websocket("wss://" + account.getInstance() + "/api/v1/streaming/?stream="+notif_url+"&access_token=" + account.getToken(), "wss", new AsyncHttpClient.WebSocketConnectCallback() { + AsyncHttpClient.getDefaultInstance().websocket("wss://" + account.getInstance() + "/api/v1/streaming/?stream=" + notif_url + "&access_token=" + account.getToken(), "wss", new AsyncHttpClient.WebSocketConnectCallback() { @Override public void onCompleted(Exception ex, WebSocket webSocket) { - webSocketFutures.put(account.getAcct()+"@"+account.getInstance(), webSocket); + webSocketFutures.put(account.getAcct() + "@" + account.getInstance(), webSocket); if (ex != null) { return; } @@ -245,14 +245,15 @@ public class LiveNotificationService extends Service implements NetworkStateRece try { JSONObject eventJson = new JSONObject(s); onRetrieveStreaming(account, eventJson); - } catch (JSONException ignored) {} + } catch (JSONException ignored) { + } } }); webSocket.setClosedCallback(new CompletedCallback() { @Override public void onCompleted(Exception ex) { - if( networkStateReceiver.connected) { + if (networkStateReceiver.connected) { startWork(account); } } @@ -270,10 +271,10 @@ public class LiveNotificationService extends Service implements NetworkStateRece } - private void startWork(Account accountStream){ + private void startWork(Account accountStream) { String key = accountStream.getAcct() + "@" + accountStream.getInstance(); - if(!threads.containsKey(key) || !Objects.requireNonNull(threads.get(key)).isAlive()){ + if (!threads.containsKey(key) || !Objects.requireNonNull(threads.get(key)).isAlive()) { Thread thread = new Thread() { @Override public void run() { @@ -287,7 +288,7 @@ public class LiveNotificationService extends Service implements NetworkStateRece } private void onRetrieveStreaming(Account account, JSONObject response) { - if( response == null ) + if (response == null) return; final Notification notification; String dataId; @@ -308,13 +309,13 @@ public class LiveNotificationService extends Service implements NetworkStateRece android.app.Notification notificationChannel = new NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle(getString(R.string.top_notification)) .setSmallIcon(R.drawable.fedilab_notification_icon) - .setContentText(getString(R.string.top_notification_message, String.valueOf(totalAccount),String.valueOf(eventsCount))).build(); + .setContentText(getString(R.string.top_notification_message, String.valueOf(totalAccount), String.valueOf(eventsCount))).build(); startForeground(1, notificationChannel); } event = Helper.EventStreaming.NOTIFICATION; notification = API.parseNotificationResponse(getApplicationContext(), new JSONObject(response.get("payload").toString())); - if( notification == null){ + if (notification == null) { return; } b.putParcelable("data", notification); @@ -325,11 +326,11 @@ public class LiveNotificationService extends Service implements NetworkStateRece Helper.NotifType notifType = Helper.NotifType.MENTION; boolean activityRunning = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("isMainActivityRunning", false); String key = account.getAcct() + "@" + account.getInstance(); - if( lastNotification.containsKey(key) && notification.getId().compareTo(Objects.requireNonNull(lastNotification.get(key))) <= 0){ + if (lastNotification.containsKey(key) && notification.getId().compareTo(Objects.requireNonNull(lastNotification.get(key))) <= 0) { canNotify = false; } - boolean allowStream = sharedpreferences.getBoolean(Helper.SET_ALLOW_STREAM+account.getId()+account.getInstance(), true); - if( !allowStream){ + boolean allowStream = sharedpreferences.getBoolean(Helper.SET_ALLOW_STREAM + account.getId() + account.getInstance(), true); + if (!allowStream) { canNotify = false; } if ((userId == null || !userId.equals(account.getId()) || !activityRunning) && liveNotifications && canNotify && notify) { @@ -350,13 +351,13 @@ public class LiveNotificationService extends Service implements NetworkStateRece message = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true), getString(R.string.notif_mention)); else message = String.format("@%s %s", notification.getAccount().getAcct(), getString(R.string.notif_mention)); - if( notification.getStatus() != null) { - if( notification.getStatus().getSpoiler_text() != null && notification.getStatus().getSpoiler_text().length() > 0 ) { + if (notification.getStatus() != null) { + if (notification.getStatus().getSpoiler_text() != null && notification.getStatus().getSpoiler_text().length() > 0) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) message = "\n" + new SpannableString(Html.fromHtml(notification.getStatus().getSpoiler_text(), FROM_HTML_MODE_LEGACY)); else message = "\n" + new SpannableString(Html.fromHtml(notification.getStatus().getSpoiler_text())); - }else{ + } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) message = "\n" + new SpannableString(Html.fromHtml(notification.getStatus().getContent(), FROM_HTML_MODE_LEGACY)); else @@ -441,8 +442,8 @@ public class LiveNotificationService extends Service implements NetworkStateRece @Override public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) { - Helper.notify_user(getApplicationContext(),account, intent, BitmapFactory.decodeResource(getResources(), - R.drawable.mastodonlogo), finalNotifType, "@" + notification.getAccount().getAcct(), finalMessage); + Helper.notify_user(getApplicationContext(), account, intent, BitmapFactory.decodeResource(getResources(), + R.drawable.mastodonlogo), finalNotifType, "@" + notification.getAccount().getAcct(), finalMessage); return false; } }) @@ -450,7 +451,7 @@ public class LiveNotificationService extends Service implements NetworkStateRece @Override public void onResourceReady(@NonNull Bitmap resource, Transition transition) { - Helper.notify_user(getApplicationContext(), account,intent, resource, finalNotifType, "@" + notification.getAccount().getAcct(), finalMessage); + Helper.notify_user(getApplicationContext(), account, intent, resource, finalNotifType, "@" + notification.getAccount().getAcct(), finalMessage); } }); } @@ -460,7 +461,7 @@ public class LiveNotificationService extends Service implements NetworkStateRece } } - if( canSendBroadCast) { + if (canSendBroadCast) { b.putString("userIdService", account.getId()); Intent intentBC = new Intent(Helper.RECEIVE_DATA); intentBC.putExtra("eventStreaming", event); @@ -477,10 +478,12 @@ public class LiveNotificationService extends Service implements NetworkStateRece try { dataId = response.getString("id"); b.putString("dataId", dataId); - } catch (JSONException ignored) { } + } catch (JSONException ignored) { + } break; } - } catch (Exception ignored) { } + } catch (Exception ignored) { + } } @Override diff --git a/app/src/main/java/app/fedilab/android/services/NetworkStateReceiver.java b/app/src/main/java/app/fedilab/android/services/NetworkStateReceiver.java index c64d90636..8d2d23819 100644 --- a/app/src/main/java/app/fedilab/android/services/NetworkStateReceiver.java +++ b/app/src/main/java/app/fedilab/android/services/NetworkStateReceiver.java @@ -13,6 +13,7 @@ package app.fedilab.android.services; * * You should have received a copy of the GNU General Public License along with Fedilab; if not, * see . */ + import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; @@ -25,7 +26,6 @@ import java.util.Set; /** * Original work from https://stackoverflow.com/a/25873554 - * */ public class NetworkStateReceiver extends BroadcastReceiver { @@ -39,16 +39,16 @@ public class NetworkStateReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { - if(intent == null || intent.getExtras() == null) + if (intent == null || intent.getExtras() == null) return; ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); assert manager != null; NetworkInfo ni = manager.getActiveNetworkInfo(); - if(ni != null && ni.getState() == NetworkInfo.State.CONNECTED) { + if (ni != null && ni.getState() == NetworkInfo.State.CONNECTED) { connected = true; - } else if(intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) { + } else if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) { connected = false; } @@ -57,15 +57,15 @@ public class NetworkStateReceiver extends BroadcastReceiver { private void notifyStateToAll() { - for(NetworkStateReceiverListener listener : listeners) + for (NetworkStateReceiverListener listener : listeners) notifyState(listener); } private void notifyState(NetworkStateReceiverListener listener) { - if(connected == null || listener == null) + if (connected == null || listener == null) return; - if(connected) + if (connected) listener.networkAvailable(); else listener.networkUnavailable(); @@ -82,6 +82,7 @@ public class NetworkStateReceiver extends BroadcastReceiver { public interface NetworkStateReceiverListener { void networkAvailable(); + void networkUnavailable(); } } \ No newline at end of file diff --git a/app/src/main/java/app/fedilab/android/services/PeertubeUploadReceiver.java b/app/src/main/java/app/fedilab/android/services/PeertubeUploadReceiver.java index eaedfe7a7..115e4f54e 100644 --- a/app/src/main/java/app/fedilab/android/services/PeertubeUploadReceiver.java +++ b/app/src/main/java/app/fedilab/android/services/PeertubeUploadReceiver.java @@ -13,12 +13,12 @@ package app.fedilab.android.services; * * You should have received a copy of the GNU General Public License along with Fedilab; if not, * see . */ + import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; - import androidx.localbroadcastmanager.content.LocalBroadcastManager; import net.gotev.uploadservice.ServerResponse; @@ -58,13 +58,13 @@ public class PeertubeUploadReceiver extends UploadServiceBroadcastReceiver { try { JSONObject response = new JSONObject(serverResponse.getBodyAsString()); - if( !response.has("video")){ //IT's not from Peertube + if (!response.has("video")) { //IT's not from Peertube ArrayList file = uploadInfo.getSuccessfullyUploadedFiles(); Intent addMedia = new Intent(Helper.INTENT_ADD_UPLOADED_MEDIA); addMedia.putExtra("response", serverResponse.getBodyAsString()); addMedia.putStringArrayListExtra("uploadInfo", file); LocalBroadcastManager.getInstance(context).sendBroadcast(addMedia); - }else{ + } else { String videoID = response.getJSONObject("video").get("id").toString(); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedpreferences.edit(); diff --git a/app/src/main/java/app/fedilab/android/services/RestartLiveNotificationReceiver.java b/app/src/main/java/app/fedilab/android/services/RestartLiveNotificationReceiver.java index 88cc45116..cf3618015 100644 --- a/app/src/main/java/app/fedilab/android/services/RestartLiveNotificationReceiver.java +++ b/app/src/main/java/app/fedilab/android/services/RestartLiveNotificationReceiver.java @@ -13,6 +13,7 @@ package app.fedilab.android.services; * * You should have received a copy of the GNU General Public License along with Fedilab; if not, * see . */ + import android.annotation.SuppressLint; import android.content.BroadcastReceiver; import android.content.Context; @@ -34,11 +35,12 @@ public class RestartLiveNotificationReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); boolean liveNotifications = sharedpreferences.getBoolean(Helper.SET_LIVE_NOTIFICATIONS, true); - if( liveNotifications) { + if (liveNotifications) { Intent streamingServiceIntent = new Intent(context.getApplicationContext(), LiveNotificationService.class); try { context.startService(streamingServiceIntent); - }catch (Exception ignored){} + } catch (Exception ignored) { + } } } diff --git a/app/src/main/java/app/fedilab/android/services/StopLiveNotificationReceiver.java b/app/src/main/java/app/fedilab/android/services/StopLiveNotificationReceiver.java index f2280b25d..083bb4ff7 100644 --- a/app/src/main/java/app/fedilab/android/services/StopLiveNotificationReceiver.java +++ b/app/src/main/java/app/fedilab/android/services/StopLiveNotificationReceiver.java @@ -13,6 +13,7 @@ package app.fedilab.android.services; * * You should have received a copy of the GNU General Public License along with Fedilab; if not, * see . */ + import android.annotation.SuppressLint; import android.content.BroadcastReceiver; import android.content.Context; @@ -30,10 +31,11 @@ public class StopLiveNotificationReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Intent streamingServiceIntent = new Intent(context.getApplicationContext(), LiveNotificationService.class); - streamingServiceIntent.putExtra("stop",true); + streamingServiceIntent.putExtra("stop", true); try { context.startService(streamingServiceIntent); - }catch (Exception ignored){} + } catch (Exception ignored) { + } } } \ No newline at end of file diff --git a/app/src/main/java/app/fedilab/android/services/StreamingFederatedTimelineService.java b/app/src/main/java/app/fedilab/android/services/StreamingFederatedTimelineService.java index 92f557b04..31cb6cbe2 100644 --- a/app/src/main/java/app/fedilab/android/services/StreamingFederatedTimelineService.java +++ b/app/src/main/java/app/fedilab/android/services/StreamingFederatedTimelineService.java @@ -22,6 +22,7 @@ import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.Build; import android.os.Bundle; + import androidx.annotation.Nullable; import androidx.localbroadcastmanager.content.LocalBroadcastManager; @@ -57,6 +58,7 @@ public class StreamingFederatedTimelineService extends IntentService { static { Helper.installProvider(); } + /** * Creates an IntentService. Invoked by your subclass's constructor. * @@ -66,6 +68,7 @@ public class StreamingFederatedTimelineService extends IntentService { public StreamingFederatedTimelineService(String name) { super(name); } + @SuppressWarnings("unused") public StreamingFederatedTimelineService() { super("StreamingFederatedTimelineService"); @@ -78,7 +81,7 @@ public class StreamingFederatedTimelineService extends IntentService { super.onCreate(); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); boolean display_global = sharedpreferences.getBoolean(Helper.SET_DISPLAY_GLOBAL, true); - if( !display_global){ + if (!display_global) { stopSelf(); } SharedPreferences.Editor editor = sharedpreferences.edit(); @@ -95,20 +98,20 @@ public class StreamingFederatedTimelineService extends IntentService { String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, null); Account accountStream = null; - if( userId != null) { + if (userId != null) { SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); accountStream = new AccountDAO(getApplicationContext(), db).getUniqAccount(userId, instance); } - if( accountStream != null) { + if (accountStream != null) { Headers headers = new Headers(); headers.add("Authorization", "Bearer " + accountStream.getToken()); headers.add("Connection", "Keep-Alive"); headers.add("method", "GET"); headers.add("scheme", "https"); - Uri url = Uri.parse("wss://" + accountStream.getInstance() + "/api/v1/streaming/?stream=public&access_token="+ accountStream.getToken()); + Uri url = Uri.parse("wss://" + accountStream.getInstance() + "/api/v1/streaming/?stream=public&access_token=" + accountStream.getToken()); AsyncHttpRequest.setDefaultHeaders(headers, url); Account finalAccountStream = accountStream; - if( Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT ) { + if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) { try { AsyncHttpClient.getDefaultInstance().getSSLSocketMiddleware().setSSLContext(new TLSSocketFactory(accountStream.getInstance()).getSSLContext()); AsyncHttpClient.getDefaultInstance().getSSLSocketMiddleware().setConnectAllAddresses(true); @@ -118,7 +121,7 @@ public class StreamingFederatedTimelineService extends IntentService { e.printStackTrace(); } } - AsyncHttpClient.getDefaultInstance().websocket("wss://" + accountStream.getInstance() + "/api/v1/streaming/?stream=public&access_token="+ accountStream.getToken(),"wss", new AsyncHttpClient.WebSocketConnectCallback() { + AsyncHttpClient.getDefaultInstance().websocket("wss://" + accountStream.getInstance() + "/api/v1/streaming/?stream=public&access_token=" + accountStream.getToken(), "wss", new AsyncHttpClient.WebSocketConnectCallback() { @Override public void onCompleted(Exception ex, WebSocket webSocket) { if (ex != null) { @@ -135,7 +138,8 @@ public class StreamingFederatedTimelineService extends IntentService { JSONObject eventJson = new JSONObject(s); onRetrieveStreaming(finalAccountStream, eventJson); - } catch (JSONException ignored) {} + } catch (JSONException ignored) { + } } }); } @@ -144,17 +148,17 @@ public class StreamingFederatedTimelineService extends IntentService { } public void onRetrieveStreaming(Account account, JSONObject response) { - if( response == null ) + if (response == null) return; - Status status ; + Status status; Bundle b = new Bundle(); try { - if( response.get("event").toString().equals("update")){ + if (response.get("event").toString().equals("update")) { status = API.parseStatuses(getApplicationContext(), new JSONObject(response.get("payload").toString())); status.setNew(true); b.putParcelable("data", status); - if( account != null) - b.putString("userIdService",account.getId()); + if (account != null) + b.putString("userIdService", account.getId()); Intent intentBC = new Intent(Helper.RECEIVE_FEDERATED_DATA); intentBC.putExtras(b); LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intentBC); diff --git a/app/src/main/java/app/fedilab/android/services/StreamingHomeTimelineService.java b/app/src/main/java/app/fedilab/android/services/StreamingHomeTimelineService.java index 1b125fe21..258a02355 100644 --- a/app/src/main/java/app/fedilab/android/services/StreamingHomeTimelineService.java +++ b/app/src/main/java/app/fedilab/android/services/StreamingHomeTimelineService.java @@ -22,6 +22,7 @@ import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.Build; import android.os.Bundle; + import androidx.annotation.Nullable; import androidx.localbroadcastmanager.content.LocalBroadcastManager; @@ -57,6 +58,7 @@ public class StreamingHomeTimelineService extends IntentService { static { Helper.installProvider(); } + /** * Creates an IntentService. Invoked by your subclass's constructor. * @@ -66,6 +68,7 @@ public class StreamingHomeTimelineService extends IntentService { public StreamingHomeTimelineService(String name) { super(name); } + @SuppressWarnings("unused") public StreamingHomeTimelineService() { super("StreamingHomeTimelineService"); @@ -78,7 +81,7 @@ public class StreamingHomeTimelineService extends IntentService { super.onCreate(); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); boolean display_global = sharedpreferences.getBoolean(Helper.SET_DISPLAY_GLOBAL, true); - if( !display_global){ + if (!display_global) { stopSelf(); } SharedPreferences.Editor editor = sharedpreferences.edit(); @@ -95,20 +98,20 @@ public class StreamingHomeTimelineService extends IntentService { String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, null); Account accountStream = null; - if( userId != null) { + if (userId != null) { SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); accountStream = new AccountDAO(getApplicationContext(), db).getUniqAccount(userId, instance); } - if( accountStream != null) { + if (accountStream != null) { Headers headers = new Headers(); headers.add("Authorization", "Bearer " + accountStream.getToken()); headers.add("Connection", "Keep-Alive"); headers.add("method", "GET"); headers.add("scheme", "https"); - Uri url = Uri.parse("wss://" + accountStream.getInstance() + "/api/v1/streaming/?stream=user&access_token="+ accountStream.getToken()); + Uri url = Uri.parse("wss://" + accountStream.getInstance() + "/api/v1/streaming/?stream=user&access_token=" + accountStream.getToken()); AsyncHttpRequest.setDefaultHeaders(headers, url); Account finalAccountStream = accountStream; - if( Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT ) { + if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) { try { AsyncHttpClient.getDefaultInstance().getSSLSocketMiddleware().setSSLContext(new TLSSocketFactory(accountStream.getInstance()).getSSLContext()); AsyncHttpClient.getDefaultInstance().getSSLSocketMiddleware().setConnectAllAddresses(true); @@ -118,7 +121,7 @@ public class StreamingHomeTimelineService extends IntentService { e.printStackTrace(); } } - AsyncHttpClient.getDefaultInstance().websocket("wss://" + accountStream.getInstance() + "/api/v1/streaming/?stream=user&access_token="+ accountStream.getToken(),"wss", new AsyncHttpClient.WebSocketConnectCallback() { + AsyncHttpClient.getDefaultInstance().websocket("wss://" + accountStream.getInstance() + "/api/v1/streaming/?stream=user&access_token=" + accountStream.getToken(), "wss", new AsyncHttpClient.WebSocketConnectCallback() { @Override public void onCompleted(Exception ex, WebSocket webSocket) { if (ex != null) { @@ -135,7 +138,8 @@ public class StreamingHomeTimelineService extends IntentService { JSONObject eventJson = new JSONObject(s); onRetrieveStreaming(finalAccountStream, eventJson); - } catch (JSONException ignored) {} + } catch (JSONException ignored) { + } } }); } @@ -144,17 +148,17 @@ public class StreamingHomeTimelineService extends IntentService { } public void onRetrieveStreaming(Account account, JSONObject response) { - if( response == null ) + if (response == null) return; - Status status ; + Status status; Bundle b = new Bundle(); try { - if( response.get("event").toString().equals("update")){ + if (response.get("event").toString().equals("update")) { status = API.parseStatuses(getApplicationContext(), new JSONObject(response.get("payload").toString())); status.setNew(true); b.putParcelable("data", status); - if( account != null) - b.putString("userIdService",account.getId()); + if (account != null) + b.putString("userIdService", account.getId()); Intent intentBC = new Intent(Helper.RECEIVE_HOME_DATA); intentBC.putExtras(b); LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intentBC); diff --git a/app/src/main/java/app/fedilab/android/services/StreamingLocalTimelineService.java b/app/src/main/java/app/fedilab/android/services/StreamingLocalTimelineService.java index 773a07c4e..95b963af3 100644 --- a/app/src/main/java/app/fedilab/android/services/StreamingLocalTimelineService.java +++ b/app/src/main/java/app/fedilab/android/services/StreamingLocalTimelineService.java @@ -22,6 +22,7 @@ import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.Build; import android.os.Bundle; + import androidx.annotation.Nullable; import androidx.localbroadcastmanager.content.LocalBroadcastManager; @@ -57,6 +58,7 @@ public class StreamingLocalTimelineService extends IntentService { static { Helper.installProvider(); } + /** * Creates an IntentService. Invoked by your subclass's constructor. * @@ -66,6 +68,7 @@ public class StreamingLocalTimelineService extends IntentService { public StreamingLocalTimelineService(String name) { super(name); } + @SuppressWarnings("unused") public StreamingLocalTimelineService() { super("StreamingLocalTimelineService"); @@ -78,7 +81,7 @@ public class StreamingLocalTimelineService extends IntentService { super.onCreate(); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); boolean display_local = sharedpreferences.getBoolean(Helper.SET_DISPLAY_LOCAL, true); - if( !display_local){ + if (!display_local) { stopSelf(); } SharedPreferences.Editor editor = sharedpreferences.edit(); @@ -95,21 +98,21 @@ public class StreamingLocalTimelineService extends IntentService { String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, null); Account accountStream = null; - if( userId != null) { + if (userId != null) { SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); accountStream = new AccountDAO(getApplicationContext(), db).getUniqAccount(userId, instance); } - if( accountStream != null) { + if (accountStream != null) { Headers headers = new Headers(); headers.add("Authorization", "Bearer " + accountStream.getToken()); headers.add("Connection", "Keep-Alive"); headers.add("method", "GET"); headers.add("scheme", "https"); - Uri url = Uri.parse("wss://" + accountStream.getInstance() + "/api/v1/streaming/?stream=public:local&access_token="+ accountStream.getToken()); + Uri url = Uri.parse("wss://" + accountStream.getInstance() + "/api/v1/streaming/?stream=public:local&access_token=" + accountStream.getToken()); AsyncHttpRequest.setDefaultHeaders(headers, url); Account finalAccountStream = accountStream; - if( Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT ) { + if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) { try { AsyncHttpClient.getDefaultInstance().getSSLSocketMiddleware().setSSLContext(new TLSSocketFactory(accountStream.getInstance()).getSSLContext()); AsyncHttpClient.getDefaultInstance().getSSLSocketMiddleware().setConnectAllAddresses(true); @@ -119,7 +122,7 @@ public class StreamingLocalTimelineService extends IntentService { e.printStackTrace(); } } - AsyncHttpClient.getDefaultInstance().websocket("wss://" + accountStream.getInstance() + "/api/v1/streaming/?stream=public:local&access_token="+ accountStream.getToken(),"wss", new AsyncHttpClient.WebSocketConnectCallback() { + AsyncHttpClient.getDefaultInstance().websocket("wss://" + accountStream.getInstance() + "/api/v1/streaming/?stream=public:local&access_token=" + accountStream.getToken(), "wss", new AsyncHttpClient.WebSocketConnectCallback() { @Override public void onCompleted(Exception ex, WebSocket webSocket) { if (ex != null) { @@ -135,7 +138,8 @@ public class StreamingLocalTimelineService extends IntentService { try { JSONObject eventJson = new JSONObject(s); onRetrieveStreaming(finalAccountStream, eventJson); - } catch (JSONException ignored) {} + } catch (JSONException ignored) { + } } }); } @@ -144,17 +148,17 @@ public class StreamingLocalTimelineService extends IntentService { } public void onRetrieveStreaming(Account account, JSONObject response) { - if( response == null ) + if (response == null) return; - Status status ; + Status status; Bundle b = new Bundle(); try { - if( response.get("event").toString().equals("update")){ + if (response.get("event").toString().equals("update")) { status = API.parseStatuses(getApplicationContext(), new JSONObject(response.get("payload").toString())); status.setNew(true); b.putParcelable("data", status); - if( account != null) - b.putString("userIdService",account.getId()); + if (account != null) + b.putString("userIdService", account.getId()); Intent intentBC = new Intent(Helper.RECEIVE_LOCAL_DATA); intentBC.putExtras(b); LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intentBC); diff --git a/app/src/main/java/app/fedilab/android/sqlite/AccountDAO.java b/app/src/main/java/app/fedilab/android/sqlite/AccountDAO.java index 3f75987f2..c936a923d 100644 --- a/app/src/main/java/app/fedilab/android/sqlite/AccountDAO.java +++ b/app/src/main/java/app/fedilab/android/sqlite/AccountDAO.java @@ -46,49 +46,49 @@ public class AccountDAO { /** * Insert an Account in database + * * @param account Account * @return boolean */ - public boolean insertAccount(Account account) - { + public boolean insertAccount(Account account) { ContentValues values = new ContentValues(); - if( account.getCreated_at() == null) + if (account.getCreated_at() == null) account.setCreated_at(new Date()); - if( account.getNote() == null) + if (account.getNote() == null) account.setNote(""); values.put(Sqlite.COL_USER_ID, account.getId()); values.put(Sqlite.COL_USERNAME, account.getUsername()); values.put(Sqlite.COL_ACCT, account.getAcct()); values.put(Sqlite.COL_DISPLAYED_NAME, account.getDisplay_name()); - values.put(Sqlite.COL_LOCKED,account.isLocked()); - values.put(Sqlite.COL_FOLLOWERS_COUNT,account.getFollowers_count()); - values.put(Sqlite.COL_FOLLOWING_COUNT,account.getFollowing_count()); - values.put(Sqlite.COL_STATUSES_COUNT,account.getStatuses_count()); - values.put(Sqlite.COL_NOTE,account.getNote()); - values.put(Sqlite.COL_URL,account.getUrl()); - values.put(Sqlite.COL_AVATAR,account.getAvatar()); - values.put(Sqlite.COL_AVATAR_STATIC,account.getAvatar_static()); - values.put(Sqlite.COL_HEADER,account.getHeader()); - values.put(Sqlite.COL_HEADER_STATIC,account.getHeader_static()); + values.put(Sqlite.COL_LOCKED, account.isLocked()); + values.put(Sqlite.COL_FOLLOWERS_COUNT, account.getFollowers_count()); + values.put(Sqlite.COL_FOLLOWING_COUNT, account.getFollowing_count()); + values.put(Sqlite.COL_STATUSES_COUNT, account.getStatuses_count()); + values.put(Sqlite.COL_NOTE, account.getNote()); + values.put(Sqlite.COL_URL, account.getUrl()); + values.put(Sqlite.COL_AVATAR, account.getAvatar()); + values.put(Sqlite.COL_AVATAR_STATIC, account.getAvatar_static()); + values.put(Sqlite.COL_HEADER, account.getHeader()); + values.put(Sqlite.COL_HEADER_STATIC, account.getHeader_static()); values.put(Sqlite.COL_CREATED_AT, Helper.dateToString(account.getCreated_at())); values.put(Sqlite.COL_INSTANCE, account.getInstance()); values.put(Sqlite.COL_EMOJIS, Helper.emojisToStringStorage(account.getEmojis())); values.put(Sqlite.COL_SOCIAL, account.getSocial()); - if( account.getClient_id() != null && account.getClient_secret() != null && account.getRefresh_token() != null) { + if (account.getClient_id() != null && account.getClient_secret() != null && account.getRefresh_token() != null) { values.put(Sqlite.COL_CLIENT_ID, account.getClient_id()); values.put(Sqlite.COL_CLIENT_SECRET, account.getClient_secret()); values.put(Sqlite.COL_REFRESH_TOKEN, account.getRefresh_token()); } - if( account.getToken() != null) + if (account.getToken() != null) values.put(Sqlite.COL_OAUTHTOKEN, account.getToken()); values.put(Sqlite.COL_SENSITIVE, account.isSensitive()); values.put(Sqlite.COL_PRIVACY, account.getPrivacy()); //Inserts account - try{ + try { db.insertOrThrow(Sqlite.TABLE_USER_ACCOUNT, null, values); - }catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); return false; } @@ -97,37 +97,37 @@ public class AccountDAO { /** * Update an Account in database + * * @param account Account * @return boolean */ - public int updateAccount(Account account) - { + public int updateAccount(Account account) { ContentValues values = new ContentValues(); - if( account.getNote() == null) + if (account.getNote() == null) account.setNote(""); - if( account.getCreated_at() == null) + if (account.getCreated_at() == null) account.setCreated_at(new Date()); values.put(Sqlite.COL_ACCT, account.getAcct()); values.put(Sqlite.COL_DISPLAYED_NAME, account.getDisplay_name()); - values.put(Sqlite.COL_LOCKED,account.isLocked()); - values.put(Sqlite.COL_FOLLOWERS_COUNT,account.getFollowers_count()); - values.put(Sqlite.COL_FOLLOWING_COUNT,account.getFollowing_count()); - values.put(Sqlite.COL_STATUSES_COUNT,account.getStatuses_count()); - values.put(Sqlite.COL_NOTE,account.getNote()); - values.put(Sqlite.COL_URL,account.getUrl()); - values.put(Sqlite.COL_AVATAR,account.getAvatar()); - values.put(Sqlite.COL_AVATAR_STATIC,account.getAvatar_static()); - values.put(Sqlite.COL_HEADER,account.getHeader()); - values.put(Sqlite.COL_HEADER_STATIC,account.getHeader_static()); + values.put(Sqlite.COL_LOCKED, account.isLocked()); + values.put(Sqlite.COL_FOLLOWERS_COUNT, account.getFollowers_count()); + values.put(Sqlite.COL_FOLLOWING_COUNT, account.getFollowing_count()); + values.put(Sqlite.COL_STATUSES_COUNT, account.getStatuses_count()); + values.put(Sqlite.COL_NOTE, account.getNote()); + values.put(Sqlite.COL_URL, account.getUrl()); + values.put(Sqlite.COL_AVATAR, account.getAvatar()); + values.put(Sqlite.COL_AVATAR_STATIC, account.getAvatar_static()); + values.put(Sqlite.COL_HEADER, account.getHeader()); + values.put(Sqlite.COL_HEADER_STATIC, account.getHeader_static()); values.put(Sqlite.COL_CREATED_AT, Helper.dateToString(account.getCreated_at())); values.put(Sqlite.COL_EMOJIS, Helper.emojisToStringStorage(account.getEmojis())); values.put(Sqlite.COL_SOCIAL, account.getSocial()); - if( account.getClient_id() != null && account.getClient_secret() != null && account.getRefresh_token() != null) { + if (account.getClient_id() != null && account.getClient_secret() != null && account.getRefresh_token() != null) { values.put(Sqlite.COL_CLIENT_ID, account.getClient_id()); values.put(Sqlite.COL_CLIENT_SECRET, account.getClient_secret()); values.put(Sqlite.COL_REFRESH_TOKEN, account.getRefresh_token()); } - if( account.getToken() != null) + if (account.getToken() != null) values.put(Sqlite.COL_OAUTHTOKEN, account.getToken()); return db.update(Sqlite.TABLE_USER_ACCOUNT, values, Sqlite.COL_USER_ID + " = ? AND " + Sqlite.COL_INSTANCE + " =?", @@ -137,37 +137,37 @@ public class AccountDAO { /** * Update an Account in database + * * @param account Account * @return boolean */ - public int updateAccountCredential(Account account) - { + public int updateAccountCredential(Account account) { ContentValues values = new ContentValues(); - if( account.getNote() == null) + if (account.getNote() == null) account.setNote(""); - if( account.getCreated_at() == null) + if (account.getCreated_at() == null) account.setCreated_at(new Date()); values.put(Sqlite.COL_ACCT, account.getAcct()); values.put(Sqlite.COL_DISPLAYED_NAME, account.getDisplay_name()); - values.put(Sqlite.COL_LOCKED,account.isLocked()); - values.put(Sqlite.COL_FOLLOWERS_COUNT,account.getFollowers_count()); - values.put(Sqlite.COL_FOLLOWING_COUNT,account.getFollowing_count()); - values.put(Sqlite.COL_STATUSES_COUNT,account.getStatuses_count()); - values.put(Sqlite.COL_NOTE,account.getNote()); - values.put(Sqlite.COL_URL,account.getUrl()); - values.put(Sqlite.COL_AVATAR,account.getAvatar()); - values.put(Sqlite.COL_AVATAR_STATIC,account.getAvatar_static()); - values.put(Sqlite.COL_HEADER,account.getHeader()); - values.put(Sqlite.COL_HEADER_STATIC,account.getHeader_static()); + values.put(Sqlite.COL_LOCKED, account.isLocked()); + values.put(Sqlite.COL_FOLLOWERS_COUNT, account.getFollowers_count()); + values.put(Sqlite.COL_FOLLOWING_COUNT, account.getFollowing_count()); + values.put(Sqlite.COL_STATUSES_COUNT, account.getStatuses_count()); + values.put(Sqlite.COL_NOTE, account.getNote()); + values.put(Sqlite.COL_URL, account.getUrl()); + values.put(Sqlite.COL_AVATAR, account.getAvatar()); + values.put(Sqlite.COL_AVATAR_STATIC, account.getAvatar_static()); + values.put(Sqlite.COL_HEADER, account.getHeader()); + values.put(Sqlite.COL_HEADER_STATIC, account.getHeader_static()); values.put(Sqlite.COL_CREATED_AT, Helper.dateToString(account.getCreated_at())); values.put(Sqlite.COL_EMOJIS, Helper.emojisToStringStorage(account.getEmojis())); values.put(Sqlite.COL_SOCIAL, account.getSocial()); - if( account.getClient_id() != null && account.getClient_secret() != null && account.getRefresh_token() != null) { + if (account.getClient_id() != null && account.getClient_secret() != null && account.getRefresh_token() != null) { values.put(Sqlite.COL_CLIENT_ID, account.getClient_id()); values.put(Sqlite.COL_CLIENT_SECRET, account.getClient_secret()); values.put(Sqlite.COL_REFRESH_TOKEN, account.getRefresh_token()); } - if( account.getToken() != null) + if (account.getToken() != null) values.put(Sqlite.COL_OAUTHTOKEN, account.getToken()); values.put(Sqlite.COL_SENSITIVE, account.isSensitive()); values.put(Sqlite.COL_PRIVACY, account.getPrivacy()); @@ -177,17 +177,18 @@ public class AccountDAO { } - public int removeUser(Account account){ - return db.delete(Sqlite.TABLE_USER_ACCOUNT, Sqlite.COL_USER_ID + " = '" +account.getId() + - "' AND " + Sqlite.COL_INSTANCE + " = '" + account.getInstance()+ "'", null); + public int removeUser(Account account) { + return db.delete(Sqlite.TABLE_USER_ACCOUNT, Sqlite.COL_USER_ID + " = '" + account.getId() + + "' AND " + Sqlite.COL_INSTANCE + " = '" + account.getInstance() + "'", null); } /** * Returns last used account + * * @return Account */ - public Account getLastUsedAccount(){ + public Account getLastUsedAccount() { try { Cursor c = db.query(Sqlite.TABLE_USER_ACCOUNT, null, Sqlite.COL_OAUTHTOKEN + " != 'null'", null, null, null, Sqlite.COL_UPDATED_AT + " DESC", "1"); @@ -199,11 +200,12 @@ public class AccountDAO { /** * Returns an Account by its id and acct - * @param accountId String + * + * @param accountId String * @param accountAcct String * @return Account */ - public Account getAccountByIDAcct(String accountId, String accountAcct){ + public Account getAccountByIDAcct(String accountId, String accountAcct) { try { Cursor c = db.query(Sqlite.TABLE_USER_ACCOUNT, null, Sqlite.COL_USER_ID + " = '" + accountId + "' AND " + Sqlite.COL_ACCT + " = '" + accountAcct + "'", null, null, null, null, "1"); return cursorToUser(c); @@ -213,12 +215,12 @@ public class AccountDAO { } - /** * Returns all Account in db + * * @return Account List */ - public List getAllAccount(){ + public List getAllAccount() { try { Cursor c = db.query(Sqlite.TABLE_USER_ACCOUNT, null, null, null, null, null, Sqlite.COL_INSTANCE + " ASC", null); @@ -230,12 +232,13 @@ public class AccountDAO { /** * Returns all Account in db + * * @return Account List */ - public List getAllAccountActivated(){ + public List getAllAccountActivated() { try { - Cursor c = db.query(Sqlite.TABLE_USER_ACCOUNT, null, Sqlite.COL_OAUTHTOKEN + " != 'null'", null, null, null, Sqlite.COL_INSTANCE + " ASC", null); + Cursor c = db.query(Sqlite.TABLE_USER_ACCOUNT, null, Sqlite.COL_OAUTHTOKEN + " != 'null'", null, null, null, Sqlite.COL_INSTANCE + " ASC", null); return cursorToListUser(c); } catch (Exception e) { return null; @@ -244,9 +247,10 @@ public class AccountDAO { /** * Returns all Account in db + * * @return Account List */ - public List getAllAccountCrossAction(){ + public List getAllAccountCrossAction() { try { Cursor c = db.query(Sqlite.TABLE_USER_ACCOUNT, null, Sqlite.COL_SOCIAL + " != 'PEERTUBE' AND " + Sqlite.COL_OAUTHTOKEN + " != 'null'", null, null, null, Sqlite.COL_INSTANCE + " ASC", null); @@ -259,10 +263,11 @@ public class AccountDAO { /** * Returns an Account by token + * * @param token String * @return Account */ - public Account getAccountByToken(String token){ + public Account getAccountByToken(String token) { try { Cursor c = db.query(Sqlite.TABLE_USER_ACCOUNT, null, Sqlite.COL_OAUTHTOKEN + " = \"" + token + "\"", null, null, null, null, "1"); @@ -271,13 +276,15 @@ public class AccountDAO { return null; } } + /** * Returns an Account by token - * @param userId String + * + * @param userId String * @param instance String * @return Account */ - public Account getUniqAccount(String userId, String instance){ + public Account getUniqAccount(String userId, String instance) { try { Cursor c = db.query(Sqlite.TABLE_USER_ACCOUNT, null, Sqlite.COL_USER_ID + " = \"" + userId + "\" AND " + Sqlite.COL_INSTANCE + " = \"" + instance + "\"", null, null, null, null, "1"); @@ -290,13 +297,13 @@ public class AccountDAO { /** * Test if the current user is already stored in data base + * * @param account Account * @return boolean */ - public boolean userExist(Account account) - { - Cursor mCount= db.rawQuery("select count(*) from " + Sqlite.TABLE_USER_ACCOUNT - + " where " + Sqlite.COL_ACCT + " = '" + account.getAcct() + "' AND " + Sqlite.COL_INSTANCE + " = '" + account.getInstance()+ "'", null); + public boolean userExist(Account account) { + Cursor mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_USER_ACCOUNT + + " where " + Sqlite.COL_ACCT + " = '" + account.getAcct() + "' AND " + Sqlite.COL_INSTANCE + " = '" + account.getInstance() + "'", null); mCount.moveToFirst(); int count = mCount.getInt(0); mCount.close(); @@ -309,7 +316,7 @@ public class AccountDAO { * @param c Cursor * @return Account */ - private Account cursorToUser(Cursor c){ + private Account cursorToUser(Cursor c) { //No element found if (c.getCount() == 0) { c.close(); @@ -339,7 +346,7 @@ public class AccountDAO { account.setInstance(c.getString(c.getColumnIndex(Sqlite.COL_INSTANCE))); account.setEmojis(Helper.restoreEmojisFromString(c.getString(c.getColumnIndex(Sqlite.COL_EMOJIS)))); account.setToken(c.getString(c.getColumnIndex(Sqlite.COL_OAUTHTOKEN))); - account.setSocial(c.getString(c.getColumnIndex(Sqlite.COL_SOCIAL))!=null?c.getString(c.getColumnIndex(Sqlite.COL_SOCIAL)):"MASTODON"); + account.setSocial(c.getString(c.getColumnIndex(Sqlite.COL_SOCIAL)) != null ? c.getString(c.getColumnIndex(Sqlite.COL_SOCIAL)) : "MASTODON"); account.setClient_id(c.getString(c.getColumnIndex(Sqlite.COL_CLIENT_ID))); account.setClient_secret(c.getString(c.getColumnIndex(Sqlite.COL_CLIENT_SECRET))); account.setRefresh_token(c.getString(c.getColumnIndex(Sqlite.COL_REFRESH_TOKEN))); @@ -357,14 +364,14 @@ public class AccountDAO { * @param c Cursor * @return List */ - private List cursorToListUser(Cursor c){ + private List cursorToListUser(Cursor c) { //No element found if (c.getCount() == 0) { c.close(); return null; } List accounts = new ArrayList<>(); - while (c.moveToNext() ) { + while (c.moveToNext()) { //New user Account account = new Account(); @@ -386,7 +393,7 @@ public class AccountDAO { account.setCreated_at(Helper.stringToDate(context, c.getString(c.getColumnIndex(Sqlite.COL_CREATED_AT)))); account.setInstance(c.getString(c.getColumnIndex(Sqlite.COL_INSTANCE))); account.setToken(c.getString(c.getColumnIndex(Sqlite.COL_OAUTHTOKEN))); - account.setSocial(c.getString(c.getColumnIndex(Sqlite.COL_SOCIAL))!=null?c.getString(c.getColumnIndex(Sqlite.COL_SOCIAL)):"MASTODON"); + account.setSocial(c.getString(c.getColumnIndex(Sqlite.COL_SOCIAL)) != null ? c.getString(c.getColumnIndex(Sqlite.COL_SOCIAL)) : "MASTODON"); account.setClient_id(c.getString(c.getColumnIndex(Sqlite.COL_CLIENT_ID))); account.setClient_secret(c.getString(c.getColumnIndex(Sqlite.COL_CLIENT_SECRET))); account.setRefresh_token(c.getString(c.getColumnIndex(Sqlite.COL_REFRESH_TOKEN))); diff --git a/app/src/main/java/app/fedilab/android/sqlite/BoostScheduleDAO.java b/app/src/main/java/app/fedilab/android/sqlite/BoostScheduleDAO.java index 90bc99f0c..bfbcbf8fa 100644 --- a/app/src/main/java/app/fedilab/android/sqlite/BoostScheduleDAO.java +++ b/app/src/main/java/app/fedilab/android/sqlite/BoostScheduleDAO.java @@ -50,18 +50,19 @@ public class BoostScheduleDAO { /** * Insert a status in database + * * @param status Status - * @param jobId int + * @param jobId int * @return boolean */ - public long insert(Status status, int jobId, Date date_scheduled ) { + public long insert(Status status, int jobId, Date date_scheduled) { ContentValues values = new ContentValues(); String serializedStatus = Helper.statusToStringStorage(status); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); - if( userId == null || instance == null) + if (userId == null || instance == null) return -1; values.put(Sqlite.COL_STATUS_SERIALIZED, serializedStatus); values.put(Sqlite.COL_INSTANCE, instance); @@ -71,18 +72,19 @@ public class BoostScheduleDAO { values.put(Sqlite.COL_DATE_SCHEDULED, Helper.dateToString(date_scheduled)); //Inserts stored status long last_id; - try{ + try { last_id = db.insert(Sqlite.TABLE_BOOST_SCHEDULE, null, values); - }catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); - last_id = -1; + last_id = -1; } return last_id; } /** * Update a Boost schedule in database - * @param id long + * + * @param id long * @param jobId int * @return int */ @@ -97,6 +99,7 @@ public class BoostScheduleDAO { /** * Update scheduled date for a Status in database + * * @param scheduled_date Date * @return boolean */ @@ -110,7 +113,8 @@ public class BoostScheduleDAO { /** * Update date when task is done for a scheduled Status in database - * @param jobid int + * + * @param jobid int * @param date_sent Date * @return boolean */ @@ -129,12 +133,12 @@ public class BoostScheduleDAO { * Remove stored status by id * @return int */ - public int remove(long id){ - return db.delete(Sqlite.TABLE_BOOST_SCHEDULE, Sqlite.COL_ID + " = \"" + id + "\"", null); + public int remove(long id) { + return db.delete(Sqlite.TABLE_BOOST_SCHEDULE, Sqlite.COL_ID + " = \"" + id + "\"", null); } - public int removeAllSent(){ - return db.delete(Sqlite.TABLE_BOOST_SCHEDULE, Sqlite.COL_IS_SCHEDULED + " != 0 AND " + Sqlite.COL_SENT + " = 1", null); + public int removeAllSent() { + return db.delete(Sqlite.TABLE_BOOST_SCHEDULE, Sqlite.COL_IS_SCHEDULED + " != 0 AND " + Sqlite.COL_SENT + " = 1", null); } //------- GETTERS ------- @@ -142,30 +146,33 @@ public class BoostScheduleDAO { /** * Returns all scheduled Statuses in db + * * @return stored status List */ - public List getAllScheduled(){ + public List getAllScheduled() { try { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); - Cursor c = db.query(Sqlite.TABLE_BOOST_SCHEDULE, null, Sqlite.COL_USER_ID + " = '" + userId+ "' AND " + Sqlite.COL_INSTANCE + " = '" + instance+ "' AND " + Sqlite.COL_IS_SCHEDULED + " != 0 AND " + Sqlite.COL_SENT + " = 0", null, null, null, Sqlite.COL_DATE_SCHEDULED + " ASC", null); + Cursor c = db.query(Sqlite.TABLE_BOOST_SCHEDULE, null, Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_IS_SCHEDULED + " != 0 AND " + Sqlite.COL_SENT + " = 0", null, null, null, Sqlite.COL_DATE_SCHEDULED + " ASC", null); return cursorToListStatuses(c); } catch (Exception e) { e.printStackTrace(); return null; } } + /** * Returns all not sent Statuses in db + * * @return stored status List */ - public List getAllNotSent(){ + public List getAllNotSent() { try { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); - Cursor c = db.query(Sqlite.TABLE_BOOST_SCHEDULE, null, Sqlite.COL_USER_ID + " = '" + userId+ "' AND " + Sqlite.COL_INSTANCE + " = '" + instance+ "' AND " +Sqlite.COL_IS_SCHEDULED + " != 0 AND " + Sqlite.COL_SENT + " = 0", null, null, null, Sqlite.COL_DATE_SCHEDULED + " DESC", null); + Cursor c = db.query(Sqlite.TABLE_BOOST_SCHEDULE, null, Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_IS_SCHEDULED + " != 0 AND " + Sqlite.COL_SENT + " = 0", null, null, null, Sqlite.COL_DATE_SCHEDULED + " DESC", null); return cursorToListStatuses(c); } catch (Exception e) { return null; @@ -174,14 +181,15 @@ public class BoostScheduleDAO { /** * Returns all sent Statuses in db + * * @return stored status List */ - public List getAllSent(){ + public List getAllSent() { try { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); - Cursor c = db.query(Sqlite.TABLE_BOOST_SCHEDULE, null, Sqlite.COL_USER_ID + " = '" + userId+ "' AND " + Sqlite.COL_INSTANCE + " = '" + instance+ "' AND " +Sqlite.COL_IS_SCHEDULED + " != 0 AND " + Sqlite.COL_SENT + " = 1", null, null, null, Sqlite.COL_DATE_SCHEDULED + " DESC", null); + Cursor c = db.query(Sqlite.TABLE_BOOST_SCHEDULE, null, Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_IS_SCHEDULED + " != 0 AND " + Sqlite.COL_SENT + " = 1", null, null, null, Sqlite.COL_DATE_SCHEDULED + " DESC", null); return cursorToListStatuses(c); } catch (Exception e) { return null; @@ -190,9 +198,10 @@ public class BoostScheduleDAO { /** * Returns a stored status by id in db + * * @return stored status StoredStatus */ - public StoredStatus getStatus(long id){ + public StoredStatus getStatus(long id) { try { Cursor c = db.query(Sqlite.TABLE_BOOST_SCHEDULE, null, Sqlite.COL_ID + " = '" + id + "'", null, null, null, null, null); return cursorToStoredStatus(c); @@ -204,9 +213,10 @@ public class BoostScheduleDAO { /** * Returns a stored status by id of job in db + * * @return stored status StoredStatus */ - public StoredStatus getStatusScheduled(int jobid){ + public StoredStatus getStatusScheduled(int jobid) { try { Cursor c = db.query(Sqlite.TABLE_BOOST_SCHEDULE, null, Sqlite.COL_IS_SCHEDULED + " = '" + jobid + "'", null, null, null, null, null); return cursorToStoredStatus(c); @@ -220,7 +230,7 @@ public class BoostScheduleDAO { * @param c Cursor * @return StoredStatus */ - private StoredStatus cursorToStoredStatus(Cursor c){ + private StoredStatus cursorToStoredStatus(Cursor c) { //No element found if (c.getCount() == 0) { c.close(); @@ -232,7 +242,7 @@ public class BoostScheduleDAO { StoredStatus storedStatus = new StoredStatus(); storedStatus.setId(c.getInt(c.getColumnIndex(Sqlite.COL_ID))); Status status = Helper.restoreStatusFromString(c.getString(c.getColumnIndex(Sqlite.COL_STATUS_SERIALIZED))); - if( status == null){ + if (status == null) { remove(c.getInt(c.getColumnIndex(Sqlite.COL_ID))); return null; } @@ -255,26 +265,26 @@ public class BoostScheduleDAO { * @param c Cursor * @return List */ - private List cursorToListStatuses(Cursor c){ + private List cursorToListStatuses(Cursor c) { //No element found if (c.getCount() == 0) { c.close(); return null; } List storedStatuses = new ArrayList<>(); - while (c.moveToNext() ) { + while (c.moveToNext()) { //Restore the status StoredStatus storedStatus = new StoredStatus(); storedStatus.setId(c.getInt(c.getColumnIndex(Sqlite.COL_ID))); Status status = Helper.restoreStatusFromString(c.getString(c.getColumnIndex(Sqlite.COL_STATUS_SERIALIZED))); - if( status == null){ + if (status == null) { remove(c.getInt(c.getColumnIndex(Sqlite.COL_ID))); continue; } storedStatus.setStatus(status); storedStatus.setStatusReply(null); storedStatus.setSent(c.getInt(c.getColumnIndex(Sqlite.COL_SENT)) == 1); - storedStatus.setJobId(c.getInt(c.getColumnIndex(Sqlite.COL_IS_SCHEDULED)) ); + storedStatus.setJobId(c.getInt(c.getColumnIndex(Sqlite.COL_IS_SCHEDULED))); storedStatus.setScheduled_date(Helper.stringToDate(context, c.getString(c.getColumnIndex(Sqlite.COL_DATE_SCHEDULED)))); storedStatus.setSent_date(Helper.stringToDate(context, c.getString(c.getColumnIndex(Sqlite.COL_DATE_SENT)))); storedStatus.setUserId(c.getString(c.getColumnIndex(Sqlite.COL_USER_ID))); diff --git a/app/src/main/java/app/fedilab/android/sqlite/CustomEmojiDAO.java b/app/src/main/java/app/fedilab/android/sqlite/CustomEmojiDAO.java index ecaf2f445..de6a24f38 100644 --- a/app/src/main/java/app/fedilab/android/sqlite/CustomEmojiDAO.java +++ b/app/src/main/java/app/fedilab/android/sqlite/CustomEmojiDAO.java @@ -18,6 +18,7 @@ import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; + import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -47,6 +48,7 @@ public class CustomEmojiDAO { /** * Insert an emoji in database + * * @param emoji Emoji */ public void insertEmoji(Emojis emoji) { @@ -60,18 +62,20 @@ public class CustomEmojiDAO { values.put(Sqlite.COL_URL_STATIC, emoji.getStatic_url()); values.put(Sqlite.COL_DATE_CREATION, Helper.dateToString(new Date())); //Inserts emoji - try{ + try { db.insert(Sqlite.TABLE_CUSTOM_EMOJI, null, values); - }catch (Exception ignored) {} + } catch (Exception ignored) { + } } //------- UPDATES ------- /** * Update an emoji in database + * * @param emoji Emojis */ - public void updateEmoji(Emojis emoji ) { + public void updateEmoji(Emojis emoji) { ContentValues values = new ContentValues(); String instance = Helper.getLiveInstance(context); values.put(Sqlite.COL_URL, emoji.getUrl()); @@ -88,15 +92,15 @@ public class CustomEmojiDAO { * Remove emoji by id * @return int */ - public int remove(Emojis emoji){ + public int remove(Emojis emoji) { String instance = Helper.getLiveInstance(context); - return db.delete(Sqlite.TABLE_CUSTOM_EMOJI, Sqlite.COL_SHORTCODE + " = \"" + emoji.getShortcode() + "\" AND " + Sqlite.COL_INSTANCE + " = \"" + instance+ "\"", null); + return db.delete(Sqlite.TABLE_CUSTOM_EMOJI, Sqlite.COL_SHORTCODE + " = \"" + emoji.getShortcode() + "\" AND " + Sqlite.COL_INSTANCE + " = \"" + instance + "\"", null); } /*** * Remove emoji by id */ - public void removeAll(){ + public void removeAll() { String instance = Helper.getLiveInstance(context); db.delete(Sqlite.TABLE_CUSTOM_EMOJI, Sqlite.COL_INSTANCE + " = \"" + instance + "\"", null); } @@ -105,12 +109,13 @@ public class CustomEmojiDAO { /** * Returns all emojis in db for an instance + * * @return emojis List */ - public List getAllEmojis(){ + public List getAllEmojis() { String instance = Helper.getLiveInstance(context); try { - Cursor c = db.query(Sqlite.TABLE_CUSTOM_EMOJI, null, Sqlite.COL_INSTANCE + " = '" + instance+ "'", null, Sqlite.COL_SHORTCODE , null, Sqlite.COL_SHORTCODE + " ASC", null); + Cursor c = db.query(Sqlite.TABLE_CUSTOM_EMOJI, null, Sqlite.COL_INSTANCE + " = '" + instance + "'", null, Sqlite.COL_SHORTCODE, null, Sqlite.COL_SHORTCODE + " ASC", null); return cursorToListEmojis(c); } catch (Exception e) { return null; @@ -119,11 +124,12 @@ public class CustomEmojiDAO { /** * Returns all emojis in db for an instance + * * @return emojis List */ - public List getAllEmojis(String instance){ + public List getAllEmojis(String instance) { try { - Cursor c = db.query(Sqlite.TABLE_CUSTOM_EMOJI, null, Sqlite.COL_INSTANCE + " = '" + instance+ "'", null, Sqlite.COL_SHORTCODE , null, Sqlite.COL_SHORTCODE + " ASC", null); + Cursor c = db.query(Sqlite.TABLE_CUSTOM_EMOJI, null, Sqlite.COL_INSTANCE + " = '" + instance + "'", null, Sqlite.COL_SHORTCODE, null, Sqlite.COL_SHORTCODE + " ASC", null); return cursorToListEmojis(c); } catch (Exception e) { return null; @@ -132,12 +138,13 @@ public class CustomEmojiDAO { /** * Returns an emoji by its shortcode in db + * * @return emoji Emojis */ - public Emojis getEmoji(String shortCode){ + public Emojis getEmoji(String shortCode) { try { String instance = Helper.getLiveInstance(context); - Cursor c = db.query(Sqlite.TABLE_CUSTOM_EMOJI, null, Sqlite.COL_SHORTCODE + " = \"" + shortCode + "\" AND " + Sqlite.COL_INSTANCE + " = \"" + instance+ "\"", null, null, null, null, null); + Cursor c = db.query(Sqlite.TABLE_CUSTOM_EMOJI, null, Sqlite.COL_SHORTCODE + " = \"" + shortCode + "\" AND " + Sqlite.COL_INSTANCE + " = \"" + instance + "\"", null, null, null, null, null); return cursorToEmoji(c); } catch (Exception e) { return null; @@ -147,12 +154,13 @@ public class CustomEmojiDAO { /** * Returns an emoji by its shortcode in db + * * @return emoji Emojis */ - public List getEmojiStartingBy(String shortCode){ + public List getEmojiStartingBy(String shortCode) { try { String instance = Helper.getLiveInstance(context); - Cursor c = db.query(Sqlite.TABLE_CUSTOM_EMOJI, null, Sqlite.COL_SHORTCODE + " LIKE \"%" + shortCode + "%\" AND " + Sqlite.COL_INSTANCE + " = \"" + instance+ "\"", null, Sqlite.COL_SHORTCODE , null, null, null); + Cursor c = db.query(Sqlite.TABLE_CUSTOM_EMOJI, null, Sqlite.COL_SHORTCODE + " LIKE \"%" + shortCode + "%\" AND " + Sqlite.COL_INSTANCE + " = \"" + instance + "\"", null, Sqlite.COL_SHORTCODE, null, null, null); return cursorToListEmojis(c); } catch (Exception e) { return null; @@ -164,7 +172,7 @@ public class CustomEmojiDAO { * @param c Cursor * @return Emojis */ - private Emojis cursorToEmoji(Cursor c){ + private Emojis cursorToEmoji(Cursor c) { //No element found if (c.getCount() == 0) { c.close(); @@ -188,14 +196,14 @@ public class CustomEmojiDAO { * @param c Cursor * @return List */ - private List cursorToListEmojis(Cursor c){ + private List cursorToListEmojis(Cursor c) { //No element found if (c.getCount() == 0) { c.close(); return null; } List emojis = new ArrayList<>(); - while (c.moveToNext() ) { + while (c.moveToNext()) { //Restore the emojis Emojis emoji = new Emojis(); emoji.setShortcode(c.getString(c.getColumnIndex(Sqlite.COL_SHORTCODE))); diff --git a/app/src/main/java/app/fedilab/android/sqlite/DomainBlockDAO.java b/app/src/main/java/app/fedilab/android/sqlite/DomainBlockDAO.java index 6a7e5a664..a723c0f24 100644 --- a/app/src/main/java/app/fedilab/android/sqlite/DomainBlockDAO.java +++ b/app/src/main/java/app/fedilab/android/sqlite/DomainBlockDAO.java @@ -42,18 +42,21 @@ public class DomainBlockDAO { /** * Insert a domain in database + * * @param domain String */ private void insert(String domain) { ContentValues values = new ContentValues(); values.put(Sqlite.COL_DOMAIN, domain); - try{ + try { db.insert(Sqlite.TABLE_TRACKING_BLOCK, null, values); - }catch (Exception ignored) {} + } catch (Exception ignored) { + } } /** * Insert domains in database + * * @param domains List */ public void set(List domains) { @@ -63,26 +66,28 @@ public class DomainBlockDAO { } - public int getTotalCount(){ - Cursor mCount= db.rawQuery("SELECT Count(*) FROM " + Sqlite.TABLE_TRACKING_BLOCK, null); + public int getTotalCount() { + Cursor mCount = db.rawQuery("SELECT Count(*) FROM " + Sqlite.TABLE_TRACKING_BLOCK, null); mCount.moveToFirst(); int count = mCount.getInt(0); mCount.close(); return count; } + /*** * Remove all domains */ - private void removeAll(){ + private void removeAll() { db.delete(Sqlite.TABLE_TRACKING_BLOCK, null, null); } /** * Returns all domains in db + * * @return string domain List */ - public List getAll(){ + public List getAll() { try { Cursor c = db.query(Sqlite.TABLE_TRACKING_BLOCK, null, null, null, null, null, null, null); return cursorToDomain(c); @@ -92,20 +97,19 @@ public class DomainBlockDAO { } - /*** * Method to hydrate domain from database * @param c Cursor * @return List */ - private List cursorToDomain(Cursor c){ + private List cursorToDomain(Cursor c) { //No element found if (c.getCount() == 0) { c.close(); return null; } List domains = new ArrayList<>(); - while (c.moveToNext() ) { + while (c.moveToNext()) { domains.add(c.getString(c.getColumnIndex(Sqlite.COL_DOMAIN))); } //Close the cursor diff --git a/app/src/main/java/app/fedilab/android/sqlite/InstancesDAO.java b/app/src/main/java/app/fedilab/android/sqlite/InstancesDAO.java index 0b4651fdb..d81190e63 100644 --- a/app/src/main/java/app/fedilab/android/sqlite/InstancesDAO.java +++ b/app/src/main/java/app/fedilab/android/sqlite/InstancesDAO.java @@ -51,6 +51,7 @@ public class InstancesDAO { /** * Insert an instance name in database + * * @param instanceName String */ public void insertInstance(String instanceName, String id, String type) { @@ -60,9 +61,10 @@ public class InstancesDAO { values.put(Sqlite.COL_INSTANCE_TYPE, type); values.put(Sqlite.COL_DATE_CREATION, Helper.dateToString(new Date())); //Inserts search - try{ + try { db.insert(Sqlite.TABLE_INSTANCES, null, values); - }catch (Exception ignored) {} + } catch (Exception ignored) { + } } @@ -70,6 +72,7 @@ public class InstancesDAO { /** * update instance in database + * * @param remoteInstance RemoteInstance */ public void updateInstance(RemoteInstance remoteInstance) { @@ -78,12 +81,14 @@ public class InstancesDAO { values.put(Sqlite.COL_FILTERED_WITH, remoteInstance.getFilteredWith()); - if( tags != null && tags.size() > 0) { + if (tags != null && tags.size() > 0) { values.put(Sqlite.COL_TAGS, Helper.arrayToStringStorage(tags)); } - try{ - db.update(Sqlite.TABLE_INSTANCES, values, Sqlite.COL_INSTANCE + " = ? ", new String[]{String.valueOf(remoteInstance.getHost())}); - }catch (Exception ignored) {ignored.printStackTrace();} + try { + db.update(Sqlite.TABLE_INSTANCES, values, Sqlite.COL_INSTANCE + " = ? ", new String[]{String.valueOf(remoteInstance.getHost())}); + } catch (Exception ignored) { + ignored.printStackTrace(); + } } @@ -97,8 +102,8 @@ public class InstancesDAO { * Remove instance by its name * @return int */ - public int remove(String host){ - return db.delete(Sqlite.TABLE_INSTANCES, Sqlite.COL_INSTANCE + " = \"" + host + "\"", null); + public int remove(String host) { + return db.delete(Sqlite.TABLE_INSTANCES, Sqlite.COL_INSTANCE + " = \"" + host + "\"", null); } //------- REMOVE ------- @@ -107,7 +112,7 @@ public class InstancesDAO { * Remove instance by its name * @return int */ - public void cleanDoublon(){ + public void cleanDoublon() { db.delete(Sqlite.TABLE_INSTANCES, Sqlite.COL_ID + " NOT IN (" + " SELECT MIN(" + Sqlite.COL_ID + ")" + " FROM " + Sqlite.TABLE_INSTANCES + @@ -118,9 +123,10 @@ public class InstancesDAO { /** * Returns all instances in db for a user + * * @return instances List */ - public List getAllInstances(){ + public List getAllInstances() { try { Cursor c = db.query(Sqlite.TABLE_INSTANCES, null, null, null, null, null, Sqlite.COL_INSTANCE + " ASC", null); return cursorToListSearch(c); @@ -131,12 +137,12 @@ public class InstancesDAO { } - /** * Returns instance by its nale in db + * * @return instance List */ - public List getInstanceByName(String keyword){ + public List getInstanceByName(String keyword) { try { Cursor c = db.query(Sqlite.TABLE_INSTANCES, null, Sqlite.COL_INSTANCE + " = \"" + keyword + "\"", null, null, null, null, null); return cursorToListSearch(c); @@ -151,23 +157,24 @@ public class InstancesDAO { * @param c Cursor * @return List */ - private List cursorToListSearch(Cursor c){ + private List cursorToListSearch(Cursor c) { //No element found if (c.getCount() == 0) { c.close(); return null; } List remoteInstances = new ArrayList<>(); - while (c.moveToNext() ) { + while (c.moveToNext()) { RemoteInstance remoteInstance = new RemoteInstance(); remoteInstance.setDbID(c.getString(c.getColumnIndex(Sqlite.COL_ID))); remoteInstance.setId(c.getString(c.getColumnIndex(Sqlite.COL_USER_ID))); try { remoteInstance.setTags(Helper.restoreArrayFromString(c.getString(c.getColumnIndex(Sqlite.COL_TAGS)))); - }catch (Exception ignored){} + } catch (Exception ignored) { + } remoteInstance.setHost(c.getString(c.getColumnIndex(Sqlite.COL_INSTANCE))); remoteInstance.setFilteredWith(c.getString(c.getColumnIndex(Sqlite.COL_FILTERED_WITH))); - remoteInstance.setType(c.getString(c.getColumnIndex(Sqlite.COL_INSTANCE_TYPE)) == null?"MASTODON":c.getString(c.getColumnIndex(Sqlite.COL_INSTANCE_TYPE))); + remoteInstance.setType(c.getString(c.getColumnIndex(Sqlite.COL_INSTANCE_TYPE)) == null ? "MASTODON" : c.getString(c.getColumnIndex(Sqlite.COL_INSTANCE_TYPE))); remoteInstances.add(remoteInstance); } //Close the cursor diff --git a/app/src/main/java/app/fedilab/android/sqlite/MainMenuDAO.java b/app/src/main/java/app/fedilab/android/sqlite/MainMenuDAO.java index ce1bfbccc..d2921e84a 100644 --- a/app/src/main/java/app/fedilab/android/sqlite/MainMenuDAO.java +++ b/app/src/main/java/app/fedilab/android/sqlite/MainMenuDAO.java @@ -46,36 +46,39 @@ public class MainMenuDAO { /** * Insert a menu configuration name in database + * * @param mainMenuItem MainMenuItem - * @param userId String - * @param instance String + * @param userId String + * @param instance String */ public void insertMenu(MainMenuItem mainMenuItem, String userId, String instance) { ContentValues values = new ContentValues(); values.put(Sqlite.COL_INSTANCE, instance); values.put(Sqlite.COL_USER_ID, userId); - values.put(Sqlite.COL_NAV_NEWS, mainMenuItem.isNav_news()?1:0); - values.put(Sqlite.COL_NAV_LIST, mainMenuItem.isNav_list()?1:0); - values.put(Sqlite.COL_NAV_SCHEDULED, mainMenuItem.isNav_scheduled()?1:0); - values.put(Sqlite.COL_NAV_ARCHIVE, mainMenuItem.isNav_archive()?1:0); - values.put(Sqlite.COL_NAV_ARCHIVE_NOTIFICATIONS, mainMenuItem.isNav_archive_notifications()?1:0); - values.put(Sqlite.COL_NAV_PEERTUBE, mainMenuItem.isNav_peertube()?1:0); - values.put(Sqlite.COL_NAV_FILTERS, mainMenuItem.isNav_filters()?1:0); - values.put(Sqlite.COL_NAV_HOW_TO_FOLLOW, mainMenuItem.isNav_how_to_follow()?1:0); - values.put(Sqlite.COL_NAV_BLOCKED, mainMenuItem.isNav_blocked()?1:0); - values.put(Sqlite.COL_NAV_MUTED, mainMenuItem.isNav_muted()?1:0); - values.put(Sqlite.COL_NAV_BLOCKED_DOMAINS, mainMenuItem.isNav_blocked()?1:0); - values.put(Sqlite.COL_NAV_HOWTO, mainMenuItem.isNav_howto()?1:0); + values.put(Sqlite.COL_NAV_NEWS, mainMenuItem.isNav_news() ? 1 : 0); + values.put(Sqlite.COL_NAV_LIST, mainMenuItem.isNav_list() ? 1 : 0); + values.put(Sqlite.COL_NAV_SCHEDULED, mainMenuItem.isNav_scheduled() ? 1 : 0); + values.put(Sqlite.COL_NAV_ARCHIVE, mainMenuItem.isNav_archive() ? 1 : 0); + values.put(Sqlite.COL_NAV_ARCHIVE_NOTIFICATIONS, mainMenuItem.isNav_archive_notifications() ? 1 : 0); + values.put(Sqlite.COL_NAV_PEERTUBE, mainMenuItem.isNav_peertube() ? 1 : 0); + values.put(Sqlite.COL_NAV_FILTERS, mainMenuItem.isNav_filters() ? 1 : 0); + values.put(Sqlite.COL_NAV_HOW_TO_FOLLOW, mainMenuItem.isNav_how_to_follow() ? 1 : 0); + values.put(Sqlite.COL_NAV_BLOCKED, mainMenuItem.isNav_blocked() ? 1 : 0); + values.put(Sqlite.COL_NAV_MUTED, mainMenuItem.isNav_muted() ? 1 : 0); + values.put(Sqlite.COL_NAV_BLOCKED_DOMAINS, mainMenuItem.isNav_blocked() ? 1 : 0); + values.put(Sqlite.COL_NAV_HOWTO, mainMenuItem.isNav_howto() ? 1 : 0); //Inserts menu conf - try{ + try { db.insert(Sqlite.TABLE_MAIN_MENU_ITEMS, null, values); - }catch (Exception ignored) {} + } catch (Exception ignored) { + } } //------- INSERTIONS ------- /** * Insert a menu configuration name in database + * * @param mainMenuItem MainMenuItem */ public void insertMenu(MainMenuItem mainMenuItem) { @@ -85,22 +88,23 @@ public class MainMenuDAO { ContentValues values = new ContentValues(); values.put(Sqlite.COL_INSTANCE, instance); values.put(Sqlite.COL_USER_ID, userId); - values.put(Sqlite.COL_NAV_NEWS, mainMenuItem.isNav_news()?1:0); - values.put(Sqlite.COL_NAV_LIST, mainMenuItem.isNav_list()?1:0); - values.put(Sqlite.COL_NAV_SCHEDULED, mainMenuItem.isNav_scheduled()?1:0); - values.put(Sqlite.COL_NAV_ARCHIVE, mainMenuItem.isNav_archive()?1:0); - values.put(Sqlite.COL_NAV_ARCHIVE_NOTIFICATIONS, mainMenuItem.isNav_archive_notifications()?1:0); - values.put(Sqlite.COL_NAV_PEERTUBE, mainMenuItem.isNav_peertube()?1:0); - values.put(Sqlite.COL_NAV_FILTERS, mainMenuItem.isNav_filters()?1:0); - values.put(Sqlite.COL_NAV_HOW_TO_FOLLOW, mainMenuItem.isNav_how_to_follow()?1:0); - values.put(Sqlite.COL_NAV_BLOCKED, mainMenuItem.isNav_blocked()?1:0); - values.put(Sqlite.COL_NAV_MUTED, mainMenuItem.isNav_muted()?1:0); - values.put(Sqlite.COL_NAV_BLOCKED_DOMAINS, mainMenuItem.isNav_blocked()?1:0); - values.put(Sqlite.COL_NAV_HOWTO, mainMenuItem.isNav_howto()?1:0); + values.put(Sqlite.COL_NAV_NEWS, mainMenuItem.isNav_news() ? 1 : 0); + values.put(Sqlite.COL_NAV_LIST, mainMenuItem.isNav_list() ? 1 : 0); + values.put(Sqlite.COL_NAV_SCHEDULED, mainMenuItem.isNav_scheduled() ? 1 : 0); + values.put(Sqlite.COL_NAV_ARCHIVE, mainMenuItem.isNav_archive() ? 1 : 0); + values.put(Sqlite.COL_NAV_ARCHIVE_NOTIFICATIONS, mainMenuItem.isNav_archive_notifications() ? 1 : 0); + values.put(Sqlite.COL_NAV_PEERTUBE, mainMenuItem.isNav_peertube() ? 1 : 0); + values.put(Sqlite.COL_NAV_FILTERS, mainMenuItem.isNav_filters() ? 1 : 0); + values.put(Sqlite.COL_NAV_HOW_TO_FOLLOW, mainMenuItem.isNav_how_to_follow() ? 1 : 0); + values.put(Sqlite.COL_NAV_BLOCKED, mainMenuItem.isNav_blocked() ? 1 : 0); + values.put(Sqlite.COL_NAV_MUTED, mainMenuItem.isNav_muted() ? 1 : 0); + values.put(Sqlite.COL_NAV_BLOCKED_DOMAINS, mainMenuItem.isNav_blocked() ? 1 : 0); + values.put(Sqlite.COL_NAV_HOWTO, mainMenuItem.isNav_howto() ? 1 : 0); //Inserts menu conf - try{ + try { db.insert(Sqlite.TABLE_MAIN_MENU_ITEMS, null, values); - }catch (Exception ignored) {} + } catch (Exception ignored) { + } } @@ -109,33 +113,37 @@ public class MainMenuDAO { /** * update menu items in database + * * @param mainMenuItem MainMenuItem */ public void updateMenu(MainMenuItem mainMenuItem, String userId, String instance) { ContentValues values = new ContentValues(); values.put(Sqlite.COL_INSTANCE, instance); values.put(Sqlite.COL_USER_ID, userId); - values.put(Sqlite.COL_NAV_NEWS, mainMenuItem.isNav_news()?1:0); - values.put(Sqlite.COL_NAV_LIST, mainMenuItem.isNav_list()?1:0); - values.put(Sqlite.COL_NAV_SCHEDULED, mainMenuItem.isNav_scheduled()?1:0); - values.put(Sqlite.COL_NAV_ARCHIVE, mainMenuItem.isNav_archive()?1:0); - values.put(Sqlite.COL_NAV_ARCHIVE_NOTIFICATIONS, mainMenuItem.isNav_archive_notifications()?1:0); - values.put(Sqlite.COL_NAV_PEERTUBE, mainMenuItem.isNav_peertube()?1:0); - values.put(Sqlite.COL_NAV_FILTERS, mainMenuItem.isNav_filters()?1:0); - values.put(Sqlite.COL_NAV_HOW_TO_FOLLOW, mainMenuItem.isNav_how_to_follow()?1:0); - values.put(Sqlite.COL_NAV_BLOCKED, mainMenuItem.isNav_blocked()?1:0); - values.put(Sqlite.COL_NAV_MUTED, mainMenuItem.isNav_muted()?1:0); - values.put(Sqlite.COL_NAV_BLOCKED_DOMAINS, mainMenuItem.isNav_blocked()?1:0); - values.put(Sqlite.COL_NAV_HOWTO, mainMenuItem.isNav_howto()?1:0); - try{ - db.update(Sqlite.TABLE_MAIN_MENU_ITEMS, values, Sqlite.COL_USER_ID + " = ? AND " + Sqlite.COL_INSTANCE + " = ? " , + values.put(Sqlite.COL_NAV_NEWS, mainMenuItem.isNav_news() ? 1 : 0); + values.put(Sqlite.COL_NAV_LIST, mainMenuItem.isNav_list() ? 1 : 0); + values.put(Sqlite.COL_NAV_SCHEDULED, mainMenuItem.isNav_scheduled() ? 1 : 0); + values.put(Sqlite.COL_NAV_ARCHIVE, mainMenuItem.isNav_archive() ? 1 : 0); + values.put(Sqlite.COL_NAV_ARCHIVE_NOTIFICATIONS, mainMenuItem.isNav_archive_notifications() ? 1 : 0); + values.put(Sqlite.COL_NAV_PEERTUBE, mainMenuItem.isNav_peertube() ? 1 : 0); + values.put(Sqlite.COL_NAV_FILTERS, mainMenuItem.isNav_filters() ? 1 : 0); + values.put(Sqlite.COL_NAV_HOW_TO_FOLLOW, mainMenuItem.isNav_how_to_follow() ? 1 : 0); + values.put(Sqlite.COL_NAV_BLOCKED, mainMenuItem.isNav_blocked() ? 1 : 0); + values.put(Sqlite.COL_NAV_MUTED, mainMenuItem.isNav_muted() ? 1 : 0); + values.put(Sqlite.COL_NAV_BLOCKED_DOMAINS, mainMenuItem.isNav_blocked() ? 1 : 0); + values.put(Sqlite.COL_NAV_HOWTO, mainMenuItem.isNav_howto() ? 1 : 0); + try { + db.update(Sqlite.TABLE_MAIN_MENU_ITEMS, values, Sqlite.COL_USER_ID + " = ? AND " + Sqlite.COL_INSTANCE + " = ? ", new String[]{userId, instance}); - }catch (Exception ignored) {ignored.printStackTrace();} + } catch (Exception ignored) { + ignored.printStackTrace(); + } } /** * update menu items in database + * * @param mainMenuItem MainMenuItem */ public void updateMenu(MainMenuItem mainMenuItem) { @@ -146,39 +154,40 @@ public class MainMenuDAO { values.put(Sqlite.COL_INSTANCE, instance); values.put(Sqlite.COL_USER_ID, userId); - values.put(Sqlite.COL_NAV_NEWS, mainMenuItem.isNav_news()?1:0); - values.put(Sqlite.COL_NAV_LIST, mainMenuItem.isNav_list()?1:0); - values.put(Sqlite.COL_NAV_SCHEDULED, mainMenuItem.isNav_scheduled()?1:0); - values.put(Sqlite.COL_NAV_ARCHIVE, mainMenuItem.isNav_archive()?1:0); - values.put(Sqlite.COL_NAV_ARCHIVE_NOTIFICATIONS, mainMenuItem.isNav_archive_notifications()?1:0); - values.put(Sqlite.COL_NAV_PEERTUBE, mainMenuItem.isNav_peertube()?1:0); - values.put(Sqlite.COL_NAV_FILTERS, mainMenuItem.isNav_filters()?1:0); - values.put(Sqlite.COL_NAV_HOW_TO_FOLLOW, mainMenuItem.isNav_how_to_follow()?1:0); - values.put(Sqlite.COL_NAV_BLOCKED, mainMenuItem.isNav_blocked()?1:0); - values.put(Sqlite.COL_NAV_MUTED, mainMenuItem.isNav_muted()?1:0); - values.put(Sqlite.COL_NAV_BLOCKED_DOMAINS, mainMenuItem.isNav_blocked()?1:0); - values.put(Sqlite.COL_NAV_HOWTO, mainMenuItem.isNav_howto()?1:0); - try{ - db.update(Sqlite.TABLE_MAIN_MENU_ITEMS, values, Sqlite.COL_USER_ID + " = ? AND " + Sqlite.COL_INSTANCE + " = ? " , + values.put(Sqlite.COL_NAV_NEWS, mainMenuItem.isNav_news() ? 1 : 0); + values.put(Sqlite.COL_NAV_LIST, mainMenuItem.isNav_list() ? 1 : 0); + values.put(Sqlite.COL_NAV_SCHEDULED, mainMenuItem.isNav_scheduled() ? 1 : 0); + values.put(Sqlite.COL_NAV_ARCHIVE, mainMenuItem.isNav_archive() ? 1 : 0); + values.put(Sqlite.COL_NAV_ARCHIVE_NOTIFICATIONS, mainMenuItem.isNav_archive_notifications() ? 1 : 0); + values.put(Sqlite.COL_NAV_PEERTUBE, mainMenuItem.isNav_peertube() ? 1 : 0); + values.put(Sqlite.COL_NAV_FILTERS, mainMenuItem.isNav_filters() ? 1 : 0); + values.put(Sqlite.COL_NAV_HOW_TO_FOLLOW, mainMenuItem.isNav_how_to_follow() ? 1 : 0); + values.put(Sqlite.COL_NAV_BLOCKED, mainMenuItem.isNav_blocked() ? 1 : 0); + values.put(Sqlite.COL_NAV_MUTED, mainMenuItem.isNav_muted() ? 1 : 0); + values.put(Sqlite.COL_NAV_BLOCKED_DOMAINS, mainMenuItem.isNav_blocked() ? 1 : 0); + values.put(Sqlite.COL_NAV_HOWTO, mainMenuItem.isNav_howto() ? 1 : 0); + try { + db.update(Sqlite.TABLE_MAIN_MENU_ITEMS, values, Sqlite.COL_USER_ID + " = ? AND " + Sqlite.COL_INSTANCE + " = ? ", new String[]{userId, instance}); - }catch (Exception ignored) {ignored.printStackTrace();} + } catch (Exception ignored) { + ignored.printStackTrace(); + } } - - //------- GETTERS ------- /** * Returns instance by its nale in db - * @param userId String + * + * @param userId String * @param instance String * @return MainMenuItem */ - public MainMenuItem getMainMenu(String userId, String instance){ + public MainMenuItem getMainMenu(String userId, String instance) { try { - Cursor c = db.query(Sqlite.TABLE_MAIN_MENU_ITEMS, null, Sqlite.COL_INSTANCE + " = '" + instance+ "' AND " + Sqlite.COL_USER_ID + " = '" + userId+ "'", null, null, null, null, "1"); + Cursor c = db.query(Sqlite.TABLE_MAIN_MENU_ITEMS, null, Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'", null, null, null, null, "1"); return cursorToMainMenu(c); } catch (Exception e) { return null; @@ -187,14 +196,15 @@ public class MainMenuDAO { /** * Returns instance by its nale in db + * * @return MainMenuItem */ - public MainMenuItem getMainMenu(){ + public MainMenuItem getMainMenu() { try { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); - Cursor c = db.query(Sqlite.TABLE_MAIN_MENU_ITEMS, null, Sqlite.COL_INSTANCE + " = '" + instance+ "' AND " + Sqlite.COL_USER_ID + " = '" + userId+ "'", null, null, null, null, "1"); + Cursor c = db.query(Sqlite.TABLE_MAIN_MENU_ITEMS, null, Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'", null, null, null, null, "1"); return cursorToMainMenu(c); } catch (Exception e) { e.printStackTrace(); @@ -203,13 +213,12 @@ public class MainMenuDAO { } - /*** * Method to hydrate main menu items from database * @param c Cursor * @return MainMenuItem */ - private MainMenuItem cursorToMainMenu(Cursor c){ + private MainMenuItem cursorToMainMenu(Cursor c) { //No element found MainMenuItem mainMenuItem = new MainMenuItem(); if (c.getCount() == 0) { diff --git a/app/src/main/java/app/fedilab/android/sqlite/NotificationCacheDAO.java b/app/src/main/java/app/fedilab/android/sqlite/NotificationCacheDAO.java index 7c7463bee..b504a80dd 100644 --- a/app/src/main/java/app/fedilab/android/sqlite/NotificationCacheDAO.java +++ b/app/src/main/java/app/fedilab/android/sqlite/NotificationCacheDAO.java @@ -53,11 +53,13 @@ public class NotificationCacheDAO { //------- INSERTIONS ------- + /** * Insert a status in database + * * @param notification Notification - * @param userId String - * @param instance String + * @param userId String + * @param instance String * @return long */ public long insertNotification(Notification notification, String userId, String instance) { @@ -66,16 +68,16 @@ public class NotificationCacheDAO { values.put(Sqlite.COL_USER_ID, userId); values.put(Sqlite.COL_INSTANCE, instance); long id = -1; - if( notification.getStatus() != null) { + if (notification.getStatus() != null) { values.put(Sqlite.COL_STATUS_ID, notification.getStatus().getId()); //Check if status exists in cache; Status status = new StatusCacheDAO(context, db).getStatus(StatusCacheDAO.NOTIFICATION_CACHE, notification.getStatus().getId(), userId, instance); - if( status == null){ + if (status == null) { id = new StatusCacheDAO(context, db).insertStatus(StatusCacheDAO.NOTIFICATION_CACHE, notification.getStatus(), userId, instance); - }else { + } else { id = status.getDb_id(); } - if( notification.getType().equals("mention")){ + if (notification.getType().equals("mention")) { values.put(Sqlite.COL_IN_REPLY_TO_ID, notification.getStatus().getIn_reply_to_id()); } } @@ -86,58 +88,57 @@ public class NotificationCacheDAO { //Inserts cached status long last_id; - try{ + try { last_id = db.insert(Sqlite.TABLE_NOTIFICATION_CACHE, null, values); - }catch (Exception e) { - last_id = -1; + } catch (Exception e) { + last_id = -1; e.printStackTrace(); } return last_id; } - - /** * Returns all cached notifications in db after filter + * * @return stored notifications List */ - public List getNotificationsFromID(FilterNotifications filterNotifications, String max_id){ + public List getNotificationsFromID(FilterNotifications filterNotifications, String max_id) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); //That the basic selection for all toots - StringBuilder selection = new StringBuilder( Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'"); - if( max_id != null) + StringBuilder selection = new StringBuilder(Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'"); + if (max_id != null) selection.append(" AND " + Sqlite.COL_NOTIFICATION_ID + " < '").append(max_id).append("'"); //BOOST - if( filterNotifications == null) + if (filterNotifications == null) filterNotifications = new FilterNotifications(); - if(filterNotifications.isBoost() || filterNotifications.isFavorite() || filterNotifications.isFollow() ||filterNotifications.isMention() || filterNotifications.isPoll() ){ + if (filterNotifications.isBoost() || filterNotifications.isFavorite() || filterNotifications.isFollow() || filterNotifications.isMention() || filterNotifications.isPoll()) { selection.append(" AND ( "); - if (filterNotifications.isBoost() ) { + if (filterNotifications.isBoost()) { selection.append(Sqlite.COL_TYPE + "='reblog' OR "); } - if (filterNotifications.isPoll() ) { + if (filterNotifications.isPoll()) { selection.append(Sqlite.COL_TYPE + "='poll' OR "); } - if (filterNotifications.isFollow() ) { + if (filterNotifications.isFollow()) { selection.append(Sqlite.COL_TYPE + "='follow' OR "); } - if (filterNotifications.isMention() ) { + if (filterNotifications.isMention()) { selection.append(Sqlite.COL_TYPE + "='mention' OR "); } - if (filterNotifications.isFavorite() ) { + if (filterNotifications.isFavorite()) { selection.append(Sqlite.COL_TYPE + "='favourite' OR "); } - String selectionStr = selection.toString().substring(0, selection.toString().length()-3); + String selectionStr = selection.toString().substring(0, selection.toString().length() - 3); selection = new StringBuilder(selectionStr); selection.append(") "); } - if( filterNotifications.getDateIni() != null) + if (filterNotifications.getDateIni() != null) selection.append(" AND " + Sqlite.COL_CREATED_AT + " >= '").append(filterNotifications.getDateIni()).append("'"); - if( filterNotifications.getDateEnd() != null) + if (filterNotifications.getDateEnd() != null) selection.append(" AND " + Sqlite.COL_CREATED_AT + " <= '").append(filterNotifications.getDateEnd()).append("'"); try { @@ -150,8 +151,10 @@ public class NotificationCacheDAO { } //------- INSERTIONS ------- + /** * Insert a status in database + * * @param notification Notification * @return long */ @@ -166,16 +169,16 @@ public class NotificationCacheDAO { values.put(Sqlite.COL_USER_ID, userId); values.put(Sqlite.COL_INSTANCE, instance); long id = -1; - if( notification.getStatus() != null) { + if (notification.getStatus() != null) { values.put(Sqlite.COL_STATUS_ID, notification.getStatus().getId()); //Check if status exists in cache; Status status = new StatusCacheDAO(context, db).getStatus(StatusCacheDAO.NOTIFICATION_CACHE, notification.getStatus().getId(), userId, instance); - if( status == null){ + if (status == null) { id = new StatusCacheDAO(context, db).insertStatus(StatusCacheDAO.NOTIFICATION_CACHE, notification.getStatus(), userId, instance); - }else { + } else { id = status.getDb_id(); } - if( notification.getType().equals("mention")){ + if (notification.getType().equals("mention")) { values.put(Sqlite.COL_IN_REPLY_TO_ID, notification.getStatus().getIn_reply_to_id()); } } @@ -186,10 +189,10 @@ public class NotificationCacheDAO { //Inserts cached notification long last_id; - try{ + try { last_id = db.insert(Sqlite.TABLE_NOTIFICATION_CACHE, null, values); - }catch (Exception e) { - last_id = -1; + } catch (Exception e) { + last_id = -1; e.printStackTrace(); } return last_id; @@ -202,16 +205,16 @@ public class NotificationCacheDAO { * Remove stored notification * @return int */ - public int remove(Notification notification){ + public int remove(Notification notification) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); - return db.delete(Sqlite.TABLE_NOTIFICATION_CACHE, Sqlite.COL_NOTIFICATION_ID + " = \"" + notification.getId() + "\" AND " + Sqlite.COL_INSTANCE + " = \"" + instance + "\" AND " + Sqlite.COL_USER_ID + " = '" + userId+ "'", null); + return db.delete(Sqlite.TABLE_NOTIFICATION_CACHE, Sqlite.COL_NOTIFICATION_ID + " = \"" + notification.getId() + "\" AND " + Sqlite.COL_INSTANCE + " = \"" + instance + "\" AND " + Sqlite.COL_USER_ID + " = '" + userId + "'", null); } - public void removeDuplicate(){ - db.execSQL("DELETE FROM "+Sqlite.TABLE_NOTIFICATION_CACHE+" WHERE "+Sqlite.COL_ID+" NOT IN (SELECT MIN("+Sqlite.COL_ID+") FROM "+Sqlite.TABLE_NOTIFICATION_CACHE+" GROUP BY "+Sqlite.COL_NOTIFICATION_ID+","+Sqlite.COL_INSTANCE+")"); + public void removeDuplicate() { + db.execSQL("DELETE FROM " + Sqlite.TABLE_NOTIFICATION_CACHE + " WHERE " + Sqlite.COL_ID + " NOT IN (SELECT MIN(" + Sqlite.COL_ID + ") FROM " + Sqlite.TABLE_NOTIFICATION_CACHE + " GROUP BY " + Sqlite.COL_NOTIFICATION_ID + "," + Sqlite.COL_INSTANCE + ")"); } @@ -219,33 +222,34 @@ public class NotificationCacheDAO { * Remove stored notifications * @return int */ - public int remove(Notification notification, String userId, String instance){ - return db.delete(Sqlite.TABLE_NOTIFICATION_CACHE, Sqlite.COL_NOTIFICATION_ID + " = \"" + notification.getId() + "\" AND " + Sqlite.COL_INSTANCE + " = \"" + instance + "\" AND " + Sqlite.COL_USER_ID + " = '" + userId+ "'", null); + public int remove(Notification notification, String userId, String instance) { + return db.delete(Sqlite.TABLE_NOTIFICATION_CACHE, Sqlite.COL_NOTIFICATION_ID + " = \"" + notification.getId() + "\" AND " + Sqlite.COL_INSTANCE + " = \"" + instance + "\" AND " + Sqlite.COL_USER_ID + " = '" + userId + "'", null); } - public int removeAllNotification(){ + public int removeAllNotification() { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); - return db.delete(Sqlite.TABLE_NOTIFICATION_CACHE, Sqlite.COL_INSTANCE + " = '" + instance+ "' AND " + Sqlite.COL_USER_ID + " = '" + userId+ "'", null); + return db.delete(Sqlite.TABLE_NOTIFICATION_CACHE, Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'", null); } - public int removeAll(){ - return db.delete(Sqlite.TABLE_NOTIFICATION_CACHE, null, null); + public int removeAll() { + return db.delete(Sqlite.TABLE_NOTIFICATION_CACHE, null, null); } //------- GETTERS ------- /** * Returns all cached Notification in db + * * @return stored notifications List */ - public List getAllNotifications(){ + public List getAllNotifications() { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); try { - Cursor c = db.query(Sqlite.TABLE_NOTIFICATION_CACHE, null, Sqlite.COL_INSTANCE + " = '" + instance+ "' AND " + Sqlite.COL_USER_ID + " = '" + userId+ "'", null, null, null, Sqlite.COL_CREATED_AT + " DESC", null); + Cursor c = db.query(Sqlite.TABLE_NOTIFICATION_CACHE, null, Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'", null, null, null, Sqlite.COL_CREATED_AT + " DESC", null); return cursorToListNotifications(c); } catch (Exception e) { e.printStackTrace(); @@ -256,14 +260,15 @@ public class NotificationCacheDAO { /** * Returns all cached Notification in db + * * @return stored notification List */ - public List getAllNotificationsId(){ + public List getAllNotificationsId() { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); try { - Cursor c = db.query(Sqlite.TABLE_NOTIFICATION_CACHE, new String[]{Sqlite.COL_NOTIFICATION_ID}, Sqlite.COL_INSTANCE + " = '" + instance+ "' AND " + Sqlite.COL_USER_ID + " = '" + userId+ "'", null, null, null, Sqlite.COL_CREATED_AT + " DESC", null); + Cursor c = db.query(Sqlite.TABLE_NOTIFICATION_CACHE, new String[]{Sqlite.COL_NOTIFICATION_ID}, Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'", null, null, null, Sqlite.COL_CREATED_AT + " DESC", null); return cursorToListNotificationsId(c); } catch (Exception e) { e.printStackTrace(); @@ -273,14 +278,15 @@ public class NotificationCacheDAO { /** * Returns the smaller date + * * @return Date */ - public Date getSmallerDate(){ + public Date getSmallerDate() { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); try { - Cursor c = db.query(Sqlite.TABLE_NOTIFICATION_CACHE, null, Sqlite.COL_INSTANCE + " = '" + instance+ "' AND " + Sqlite.COL_USER_ID + " = '" + userId+ "'", null, null, null, Sqlite.COL_CREATED_AT + " ASC", "1"); + Cursor c = db.query(Sqlite.TABLE_NOTIFICATION_CACHE, null, Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'", null, null, null, Sqlite.COL_CREATED_AT + " ASC", "1"); //No element found if (c.getCount() == 0) { c.close(); @@ -298,14 +304,15 @@ public class NotificationCacheDAO { /** * Returns the smaller date + * * @return Date */ - public Date getGreaterDate(){ + public Date getGreaterDate() { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); try { - Cursor c = db.query(Sqlite.TABLE_NOTIFICATION_CACHE, null, Sqlite.COL_INSTANCE + " = '" + instance+ "' AND " + Sqlite.COL_USER_ID + " = '" + userId+ "'", null, null, null, Sqlite.COL_CREATED_AT + " DESC", "1"); + Cursor c = db.query(Sqlite.TABLE_NOTIFICATION_CACHE, null, Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'", null, null, null, Sqlite.COL_CREATED_AT + " DESC", "1"); //No element found if (c.getCount() == 0) { c.close(); @@ -323,11 +330,12 @@ public class NotificationCacheDAO { /** * Returns the last id of backup for a use + * * @return Date */ - public String getLastNotificationIDCache(String userId, String instance){ + public String getLastNotificationIDCache(String userId, String instance) { try { - Cursor c = db.query(Sqlite.TABLE_NOTIFICATION_CACHE, null, Sqlite.COL_INSTANCE + " = '" + instance+ "' AND " + Sqlite.COL_USER_ID + " = '" + userId+ "'", null, null, null, Sqlite.COL_NOTIFICATION_ID + " DESC", "1"); + Cursor c = db.query(Sqlite.TABLE_NOTIFICATION_CACHE, null, Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'", null, null, null, Sqlite.COL_NOTIFICATION_ID + " DESC", "1"); //No element found if (c.getCount() == 0) { c.close(); @@ -345,16 +353,17 @@ public class NotificationCacheDAO { /** * Returns the last date of backup for a user + * * @return Date */ - public Date getLastNotificationDateCache(String userId, String instance){ + public Date getLastNotificationDateCache(String userId, String instance) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - if( userId == null || instance == null) { + if (userId == null || instance == null) { userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); instance = Helper.getLiveInstance(context); } try { - Cursor c = db.query(Sqlite.TABLE_NOTIFICATION_CACHE, null, Sqlite.COL_INSTANCE + " = '" + instance+ "' AND " + Sqlite.COL_USER_ID + " = '" + userId+ "'", null, null, null, Sqlite.COL_CREATED_AT + " DESC", "1"); + Cursor c = db.query(Sqlite.TABLE_NOTIFICATION_CACHE, null, Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'", null, null, null, Sqlite.COL_CREATED_AT + " DESC", "1"); //No element found if (c.getCount() == 0) { c.close(); @@ -372,14 +381,15 @@ public class NotificationCacheDAO { /** * Returns a cached notification by id in db + * * @return Notification */ - public Notification getNotification(String id){ + public Notification getNotification(String id) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); try { - Cursor c = db.query(Sqlite.TABLE_NOTIFICATION_CACHE, null, Sqlite.COL_NOTIFICATION_ID + " = '" + id + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance +"' AND " + Sqlite.COL_USER_ID + " = '" + userId+ "'", null, null, null, null, null); + Cursor c = db.query(Sqlite.TABLE_NOTIFICATION_CACHE, null, Sqlite.COL_NOTIFICATION_ID + " = '" + id + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'", null, null, null, null, null); return cursorToStoredNotification(c); } catch (Exception e) { return null; @@ -389,11 +399,12 @@ public class NotificationCacheDAO { /** * Returns a cached notification by id in db + * * @return Notification */ - public Notification getNotification(int cacheType, String id, String userId, String instance){ + public Notification getNotification(int cacheType, String id, String userId, String instance) { try { - Cursor c = db.query(Sqlite.TABLE_NOTIFICATION_CACHE, null, Sqlite.COL_NOTIFICATION_ID + " = '" + id + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance +"' AND " + Sqlite.COL_USER_ID + " = '" + userId+ "'", null, null, null, null, null); + Cursor c = db.query(Sqlite.TABLE_NOTIFICATION_CACHE, null, Sqlite.COL_NOTIFICATION_ID + " = '" + id + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'", null, null, null, null, null); return cursorToStoredNotification(c); } catch (Exception e) { return null; @@ -401,8 +412,7 @@ public class NotificationCacheDAO { } - - public StatisticsNotification getStat(){ + public StatisticsNotification getStat() { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); @@ -412,7 +422,7 @@ public class NotificationCacheDAO { //Count All Cursor mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_NOTIFICATION_CACHE - + " where " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance +"'" + + " where " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "'" , null); mCount.moveToFirst(); statistics.setTotal_notification(mCount.getInt(0)); @@ -420,7 +430,7 @@ public class NotificationCacheDAO { //Count boosts mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_NOTIFICATION_CACHE - + " where " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance +"' AND " + + " where " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_TYPE + " = 'reblog'" , null); mCount.moveToFirst(); @@ -429,7 +439,7 @@ public class NotificationCacheDAO { //Count favorites mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_NOTIFICATION_CACHE - + " where " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance +"' AND " + + " where " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_TYPE + " = 'favourite'" , null); mCount.moveToFirst(); @@ -439,7 +449,7 @@ public class NotificationCacheDAO { //Count mentions mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_NOTIFICATION_CACHE - + " where " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance +"' AND " + + " where " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_TYPE + " = 'mention'" , null); mCount.moveToFirst(); @@ -449,7 +459,7 @@ public class NotificationCacheDAO { //Count follows mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_NOTIFICATION_CACHE - + " where " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance +"' AND " + + " where " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_TYPE + " = 'follow'" , null); mCount.moveToFirst(); @@ -459,7 +469,7 @@ public class NotificationCacheDAO { //Count polls mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_NOTIFICATION_CACHE - + " where " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance +"' AND " + + " where " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_TYPE + " = 'poll'" , null); mCount.moveToFirst(); @@ -467,22 +477,21 @@ public class NotificationCacheDAO { mCount.close(); - statistics.setFirstTootDate(getSmallerDate()); statistics.setLastTootDate(getGreaterDate()); long days = 1; - if( statistics.getLastTootDate() != null && statistics.getFirstTootDate() != null) { + if (statistics.getLastTootDate() != null && statistics.getFirstTootDate() != null) { long diff = statistics.getLastTootDate().getTime() - statistics.getFirstTootDate().getTime(); days = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS); } - statistics.setFrequency((float)statistics.getTotal_notification()/days); + statistics.setFrequency((float) statistics.getTotal_notification() / days); return statistics; } - public NotificationCharts getCharts(Date dateIni, Date dateEnd){ + public NotificationCharts getCharts(Date dateIni, Date dateEnd) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); @@ -490,15 +499,15 @@ public class NotificationCacheDAO { Calendar start = Calendar.getInstance(); start.setTime(dateIni); - start.set(Calendar.HOUR_OF_DAY,0); - start.set(Calendar.MINUTE,0); - start.set(Calendar.SECOND,0); + start.set(Calendar.HOUR_OF_DAY, 0); + start.set(Calendar.MINUTE, 0); + start.set(Calendar.SECOND, 0); Calendar end = Calendar.getInstance(); end.setTime(dateEnd); - end.set(Calendar.HOUR_OF_DAY,23); - end.set(Calendar.MINUTE,59); - end.set(Calendar.SECOND,59); + end.set(Calendar.HOUR_OF_DAY, 23); + end.set(Calendar.MINUTE, 59); + end.set(Calendar.SECOND, 59); StringBuilder selection = new StringBuilder(Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'"); selection.append(" AND " + Sqlite.COL_CREATED_AT + " >= '").append(Helper.dateToString(start.getTime())).append("'"); @@ -518,7 +527,7 @@ public class NotificationCacheDAO { charts.setMentions(new LinkedHashMap<>()); charts.setPolls(new LinkedHashMap<>()); charts.setReblogs(new LinkedHashMap<>()); - if( data != null) { + if (data != null) { for (Notification notification : data) { Calendar tempdate = Calendar.getInstance(); tempdate.setTime(notification.getCreated_at()); @@ -527,35 +536,35 @@ public class NotificationCacheDAO { tempdate.set(Calendar.SECOND, 0); long date = tempdate.getTimeInMillis(); if (notification.getType().equals("reblog")) { - if(charts.getReblogs().containsKey(date)){ - charts.getReblogs().put(date,(charts.getReblogs().get(date)+1)); - }else{ - charts.getReblogs().put(date,1); + if (charts.getReblogs().containsKey(date)) { + charts.getReblogs().put(date, (charts.getReblogs().get(date) + 1)); + } else { + charts.getReblogs().put(date, 1); } } else if (notification.getType().equals("favourite")) { - if(charts.getFavourites().containsKey(date)){ - charts.getFavourites().put(date,(charts.getFavourites().get(date)+1)); - }else{ - charts.getFavourites().put(date,1); + if (charts.getFavourites().containsKey(date)) { + charts.getFavourites().put(date, (charts.getFavourites().get(date) + 1)); + } else { + charts.getFavourites().put(date, 1); } } else if (notification.getType().equals("follow")) { - if(charts.getFollows().containsKey(date)){ - charts.getFollows().put(date,(charts.getFollows().get(date)+1)); - }else{ - charts.getFollows().put(date,1); + if (charts.getFollows().containsKey(date)) { + charts.getFollows().put(date, (charts.getFollows().get(date) + 1)); + } else { + charts.getFollows().put(date, 1); } } else if (notification.getType().equals("mention")) { - if(charts.getMentions().containsKey(date)){ - charts.getMentions().put(date,(charts.getMentions().get(date)+1)); - }else{ - charts.getMentions().put(date,1); + if (charts.getMentions().containsKey(date)) { + charts.getMentions().put(date, (charts.getMentions().get(date) + 1)); + } else { + charts.getMentions().put(date, 1); } - }else if (notification.getType().equals("poll")) { - if(charts.getPolls().containsKey(date)){ - charts.getPolls().put(date,(charts.getPolls().get(date)+1)); - }else{ - charts.getPolls().put(date,1); + } else if (notification.getType().equals("poll")) { + if (charts.getPolls().containsKey(date)) { + charts.getPolls().put(date, (charts.getPolls().get(date) + 1)); + } else { + charts.getPolls().put(date, 1); } } } @@ -565,7 +574,7 @@ public class NotificationCacheDAO { } - public NotificationCharts getChartsEvolution(String status_id, Date dateIni, Date dateEnd){ + public NotificationCharts getChartsEvolution(String status_id, Date dateIni, Date dateEnd) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); @@ -573,17 +582,17 @@ public class NotificationCacheDAO { Calendar start = Calendar.getInstance(); Calendar end = Calendar.getInstance(); - if( status_id == null) { + if (status_id == null) { start.setTime(dateIni); - start.set(Calendar.HOUR_OF_DAY,0); - start.set(Calendar.MINUTE,0); - start.set(Calendar.SECOND,0); + start.set(Calendar.HOUR_OF_DAY, 0); + start.set(Calendar.MINUTE, 0); + start.set(Calendar.SECOND, 0); end.setTime(dateEnd); end.set(Calendar.HOUR_OF_DAY, 23); end.set(Calendar.MINUTE, 59); end.set(Calendar.SECOND, 59); - }else{ + } else { start.setTime(dateIni); end.setTime(dateIni); @@ -601,13 +610,13 @@ public class NotificationCacheDAO { charts.setReblogs(new LinkedHashMap<>()); int reblogCount = 0; int favCount = 0; - // int pollCount = 0; + // int pollCount = 0; int followCount = 0; int mentionCount = 0; Date smallestDate = getSmallerDate(); int minYVal = 0; - if( status_id == null) { + if (status_id == null) { StringBuilder selection = new StringBuilder(Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'"); selection.append(" AND " + Sqlite.COL_CREATED_AT + " >= '").append(Helper.dateToString(smallestDate)).append("'"); selection.append(" AND " + Sqlite.COL_CREATED_AT + " <= '").append(Helper.dateToString(start.getTime())).append("'"); @@ -673,15 +682,15 @@ public class NotificationCacheDAO { for (Date date = start.getTime(); start.before(end); start.add(Calendar.DATE, 1), date = start.getTime()) { Calendar startTmp = Calendar.getInstance(); startTmp.setTime(date); - startTmp.set(Calendar.HOUR_OF_DAY,0); - startTmp.set(Calendar.MINUTE,0); - startTmp.set(Calendar.SECOND,0); + startTmp.set(Calendar.HOUR_OF_DAY, 0); + startTmp.set(Calendar.MINUTE, 0); + startTmp.set(Calendar.SECOND, 0); Calendar endTmp = Calendar.getInstance(); endTmp.setTime(date); - endTmp.set(Calendar.HOUR_OF_DAY,23); - endTmp.set(Calendar.MINUTE,59); - endTmp.set(Calendar.SECOND,59); + endTmp.set(Calendar.HOUR_OF_DAY, 23); + endTmp.set(Calendar.MINUTE, 59); + endTmp.set(Calendar.SECOND, 59); selection = new StringBuilder(Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'"); @@ -704,7 +713,7 @@ public class NotificationCacheDAO { , null); mCount.moveToFirst(); favCount += mCount.getInt(0); - charts.getFavourites().put(date.getTime(),favCount); + charts.getFavourites().put(date.getTime(), favCount); mCount.close(); mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_NOTIFICATION_CACHE @@ -723,7 +732,7 @@ public class NotificationCacheDAO { , null); mCount.moveToFirst(); followCount += mCount.getInt(0); - charts.getFollows().put(date.getTime(),followCount); + charts.getFollows().put(date.getTime(), followCount); mCount.close(); /* mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_NOTIFICATION_CACHE @@ -739,7 +748,7 @@ public class NotificationCacheDAO { e.printStackTrace(); } } - }else{ + } else { start.add(Calendar.HOUR, -1); charts.getReblogs().put(start.getTimeInMillis(), 0); charts.getFavourites().put(start.getTimeInMillis(), 0); @@ -756,8 +765,8 @@ public class NotificationCacheDAO { StringBuilder selection = new StringBuilder(Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'"); selection.append(" AND " + Sqlite.COL_CREATED_AT + " >= '").append(Helper.dateToString(startTmp.getTime())).append("'"); selection.append(" AND " + Sqlite.COL_CREATED_AT + " <= '").append(Helper.dateToString(endTmp.getTime())).append("'"); - selection.append(" AND (" + Sqlite.COL_STATUS_ID + " = '").append(status_id).append("'").append( " OR "); - selection.append(Sqlite.COL_IN_REPLY_TO_ID + " = '").append(status_id).append("'").append( " ) "); + selection.append(" AND (" + Sqlite.COL_STATUS_ID + " = '").append(status_id).append("'").append(" OR "); + selection.append(Sqlite.COL_IN_REPLY_TO_ID + " = '").append(status_id).append("'").append(" ) "); try { Cursor mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_NOTIFICATION_CACHE @@ -776,7 +785,7 @@ public class NotificationCacheDAO { , null); mCount.moveToFirst(); favCount += mCount.getInt(0); - charts.getFavourites().put(date.getTime(),favCount); + charts.getFavourites().put(date.getTime(), favCount); mCount.close(); mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_NOTIFICATION_CACHE @@ -798,7 +807,7 @@ public class NotificationCacheDAO { , null); mCount.moveToFirst(); followCount += mCount.getInt(0); - charts.getFollows().put(date.getTime(),followCount); + charts.getFollows().put(date.getTime(), followCount); mCount.close(); /* mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_NOTIFICATION_CACHE @@ -822,13 +831,12 @@ public class NotificationCacheDAO { } - /*** * Method to hydrate notification from database * @param c Cursor * @return Notification */ - private Notification cursorToStoredNotification(Cursor c){ + private Notification cursorToStoredNotification(Cursor c) { //No element found if (c.getCount() == 0) { c.close(); @@ -842,9 +850,9 @@ public class NotificationCacheDAO { notification.setAccount(Helper.restoreAccountFromString(c.getString(c.getColumnIndex(Sqlite.COL_ACCOUNT)))); notification.setCreated_at(Helper.stringToDate(context, c.getString(c.getColumnIndex(Sqlite.COL_CREATED_AT)))); notification.setType(c.getString(c.getColumnIndex(Sqlite.COL_TYPE))); - if( c.getString(c.getColumnIndex(Sqlite.COL_STATUS_ID)) != null ){ + if (c.getString(c.getColumnIndex(Sqlite.COL_STATUS_ID)) != null) { String status_id = c.getString(c.getColumnIndex(Sqlite.COL_STATUS_ID)); - Status status = new StatusCacheDAO(context, db).getStatus(StatusCacheDAO.NOTIFICATION_CACHE, status_id); + Status status = new StatusCacheDAO(context, db).getStatus(StatusCacheDAO.NOTIFICATION_CACHE, status_id); notification.setStatus(status); } //Close the cursor @@ -858,23 +866,23 @@ public class NotificationCacheDAO { * @param c Cursor * @return List */ - private List cursorToListNotifications(Cursor c){ + private List cursorToListNotifications(Cursor c) { //No element found if (c.getCount() == 0) { c.close(); return null; } List notifications = new ArrayList<>(); - while (c.moveToNext() ) { + while (c.moveToNext()) { //Restore cached notification Notification notification = new Notification(); notification.setId(c.getString(c.getColumnIndex(Sqlite.COL_NOTIFICATION_ID))); notification.setAccount(Helper.restoreAccountFromString(c.getString(c.getColumnIndex(Sqlite.COL_ACCOUNT)))); notification.setCreated_at(Helper.stringToDate(context, c.getString(c.getColumnIndex(Sqlite.COL_CREATED_AT)))); notification.setType(c.getString(c.getColumnIndex(Sqlite.COL_TYPE))); - if( c.getString(c.getColumnIndex(Sqlite.COL_STATUS_ID)) != null ){ + if (c.getString(c.getColumnIndex(Sqlite.COL_STATUS_ID)) != null) { String status_id = c.getString(c.getColumnIndex(Sqlite.COL_STATUS_ID)); - Status status = new StatusCacheDAO(context, db).getStatus(StatusCacheDAO.NOTIFICATION_CACHE, status_id); + Status status = new StatusCacheDAO(context, db).getStatus(StatusCacheDAO.NOTIFICATION_CACHE, status_id); notification.setStatus(status); } notifications.add(notification); @@ -891,14 +899,14 @@ public class NotificationCacheDAO { * @param c Cursor * @return List */ - private List cursorToListNotificationsId(Cursor c){ + private List cursorToListNotificationsId(Cursor c) { //No element found if (c.getCount() == 0) { c.close(); return null; } List notificationsId = new ArrayList<>(); - while (c.moveToNext() ) { + while (c.moveToNext()) { //Restore cached notification notificationsId.add(c.getString(c.getColumnIndex(Sqlite.COL_NOTIFICATION_ID))); } diff --git a/app/src/main/java/app/fedilab/android/sqlite/PeertubeFavoritesDAO.java b/app/src/main/java/app/fedilab/android/sqlite/PeertubeFavoritesDAO.java index d13bdaeeb..bc49f453a 100644 --- a/app/src/main/java/app/fedilab/android/sqlite/PeertubeFavoritesDAO.java +++ b/app/src/main/java/app/fedilab/android/sqlite/PeertubeFavoritesDAO.java @@ -49,8 +49,10 @@ public class PeertubeFavoritesDAO { //------- INSERTIONS ------- + /** * Insert a status in database + * * @param peertube Peertube * @return boolean */ @@ -62,10 +64,10 @@ public class PeertubeFavoritesDAO { values.put(Sqlite.COL_CACHE, peertube.getCache().toString()); //Inserts cached peertube long last_id; - try{ + try { last_id = db.insert(Sqlite.TABLE_PEERTUBE_FAVOURITES, null, values); - }catch (Exception e) { - last_id = -1; + } catch (Exception e) { + last_id = -1; } return last_id; } @@ -75,30 +77,30 @@ public class PeertubeFavoritesDAO { * Remove stored status * @return int */ - public int remove(Peertube peertube){ - return db.delete(Sqlite.TABLE_PEERTUBE_FAVOURITES, Sqlite.COL_UUID + " = \""+ peertube.getUuid() +"\" AND " + Sqlite.COL_INSTANCE + " = \"" + peertube.getInstance() + "\"", null); + public int remove(Peertube peertube) { + return db.delete(Sqlite.TABLE_PEERTUBE_FAVOURITES, Sqlite.COL_UUID + " = \"" + peertube.getUuid() + "\" AND " + Sqlite.COL_INSTANCE + " = \"" + peertube.getInstance() + "\"", null); } /*** * Remove stored status * @return int */ - public int removeAll(){ - return db.delete(Sqlite.TABLE_PEERTUBE_FAVOURITES, null, null); + public int removeAll() { + return db.delete(Sqlite.TABLE_PEERTUBE_FAVOURITES, null, null); } - //------- GETTERS ------- /** * Returns all cached Peertube + * * @return stored peertube List */ - public List getAllPeertube(){ + public List getAllPeertube() { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); try { - Cursor c = db.query(Sqlite.TABLE_PEERTUBE_FAVOURITES, null, null, null, null, null, Sqlite.COL_DATE+ " DESC"); + Cursor c = db.query(Sqlite.TABLE_PEERTUBE_FAVOURITES, null, null, null, null, null, Sqlite.COL_DATE + " DESC"); return cursorToListPeertube(c); } catch (Exception e) { return null; @@ -107,12 +109,13 @@ public class PeertubeFavoritesDAO { /** * Returns a cached Peertube + * * @return stored peertube List */ - public List getSinglePeertube(Peertube peertube){ + public List getSinglePeertube(Peertube peertube) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); try { - Cursor c = db.query(Sqlite.TABLE_PEERTUBE_FAVOURITES, null, Sqlite.COL_UUID + " = \""+ peertube.getUuid() +"\" AND " + Sqlite.COL_INSTANCE + " = \"" + peertube.getInstance() + "\"", null, null, null, Sqlite.COL_DATE+ " DESC"); + Cursor c = db.query(Sqlite.TABLE_PEERTUBE_FAVOURITES, null, Sqlite.COL_UUID + " = \"" + peertube.getUuid() + "\" AND " + Sqlite.COL_INSTANCE + " = \"" + peertube.getInstance() + "\"", null, null, null, Sqlite.COL_DATE + " DESC"); return cursorToListPeertube(c); } catch (Exception e) { return null; @@ -124,14 +127,14 @@ public class PeertubeFavoritesDAO { * @param c Cursor * @return List */ - private List cursorToListPeertube(Cursor c){ + private List cursorToListPeertube(Cursor c) { //No element found if (c.getCount() == 0) { c.close(); return null; } List peertubes = new ArrayList<>(); - while (c.moveToNext() ) { + while (c.moveToNext()) { //Restore cached status try { Peertube peertube = API.parsePeertube(context, c.getString(c.getColumnIndex(Sqlite.COL_INSTANCE)), new JSONObject(c.getString(c.getColumnIndex(Sqlite.COL_CACHE)))); diff --git a/app/src/main/java/app/fedilab/android/sqlite/SearchDAO.java b/app/src/main/java/app/fedilab/android/sqlite/SearchDAO.java index 71f1a85da..03f8b8598 100644 --- a/app/src/main/java/app/fedilab/android/sqlite/SearchDAO.java +++ b/app/src/main/java/app/fedilab/android/sqlite/SearchDAO.java @@ -52,11 +52,12 @@ public class SearchDAO { /** * Insert a keyword in database + * * @param keyword String */ public void insertSearch(String keyword) { ContentValues values = new ContentValues(); - if( keyword != null && keyword.trim().length() > 0) { + if (keyword != null && keyword.trim().length() > 0) { values.put(Sqlite.COL_KEYWORDS, keyword.trim()); values.put(Sqlite.COL_USER_ID, userId); values.put(Sqlite.COL_DATE_CREATION, Helper.dateToString(new Date())); @@ -73,26 +74,28 @@ public class SearchDAO { /** * update tag timeline info in database + * * @param tagTimeline TagTimeline */ public void updateSearch(TagTimeline tagTimeline) { ContentValues values = new ContentValues(); - values.put(Sqlite.COL_IS_ART, tagTimeline.isART()?1:0); - values.put(Sqlite.COL_IS_NSFW, tagTimeline.isNSFW()?1:0); + values.put(Sqlite.COL_IS_ART, tagTimeline.isART() ? 1 : 0); + values.put(Sqlite.COL_IS_NSFW, tagTimeline.isNSFW() ? 1 : 0); List any = tagTimeline.getAny(); List all = tagTimeline.getAll(); List none = tagTimeline.getNone(); String displayname = tagTimeline.getDisplayname(); values.put(Sqlite.COL_NAME, displayname); - if( any != null && any.size() > 0) + if (any != null && any.size() > 0) values.put(Sqlite.COL_ANY, Helper.arrayToStringStorage(any)); - if( all != null && all.size() > 0) + if (all != null && all.size() > 0) values.put(Sqlite.COL_ALL, Helper.arrayToStringStorage(all)); - if( none != null && none.size() > 0) + if (none != null && none.size() > 0) values.put(Sqlite.COL_NONE, Helper.arrayToStringStorage(none)); - try{ - db.update(Sqlite.TABLE_SEARCH, values, Sqlite.COL_ID + " = ? ", new String[]{String.valueOf(tagTimeline.getId())}); - }catch (Exception ignored) {} + try { + db.update(Sqlite.TABLE_SEARCH, values, Sqlite.COL_ID + " = ? ", new String[]{String.valueOf(tagTimeline.getId())}); + } catch (Exception ignored) { + } } @@ -102,19 +105,20 @@ public class SearchDAO { * Remove search by keyword * @return int */ - public int remove(String keyword){ - return db.delete(Sqlite.TABLE_SEARCH, Sqlite.COL_KEYWORDS + " = \"" + keyword + "\" AND " + Sqlite.COL_USER_ID + " = \"" + userId+ "\"", null); + public int remove(String keyword) { + return db.delete(Sqlite.TABLE_SEARCH, Sqlite.COL_KEYWORDS + " = \"" + keyword + "\" AND " + Sqlite.COL_USER_ID + " = \"" + userId + "\"", null); } //------- GETTERS ------- /** * Returns all search in db for a user + * * @return search List */ - public List getAllSearch(){ + public List getAllSearch() { try { - Cursor c = db.query(Sqlite.TABLE_SEARCH, null, Sqlite.COL_USER_ID + " = '" + userId+ "'", null, null, null, Sqlite.COL_KEYWORDS + " ASC", null); + Cursor c = db.query(Sqlite.TABLE_SEARCH, null, Sqlite.COL_USER_ID + " = '" + userId + "'", null, null, null, Sqlite.COL_KEYWORDS + " ASC", null); return cursorToListSearch(c); } catch (Exception e) { return null; @@ -122,14 +126,14 @@ public class SearchDAO { } - /** * Returns search by its keyword in db + * * @return keywords List */ - public List getSearchStartingBy(String keyword){ + public List getSearchStartingBy(String keyword) { try { - Cursor c = db.query(Sqlite.TABLE_SEARCH, null, Sqlite.COL_KEYWORDS + " LIKE \"%" + keyword + "%\" AND " + Sqlite.COL_USER_ID + " = \"" + userId+ "\"", null, null, null, null, null); + Cursor c = db.query(Sqlite.TABLE_SEARCH, null, Sqlite.COL_KEYWORDS + " LIKE \"%" + keyword + "%\" AND " + Sqlite.COL_USER_ID + " = \"" + userId + "\"", null, null, null, null, null); return cursorToListSearch(c); } catch (Exception e) { return null; @@ -138,11 +142,12 @@ public class SearchDAO { /** * Returns search by its keyword in db + * * @return keywords List */ - public List getSearchByKeyword(String keyword){ + public List getSearchByKeyword(String keyword) { try { - Cursor c = db.query(Sqlite.TABLE_SEARCH, null, Sqlite.COL_KEYWORDS + " = \"" + keyword + "\" AND " + Sqlite.COL_USER_ID + " = \"" + userId+ "\"", null, null, null, null, null); + Cursor c = db.query(Sqlite.TABLE_SEARCH, null, Sqlite.COL_KEYWORDS + " = \"" + keyword + "\" AND " + Sqlite.COL_USER_ID + " = \"" + userId + "\"", null, null, null, null, null); return cursorToListSearch(c); } catch (Exception e) { return null; @@ -155,13 +160,13 @@ public class SearchDAO { * @param c Cursor * @return List */ - private List cursorToListSearch(Cursor c){ + private List cursorToListSearch(Cursor c) { //No element found if (c.getCount() == 0) return null; List searches = new ArrayList<>(); - while (c.moveToNext() ) { - if( c.getString(c.getColumnIndex(Sqlite.COL_NAME)) != null) + while (c.moveToNext()) { + if (c.getString(c.getColumnIndex(Sqlite.COL_NAME)) != null) searches.add(c.getString(c.getColumnIndex(Sqlite.COL_NAME))); else searches.add(c.getString(c.getColumnIndex(Sqlite.COL_KEYWORDS))); @@ -175,11 +180,12 @@ public class SearchDAO { /** * Returns TagTimeline information by its keyword in db + * * @return info List */ - public List getTimelineInfo(String keyword){ + public List getTimelineInfo(String keyword) { try { - Cursor c = db.query(Sqlite.TABLE_SEARCH, null, Sqlite.COL_KEYWORDS + " = \"" + keyword + "\" AND " + Sqlite.COL_USER_ID + " = \"" + userId+ "\"", null, null, null, null, null); + Cursor c = db.query(Sqlite.TABLE_SEARCH, null, Sqlite.COL_KEYWORDS + " = \"" + keyword + "\" AND " + Sqlite.COL_USER_ID + " = \"" + userId + "\"", null, null, null, null, null); return cursorToTagTimelineSearch(c); } catch (Exception e) { return null; @@ -187,14 +193,14 @@ public class SearchDAO { } - /** * Returns TagTimeline information by its keyword in db + * * @return info List */ - public List getAll(){ + public List getAll() { try { - Cursor c = db.query(Sqlite.TABLE_SEARCH, null, Sqlite.COL_USER_ID + " = \"" + userId+ "\"", null, null, null, Sqlite.COL_KEYWORDS + " ASC", null); + Cursor c = db.query(Sqlite.TABLE_SEARCH, null, Sqlite.COL_USER_ID + " = \"" + userId + "\"", null, null, null, Sqlite.COL_KEYWORDS + " ASC", null); return cursorToTagTimelineSearch(c); } catch (Exception e) { return null; @@ -203,11 +209,12 @@ public class SearchDAO { /** * Returns TagTimeline information by its keyword in db + * * @return info List */ - public List getTabInfo(String name){ + public List getTabInfo(String name) { try { - Cursor c = db.query(Sqlite.TABLE_SEARCH, null, Sqlite.COL_NAME + " = \"" + name + "\" AND " + Sqlite.COL_USER_ID + " = \"" + userId+ "\"", null, null, null, null, null); + Cursor c = db.query(Sqlite.TABLE_SEARCH, null, Sqlite.COL_NAME + " = \"" + name + "\" AND " + Sqlite.COL_USER_ID + " = \"" + userId + "\"", null, null, null, null, null); return cursorToTagTimelineSearch(c); } catch (Exception e) { return null; @@ -216,11 +223,12 @@ public class SearchDAO { /** * Returns TagTimeline information by its keyword in db + * * @return info List */ - public List getTabInfoKeyword(String name){ + public List getTabInfoKeyword(String name) { try { - Cursor c = db.query(Sqlite.TABLE_SEARCH, null, Sqlite.COL_KEYWORDS + " = \"" + name + "\" AND " + Sqlite.COL_USER_ID + " = \"" + userId+ "\"", null, null, null, null, null); + Cursor c = db.query(Sqlite.TABLE_SEARCH, null, Sqlite.COL_KEYWORDS + " = \"" + name + "\" AND " + Sqlite.COL_USER_ID + " = \"" + userId + "\"", null, null, null, null, null); return cursorToTagTimelineSearch(c); } catch (Exception e) { return null; @@ -232,27 +240,30 @@ public class SearchDAO { * @param c Cursor * @return List */ - private List cursorToTagTimelineSearch(Cursor c){ + private List cursorToTagTimelineSearch(Cursor c) { //No element found if (c.getCount() == 0) return null; List searches = new ArrayList<>(); - while (c.moveToNext() ) { + while (c.moveToNext()) { TagTimeline tagTimeline = new TagTimeline(); try { tagTimeline.setAny(Helper.restoreArrayFromString(c.getString(c.getColumnIndex(Sqlite.COL_ANY)))); - }catch (Exception ignored){} + } catch (Exception ignored) { + } try { tagTimeline.setAll(Helper.restoreArrayFromString(c.getString(c.getColumnIndex(Sqlite.COL_ALL)))); - }catch (Exception ignored){} + } catch (Exception ignored) { + } try { tagTimeline.setNone(Helper.restoreArrayFromString(c.getString(c.getColumnIndex(Sqlite.COL_NONE)))); - }catch (Exception ignored){} + } catch (Exception ignored) { + } tagTimeline.setId(c.getInt(c.getColumnIndex(Sqlite.COL_ID))); tagTimeline.setName(c.getString(c.getColumnIndex(Sqlite.COL_KEYWORDS))); tagTimeline.setDisplayname(c.getString(c.getColumnIndex(Sqlite.COL_NAME))); - tagTimeline.setART(c.getInt(c.getColumnIndex(Sqlite.COL_IS_ART))==1); - tagTimeline.setNSFW(c.getInt(c.getColumnIndex(Sqlite.COL_IS_NSFW))==1); + tagTimeline.setART(c.getInt(c.getColumnIndex(Sqlite.COL_IS_ART)) == 1); + tagTimeline.setNSFW(c.getInt(c.getColumnIndex(Sqlite.COL_IS_NSFW)) == 1); searches.add(tagTimeline); } //Close the cursor diff --git a/app/src/main/java/app/fedilab/android/sqlite/Sqlite.java b/app/src/main/java/app/fedilab/android/sqlite/Sqlite.java index 91eefd965..252fa2801 100644 --- a/app/src/main/java/app/fedilab/android/sqlite/Sqlite.java +++ b/app/src/main/java/app/fedilab/android/sqlite/Sqlite.java @@ -136,9 +136,9 @@ public class Sqlite extends SQLiteOpenHelper { + COL_USER_ID + " TEXT, " + COL_USERNAME + " TEXT NOT NULL, " + COL_ACCT + " TEXT NOT NULL, " + COL_DISPLAYED_NAME + " TEXT NOT NULL, " + COL_LOCKED + " INTEGER NOT NULL, " + COL_FOLLOWERS_COUNT + " INTEGER NOT NULL, " + COL_FOLLOWING_COUNT + " INTEGER NOT NULL, " + COL_STATUSES_COUNT + " INTEGER NOT NULL, " - + COL_NOTE + " TEXT NOT NULL, "+ COL_URL + " TEXT NOT NULL, " - + COL_AVATAR + " TEXT NOT NULL, "+ COL_AVATAR_STATIC + " TEXT NOT NULL, " - + COL_HEADER + " TEXT NOT NULL, "+ COL_HEADER_STATIC + " TEXT NOT NULL, " + + COL_NOTE + " TEXT NOT NULL, " + COL_URL + " TEXT NOT NULL, " + + COL_AVATAR + " TEXT NOT NULL, " + COL_AVATAR_STATIC + " TEXT NOT NULL, " + + COL_HEADER + " TEXT NOT NULL, " + COL_HEADER_STATIC + " TEXT NOT NULL, " + COL_EMOJIS + " TEXT, " + COL_SOCIAL + " TEXT, " + COL_IS_MODERATOR + " INTEGER DEFAULT 0, " @@ -172,20 +172,20 @@ public class Sqlite extends SQLiteOpenHelper { private final String CREATE_TABLE_CUSTOM_EMOJI = "CREATE TABLE " + TABLE_CUSTOM_EMOJI + " (" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_SHORTCODE + " TEXT NOT NULL, " + COL_INSTANCE + " TEXT NOT NULL, " - + COL_URL + " TEXT NOT NULL, " + COL_URL_STATIC + " TEXT NOT NULL, " + COL_DATE_CREATION + " TEXT NOT NULL)"; + + COL_URL + " TEXT NOT NULL, " + COL_URL_STATIC + " TEXT NOT NULL, " + COL_DATE_CREATION + " TEXT NOT NULL)"; static final String COL_KEYWORDS = "KEYWORDS"; - static final String COL_IS_ART= "IS_ART"; - static final String COL_IS_NSFW= "IS_NSFW"; - static final String COL_ANY= "ANY_TAG"; - static final String COL_ALL= "ALL_TAG"; + static final String COL_IS_ART = "IS_ART"; + static final String COL_IS_NSFW = "IS_NSFW"; + static final String COL_ANY = "ANY_TAG"; + static final String COL_ALL = "ALL_TAG"; static final String COL_NONE = "NONE_TAG"; static final String COL_NAME = "NAME"; private final String CREATE_TABLE_SEARCH = "CREATE TABLE " + TABLE_SEARCH + " (" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_KEYWORDS + " TEXT NOT NULL, " + COL_USER_ID + " TEXT NOT NULL, " - + COL_ANY + " TEXT, " + COL_ALL + " TEXT, " + COL_NONE + " TEXT, "+ COL_NAME + " TEXT, " + + COL_ANY + " TEXT, " + COL_ALL + " TEXT, " + COL_NONE + " TEXT, " + COL_NAME + " TEXT, " + COL_IS_ART + " INTEGER DEFAULT 0, " + COL_IS_NSFW + " INTEGER DEFAULT 0, " + COL_DATE_CREATION + " TEXT NOT NULL)"; @@ -224,7 +224,7 @@ public class Sqlite extends SQLiteOpenHelper { private final String CREATE_TABLE_STATUSES_CACHE = "CREATE TABLE " + TABLE_STATUSES_CACHE + " (" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " - + COL_CACHED_ACTION + " INTEGER NOT NULL, "+ COL_INSTANCE + " TEXT NOT NULL, " + COL_USER_ID + " NOT NULL, " + COL_DATE_BACKUP + " TEXT NOT NULL, " + + COL_CACHED_ACTION + " INTEGER NOT NULL, " + COL_INSTANCE + " TEXT NOT NULL, " + COL_USER_ID + " NOT NULL, " + COL_DATE_BACKUP + " TEXT NOT NULL, " + COL_STATUS_ID + " TEXT NOT NULL, " + COL_URI + " TEXT NOT NULL, " + COL_URL + " TEXT NOT NULL, " + COL_ACCOUNT + " TEXT NOT NULL, " + COL_IN_REPLY_TO_ID + " TEXT, " + COL_IN_REPLY_TO_ACCOUNT_ID + " TEXT," + COL_REBLOG + " TEXT, " + COL_CONTENT + " TEXT NOT NULL, " + COL_CREATED_AT + " TEXT NOT NULL, " @@ -235,13 +235,13 @@ public class Sqlite extends SQLiteOpenHelper { + COL_LANGUAGE + " TEXT," + COL_PINNED + " INTEGER)"; private final String CREATE_UNIQUE_CACHE_INDEX = "CREATE UNIQUE INDEX instance_statusid on " - + TABLE_STATUSES_CACHE + "(" + COL_INSTANCE +"," + COL_STATUS_ID + "," +COL_CACHED_ACTION +")"; + + TABLE_STATUSES_CACHE + "(" + COL_INSTANCE + "," + COL_STATUS_ID + "," + COL_CACHED_ACTION + ")"; static final String COL_INSTANCE_TYPE = "INSTANCE_TYPE"; static final String COL_FILTERED_WITH = "FILTERED_WITH"; private final String CREATE_TABLE_INSTANCES = "CREATE TABLE " + TABLE_INSTANCES + " (" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " - + COL_INSTANCE + " TEXT NOT NULL, " + COL_USER_ID + " TEXT NOT NULL, " + COL_INSTANCE_TYPE + " TEXT, " + COL_TAGS + " TEXT, " + COL_FILTERED_WITH + " TEXT, "+ COL_DATE_CREATION + " TEXT NOT NULL)"; + + COL_INSTANCE + " TEXT NOT NULL, " + COL_USER_ID + " TEXT NOT NULL, " + COL_INSTANCE_TYPE + " TEXT, " + COL_TAGS + " TEXT, " + COL_FILTERED_WITH + " TEXT, " + COL_DATE_CREATION + " TEXT NOT NULL)"; static final String COL_UUID = "UUID"; @@ -257,18 +257,16 @@ public class Sqlite extends SQLiteOpenHelper { + COL_DATE + " TEXT NOT NULL)"; - private final String CREATE_TABLE_CACHE_TAGS = "CREATE TABLE " + TABLE_CACHE_TAGS + "(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_TAGS + " TEXT NOT NULL)"; - private static final String CREATE_TABLE_BOOST_SCHEDULE = "CREATE TABLE " + TABLE_BOOST_SCHEDULE + " (" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_USER_ID + " TEXT NOT NULL, " + COL_INSTANCE + " TEXT NOT NULL, " - + COL_STATUS_SERIALIZED + " TEXT NOT NULL, "+ COL_DATE_SCHEDULED + " TEXT, " + + COL_STATUS_SERIALIZED + " TEXT NOT NULL, " + COL_DATE_SCHEDULED + " TEXT, " + COL_IS_SCHEDULED + " INTEGER NOT NULL, " + COL_SENT + " INTEGER NOT NULL, " + COL_DATE_SENT + " TEXT)"; @@ -305,7 +303,6 @@ public class Sqlite extends SQLiteOpenHelper { + COL_DATE + " TEXT NOT NULL)"; - static final String COL_NOTIFICATION_ID = "NOTIFICATION_ID"; static final String COL_STATUS_ID_CACHE = "STATUS_ID_CACHE"; private static final String CREATE_TABLE_NOTIFICATIONS = "CREATE TABLE " @@ -348,10 +345,10 @@ public class Sqlite extends SQLiteOpenHelper { + COL_NAV_PEERTUBE + " INTEGER DEFAULT 1, " + COL_NAV_FILTERS + " INTEGER DEFAULT 1, " + COL_NAV_HOW_TO_FOLLOW + " INTEGER DEFAULT 1, " - + COL_NAV_ADMINISTRATION+ " INTEGER DEFAULT 1, " - + COL_NAV_BLOCKED+ " INTEGER DEFAULT 1, " - + COL_NAV_MUTED+ " INTEGER DEFAULT 1, " - + COL_NAV_BLOCKED_DOMAINS+ " INTEGER DEFAULT 1, " + + COL_NAV_ADMINISTRATION + " INTEGER DEFAULT 1, " + + COL_NAV_BLOCKED + " INTEGER DEFAULT 1, " + + COL_NAV_MUTED + " INTEGER DEFAULT 1, " + + COL_NAV_BLOCKED_DOMAINS + " INTEGER DEFAULT 1, " + COL_NAV_HOWTO + " INTEGER DEFAULT 1)"; @@ -360,8 +357,7 @@ public class Sqlite extends SQLiteOpenHelper { } - public static synchronized Sqlite getInstance(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) - { + public static synchronized Sqlite getInstance(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { if (sInstance == null) { sInstance = new Sqlite(context, name, factory, version); } @@ -408,9 +404,9 @@ public class Sqlite extends SQLiteOpenHelper { db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_CUSTOM_EMOJI + " (" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_SHORTCODE + " TEXT NOT NULL, " + COL_INSTANCE + " TEXT NOT NULL, " - + COL_URL + " TEXT NOT NULL, " + COL_URL_STATIC + " TEXT NOT NULL, " + COL_DATE_CREATION + " TEXT NOT NULL)"); + + COL_URL + " TEXT NOT NULL, " + COL_URL_STATIC + " TEXT NOT NULL, " + COL_DATE_CREATION + " TEXT NOT NULL)"); case 5: - db.execSQL("delete from "+ TABLE_CUSTOM_EMOJI); //Reset table due to bugs + db.execSQL("delete from " + TABLE_CUSTOM_EMOJI); //Reset table due to bugs case 6: db.execSQL(CREATE_TABLE_SEARCH); case 7: @@ -428,15 +424,15 @@ public class Sqlite extends SQLiteOpenHelper { case 11: db.execSQL(CREATE_TABLE_INSTANCES); case 12: - db.execSQL("ALTER TABLE " + TABLE_USER_ACCOUNT + " ADD COLUMN "+ COL_EMOJIS + " TEXT"); + db.execSQL("ALTER TABLE " + TABLE_USER_ACCOUNT + " ADD COLUMN " + COL_EMOJIS + " TEXT"); case 13: - if( oldVersion > 11) - db.execSQL("ALTER TABLE " + TABLE_INSTANCES + " ADD COLUMN "+ COL_INSTANCE_TYPE + " TEXT"); + if (oldVersion > 11) + db.execSQL("ALTER TABLE " + TABLE_INSTANCES + " ADD COLUMN " + COL_INSTANCE_TYPE + " TEXT"); case 14: db.execSQL(CREATE_TABLE_PEERTUBE_FAVOURITES); case 15: - if( oldVersion > 8) - db.execSQL("ALTER TABLE " + TABLE_STATUSES_CACHE + " ADD COLUMN "+ COL_CARD + " TEXT"); + if (oldVersion > 8) + db.execSQL("ALTER TABLE " + TABLE_STATUSES_CACHE + " ADD COLUMN " + COL_CARD + " TEXT"); case 16: case 17: db.execSQL("DROP TABLE IF EXISTS '" + TABLE_TIMELINE_CACHE + "'"); @@ -444,18 +440,18 @@ public class Sqlite extends SQLiteOpenHelper { case 18: db.execSQL(CREATE_TABLE_BOOST_SCHEDULE); case 19: - if( oldVersion > 6) { + if (oldVersion > 6) { db.execSQL("ALTER TABLE " + TABLE_SEARCH + " ADD COLUMN " + COL_IS_ART + " INTEGER DEFAULT 0"); db.execSQL("ALTER TABLE " + TABLE_SEARCH + " ADD COLUMN " + COL_IS_NSFW + " INTEGER DEFAULT 0"); } case 20: - if( oldVersion > 6) { + if (oldVersion > 6) { db.execSQL("ALTER TABLE " + TABLE_SEARCH + " ADD COLUMN " + COL_ANY + " TEXT"); db.execSQL("ALTER TABLE " + TABLE_SEARCH + " ADD COLUMN " + COL_ALL + " TEXT"); db.execSQL("ALTER TABLE " + TABLE_SEARCH + " ADD COLUMN " + COL_NONE + " TEXT"); } case 21: - if( oldVersion > 6) { + if (oldVersion > 6) { db.execSQL("ALTER TABLE " + TABLE_SEARCH + " ADD COLUMN " + COL_NAME + " TEXT"); } case 22: @@ -465,10 +461,10 @@ public class Sqlite extends SQLiteOpenHelper { db.execSQL("ALTER TABLE " + TABLE_USER_ACCOUNT + " ADD COLUMN " + COL_CLIENT_SECRET + " TEXT"); db.execSQL("ALTER TABLE " + TABLE_USER_ACCOUNT + " ADD COLUMN " + COL_REFRESH_TOKEN + " TEXT"); case 24: - db.execSQL("ALTER TABLE " + TABLE_USER_ACCOUNT + " ADD COLUMN " + COL_IS_MODERATOR + " INTEGER DEFAULT 0"); - db.execSQL("ALTER TABLE " + TABLE_USER_ACCOUNT + " ADD COLUMN " + COL_IS_ADMIN + " INTEGER DEFAULT 0"); + db.execSQL("ALTER TABLE " + TABLE_USER_ACCOUNT + " ADD COLUMN " + COL_IS_MODERATOR + " INTEGER DEFAULT 0"); + db.execSQL("ALTER TABLE " + TABLE_USER_ACCOUNT + " ADD COLUMN " + COL_IS_ADMIN + " INTEGER DEFAULT 0"); case 25: - db.execSQL("ALTER TABLE " + TABLE_USER_ACCOUNT + " ADD COLUMN " + COL_UPDATED_AT + " TEXT"); + db.execSQL("ALTER TABLE " + TABLE_USER_ACCOUNT + " ADD COLUMN " + COL_UPDATED_AT + " TEXT"); case 26: db.execSQL(CREATE_TABLE_TRACKING_BLOCK); case 27: @@ -479,7 +475,7 @@ public class Sqlite extends SQLiteOpenHelper { case 29: db.execSQL(CREATE_TABLE_TIMELINE_CACHE); case 30: - if( oldVersion > 11) { + if (oldVersion > 11) { db.execSQL("ALTER TABLE " + TABLE_INSTANCES + " ADD COLUMN " + COL_TAGS + " TEXT"); db.execSQL("ALTER TABLE " + TABLE_INSTANCES + " ADD COLUMN " + COL_FILTERED_WITH + " TEXT"); } @@ -488,9 +484,9 @@ public class Sqlite extends SQLiteOpenHelper { + COL_USER_ID + " TEXT, " + COL_USERNAME + " TEXT NOT NULL, " + COL_ACCT + " TEXT NOT NULL, " + COL_DISPLAYED_NAME + " TEXT NOT NULL, " + COL_LOCKED + " INTEGER NOT NULL, " + COL_FOLLOWERS_COUNT + " INTEGER NOT NULL, " + COL_FOLLOWING_COUNT + " INTEGER NOT NULL, " + COL_STATUSES_COUNT + " INTEGER NOT NULL, " - + COL_NOTE + " TEXT NOT NULL, "+ COL_URL + " TEXT NOT NULL, " - + COL_AVATAR + " TEXT NOT NULL, "+ COL_AVATAR_STATIC + " TEXT NOT NULL, " - + COL_HEADER + " TEXT NOT NULL, "+ COL_HEADER_STATIC + " TEXT NOT NULL, " + + COL_NOTE + " TEXT NOT NULL, " + COL_URL + " TEXT NOT NULL, " + + COL_AVATAR + " TEXT NOT NULL, " + COL_AVATAR_STATIC + " TEXT NOT NULL, " + + COL_HEADER + " TEXT NOT NULL, " + COL_HEADER_STATIC + " TEXT NOT NULL, " + COL_EMOJIS + " TEXT, " + COL_SOCIAL + " TEXT, " + COL_IS_MODERATOR + " INTEGER DEFAULT 0, " @@ -502,20 +498,20 @@ public class Sqlite extends SQLiteOpenHelper { + COL_INSTANCE + " TEXT NOT NULL, " + COL_OAUTHTOKEN + " TEXT NOT NULL, " + COL_CREATED_AT + " TEXT NOT NULL)"; db.execSQL(CREATE_TABLE_USER_ACCOUNT_TEMP); - String insert = "INSERT INTO "+TABLE_USER_ACCOUNT_TEMP+" (" - +COL_USER_ID+", "+COL_USERNAME+", "+COL_ACCT+", "+COL_DISPLAYED_NAME+", "+COL_LOCKED+", "+COL_FOLLOWERS_COUNT+", " - +COL_FOLLOWING_COUNT+", "+COL_STATUSES_COUNT+", "+COL_NOTE+", "+COL_URL+", "+COL_AVATAR+", "+COL_AVATAR_STATIC+", " - +COL_HEADER+", "+COL_HEADER_STATIC+", "+COL_EMOJIS+", "+COL_SOCIAL+", "+COL_IS_MODERATOR+", "+COL_IS_ADMIN+", " - +COL_CLIENT_ID+", "+COL_CLIENT_SECRET+", "+COL_REFRESH_TOKEN+", "+COL_UPDATED_AT+", "+COL_PRIVACY+", "+COL_SENSITIVE+", " - +COL_INSTANCE+", "+COL_OAUTHTOKEN+", "+COL_CREATED_AT+") " - +" SELECT "+COL_USER_ID+", "+COL_USERNAME+", "+COL_ACCT+", "+COL_DISPLAYED_NAME+", "+COL_LOCKED+", "+COL_FOLLOWERS_COUNT+", " - +COL_FOLLOWING_COUNT+", "+COL_STATUSES_COUNT+", "+COL_NOTE+", "+COL_URL+", "+COL_AVATAR+", "+COL_AVATAR_STATIC+", " - +COL_HEADER+", "+COL_HEADER_STATIC+", "+COL_EMOJIS+", "+COL_SOCIAL+", "+COL_IS_MODERATOR+", "+COL_IS_ADMIN+", " - +COL_CLIENT_ID+", "+COL_CLIENT_SECRET+", "+COL_REFRESH_TOKEN+", "+COL_UPDATED_AT+", "+COL_PRIVACY+", "+COL_SENSITIVE+", " - +COL_INSTANCE+", "+COL_OAUTHTOKEN+", "+COL_CREATED_AT+ " FROM " + TABLE_USER_ACCOUNT; + String insert = "INSERT INTO " + TABLE_USER_ACCOUNT_TEMP + " (" + + COL_USER_ID + ", " + COL_USERNAME + ", " + COL_ACCT + ", " + COL_DISPLAYED_NAME + ", " + COL_LOCKED + ", " + COL_FOLLOWERS_COUNT + ", " + + COL_FOLLOWING_COUNT + ", " + COL_STATUSES_COUNT + ", " + COL_NOTE + ", " + COL_URL + ", " + COL_AVATAR + ", " + COL_AVATAR_STATIC + ", " + + COL_HEADER + ", " + COL_HEADER_STATIC + ", " + COL_EMOJIS + ", " + COL_SOCIAL + ", " + COL_IS_MODERATOR + ", " + COL_IS_ADMIN + ", " + + COL_CLIENT_ID + ", " + COL_CLIENT_SECRET + ", " + COL_REFRESH_TOKEN + ", " + COL_UPDATED_AT + ", " + COL_PRIVACY + ", " + COL_SENSITIVE + ", " + + COL_INSTANCE + ", " + COL_OAUTHTOKEN + ", " + COL_CREATED_AT + ") " + + " SELECT " + COL_USER_ID + ", " + COL_USERNAME + ", " + COL_ACCT + ", " + COL_DISPLAYED_NAME + ", " + COL_LOCKED + ", " + COL_FOLLOWERS_COUNT + ", " + + COL_FOLLOWING_COUNT + ", " + COL_STATUSES_COUNT + ", " + COL_NOTE + ", " + COL_URL + ", " + COL_AVATAR + ", " + COL_AVATAR_STATIC + ", " + + COL_HEADER + ", " + COL_HEADER_STATIC + ", " + COL_EMOJIS + ", " + COL_SOCIAL + ", " + COL_IS_MODERATOR + ", " + COL_IS_ADMIN + ", " + + COL_CLIENT_ID + ", " + COL_CLIENT_SECRET + ", " + COL_REFRESH_TOKEN + ", " + COL_UPDATED_AT + ", " + COL_PRIVACY + ", " + COL_SENSITIVE + ", " + + COL_INSTANCE + ", " + COL_OAUTHTOKEN + ", " + COL_CREATED_AT + " FROM " + TABLE_USER_ACCOUNT; db.execSQL(insert); - db.execSQL("DROP TABLE "+TABLE_USER_ACCOUNT); - db.execSQL("ALTER TABLE "+TABLE_USER_ACCOUNT_TEMP + " RENAME TO "+ TABLE_USER_ACCOUNT); + db.execSQL("DROP TABLE " + TABLE_USER_ACCOUNT); + db.execSQL("ALTER TABLE " + TABLE_USER_ACCOUNT_TEMP + " RENAME TO " + TABLE_USER_ACCOUNT); case 32: db.execSQL(CREATE_TABLE_NOTIFICATIONS); @@ -523,31 +519,28 @@ public class Sqlite extends SQLiteOpenHelper { db.execSQL(CREATE_TABLE_MAIN_MENU_ITEMS); case 34: db.execSQL("DROP INDEX IF EXISTS instance_statusid"); - db.execSQL("DELETE FROM "+TABLE_STATUSES_CACHE); - db.execSQL("DELETE FROM "+TABLE_NOTIFICATION_CACHE); + db.execSQL("DELETE FROM " + TABLE_STATUSES_CACHE); + db.execSQL("DELETE FROM " + TABLE_NOTIFICATION_CACHE); db.execSQL(CREATE_UNIQUE_CACHE_INDEX); default: break; } } - public SQLiteDatabase open(){ + public SQLiteDatabase open() { //opened with write access db = getWritableDatabase(); return db; } - public void close(){ + public void close() { //Close the db - if( db != null && db.isOpen() ) { + if (db != null && db.isOpen()) { db.close(); } } - - - public static void importDB(Activity activity, String backupDBPath) { try { db.close(); @@ -561,7 +554,7 @@ public class Sqlite extends SQLiteOpenHelper { Helper.logoutCurrentUser(activity); } catch (Exception e) { e.printStackTrace(); - Toasty.error(activity.getApplicationContext(), activity.getString(R.string.data_import_error_simple),Toast.LENGTH_LONG).show(); + Toasty.error(activity.getApplicationContext(), activity.getString(R.string.data_import_error_simple), Toast.LENGTH_LONG).show(); } } @@ -572,9 +565,9 @@ public class Sqlite extends SQLiteOpenHelper { if (sd.canWrite()) { String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ENGLISH).format(new Date()); - String backupDBPath = "Fedilab_export_"+timeStamp+".fedilab"; + String backupDBPath = "Fedilab_export_" + timeStamp + ".fedilab"; File dbSource = context.getDatabasePath(DB_NAME); - File dbDest = new File(sd,backupDBPath); + File dbDest = new File(sd, backupDBPath); FileChannel src = new FileInputStream(dbSource).getChannel(); FileChannel dst = new FileOutputStream(dbDest).getChannel(); dst.transferFrom(src, 0, src.size()); @@ -590,8 +583,8 @@ public class Sqlite extends SQLiteOpenHelper { String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(context)); Account account = new AccountDAO(context, db).getUniqAccount(userId, instance); Helper.notify_user(context, account, intent, BitmapFactory.decodeResource(context.getResources(), - R.mipmap.ic_launcher), Helper.NotifType.STORE, context.getString(R.string.save_over), context.getString(R.string.download_from, backupDBPath)); - Toasty.success(context, context.getString(R.string.data_base_exported),Toast.LENGTH_LONG).show(); + R.mipmap.ic_launcher), Helper.NotifType.STORE, context.getString(R.string.save_over), context.getString(R.string.download_from, backupDBPath)); + Toasty.success(context, context.getString(R.string.data_base_exported), Toast.LENGTH_LONG).show(); } } catch (Exception e) { e.printStackTrace(); @@ -600,5 +593,4 @@ public class Sqlite extends SQLiteOpenHelper { } - } diff --git a/app/src/main/java/app/fedilab/android/sqlite/StatusCacheDAO.java b/app/src/main/java/app/fedilab/android/sqlite/StatusCacheDAO.java index 9100bda1b..9332cd31b 100644 --- a/app/src/main/java/app/fedilab/android/sqlite/StatusCacheDAO.java +++ b/app/src/main/java/app/fedilab/android/sqlite/StatusCacheDAO.java @@ -58,11 +58,13 @@ public class StatusCacheDAO { //------- INSERTIONS ------- + /** * Insert a status in database + * * @param cacheType int cache type - * @param status Status - * @param userId String + * @param status Status + * @param userId String * @return boolean */ public long insertStatus(int cacheType, Status status, String userId, String instance) { @@ -77,9 +79,9 @@ public class StatusCacheDAO { values.put(Sqlite.COL_ACCOUNT, Helper.accountToStringStorage(status.getAccount())); values.put(Sqlite.COL_IN_REPLY_TO_ID, status.getIn_reply_to_id()); values.put(Sqlite.COL_IN_REPLY_TO_ACCOUNT_ID, status.getIn_reply_to_account_id()); - values.put(Sqlite.COL_REBLOG, status.getReblog()!=null?Helper.statusToStringStorage(status.getReblog()):null); + values.put(Sqlite.COL_REBLOG, status.getReblog() != null ? Helper.statusToStringStorage(status.getReblog()) : null); values.put(Sqlite.COL_CONTENT, status.getContent()); - values.put(Sqlite.COL_EMOJIS, status.getEmojis()!=null?Helper.emojisToStringStorage(status.getEmojis()):null); + values.put(Sqlite.COL_EMOJIS, status.getEmojis() != null ? Helper.emojisToStringStorage(status.getEmojis()) : null); values.put(Sqlite.COL_REBLOGS_COUNT, status.getReblogs_count()); values.put(Sqlite.COL_FAVOURITES_COUNT, status.getFavourites_count()); values.put(Sqlite.COL_REBLOGGED, status.isReblogged()); @@ -90,19 +92,19 @@ public class StatusCacheDAO { values.put(Sqlite.COL_SENSITIVE, status.isSensitive()); values.put(Sqlite.COL_SPOILER_TEXT, status.getSpoiler_text()); values.put(Sqlite.COL_VISIBILITY, status.getVisibility()); - values.put(Sqlite.COL_MEDIA_ATTACHMENTS, status.getMedia_attachments()!=null?Helper.attachmentToStringStorage(status.getMedia_attachments()):null); - values.put(Sqlite.COL_MENTIONS, status.getMentions()!=null?Helper.mentionToStringStorage(status.getMentions()):null); - values.put(Sqlite.COL_TAGS, status.getTags()!=null?Helper.tagToStringStorage(status.getTags()):null); - values.put(Sqlite.COL_APPLICATION, status.getApplication()!=null?Helper.applicationToStringStorage(status.getApplication()):null); + values.put(Sqlite.COL_MEDIA_ATTACHMENTS, status.getMedia_attachments() != null ? Helper.attachmentToStringStorage(status.getMedia_attachments()) : null); + values.put(Sqlite.COL_MENTIONS, status.getMentions() != null ? Helper.mentionToStringStorage(status.getMentions()) : null); + values.put(Sqlite.COL_TAGS, status.getTags() != null ? Helper.tagToStringStorage(status.getTags()) : null); + values.put(Sqlite.COL_APPLICATION, status.getApplication() != null ? Helper.applicationToStringStorage(status.getApplication()) : null); values.put(Sqlite.COL_LANGUAGE, status.getLanguage()); values.put(Sqlite.COL_PINNED, status.isPinned()); //Inserts cached status long last_id; - try{ + try { last_id = db.insert(Sqlite.TABLE_STATUSES_CACHE, null, values); - }catch (Exception e) { - last_id = -1; + } catch (Exception e) { + last_id = -1; e.printStackTrace(); } return last_id; @@ -110,8 +112,9 @@ public class StatusCacheDAO { /** * Insert a status in database + * * @param cacheType int cache type - * @param status Status + * @param status Status * @return boolean */ public long insertStatus(int cacheType, Status status) { @@ -130,9 +133,9 @@ public class StatusCacheDAO { values.put(Sqlite.COL_CARD, Helper.cardToStringStorage(status.getCard())); values.put(Sqlite.COL_IN_REPLY_TO_ID, status.getIn_reply_to_id()); values.put(Sqlite.COL_IN_REPLY_TO_ACCOUNT_ID, status.getIn_reply_to_account_id()); - values.put(Sqlite.COL_REBLOG, status.getReblog()!=null?Helper.statusToStringStorage(status.getReblog()):null); + values.put(Sqlite.COL_REBLOG, status.getReblog() != null ? Helper.statusToStringStorage(status.getReblog()) : null); values.put(Sqlite.COL_CONTENT, status.getContent()); - values.put(Sqlite.COL_EMOJIS, status.getEmojis()!=null?Helper.emojisToStringStorage(status.getEmojis()):null); + values.put(Sqlite.COL_EMOJIS, status.getEmojis() != null ? Helper.emojisToStringStorage(status.getEmojis()) : null); values.put(Sqlite.COL_REBLOGS_COUNT, status.getReblogs_count()); values.put(Sqlite.COL_FAVOURITES_COUNT, status.getFavourites_count()); values.put(Sqlite.COL_REBLOGGED, status.isReblogged()); @@ -143,19 +146,19 @@ public class StatusCacheDAO { values.put(Sqlite.COL_SENSITIVE, status.isSensitive()); values.put(Sqlite.COL_SPOILER_TEXT, status.getSpoiler_text()); values.put(Sqlite.COL_VISIBILITY, status.getVisibility()); - values.put(Sqlite.COL_MEDIA_ATTACHMENTS, status.getMedia_attachments()!=null?Helper.attachmentToStringStorage(status.getMedia_attachments()):null); - values.put(Sqlite.COL_MENTIONS, status.getMentions()!=null?Helper.mentionToStringStorage(status.getMentions()):null); - values.put(Sqlite.COL_TAGS, status.getTags()!=null?Helper.tagToStringStorage(status.getTags()):null); - values.put(Sqlite.COL_APPLICATION, status.getApplication()!=null?Helper.applicationToStringStorage(status.getApplication()):null); + values.put(Sqlite.COL_MEDIA_ATTACHMENTS, status.getMedia_attachments() != null ? Helper.attachmentToStringStorage(status.getMedia_attachments()) : null); + values.put(Sqlite.COL_MENTIONS, status.getMentions() != null ? Helper.mentionToStringStorage(status.getMentions()) : null); + values.put(Sqlite.COL_TAGS, status.getTags() != null ? Helper.tagToStringStorage(status.getTags()) : null); + values.put(Sqlite.COL_APPLICATION, status.getApplication() != null ? Helper.applicationToStringStorage(status.getApplication()) : null); values.put(Sqlite.COL_LANGUAGE, status.getLanguage()); values.put(Sqlite.COL_PINNED, status.isPinned()); //Inserts cached status long last_id; - try{ + try { last_id = db.insert(Sqlite.TABLE_STATUSES_CACHE, null, values); - }catch (Exception e) { - last_id = -1; + } catch (Exception e) { + last_id = -1; e.printStackTrace(); } return last_id; @@ -165,10 +168,11 @@ public class StatusCacheDAO { /** * Update a Status cached in database + * * @param status Status * @return boolean */ - public int updateStatus(int cacheType, Status status ) { + public int updateStatus(int cacheType, Status status) { ContentValues values = new ContentValues(); String instance = Helper.getLiveInstance(context); values.put(Sqlite.COL_REBLOGS_COUNT, status.getReblogs_count()); @@ -189,15 +193,15 @@ public class StatusCacheDAO { * Remove stored status * @return int */ - public int remove(int cacheType, Status status){ + public int remove(int cacheType, Status status) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); - return db.delete(Sqlite.TABLE_STATUSES_CACHE, Sqlite.COL_CACHED_ACTION + " = \""+ cacheType +"\" AND " + Sqlite.COL_STATUS_ID + " = \"" + status.getId() + "\" AND " + Sqlite.COL_INSTANCE + " = \"" + instance + "\" AND " + Sqlite.COL_USER_ID + " = '" + userId+ "'", null); + return db.delete(Sqlite.TABLE_STATUSES_CACHE, Sqlite.COL_CACHED_ACTION + " = \"" + cacheType + "\" AND " + Sqlite.COL_STATUS_ID + " = \"" + status.getId() + "\" AND " + Sqlite.COL_INSTANCE + " = \"" + instance + "\" AND " + Sqlite.COL_USER_ID + " = '" + userId + "'", null); } - public void removeDuplicate(){ - db.execSQL("DELETE FROM "+Sqlite.TABLE_STATUSES_CACHE+" WHERE "+Sqlite.COL_ID+" NOT IN (SELECT MIN("+Sqlite.COL_ID+") FROM "+Sqlite.TABLE_STATUSES_CACHE+" GROUP BY "+Sqlite.COL_STATUS_ID+","+Sqlite.COL_INSTANCE+")"); + public void removeDuplicate() { + db.execSQL("DELETE FROM " + Sqlite.TABLE_STATUSES_CACHE + " WHERE " + Sqlite.COL_ID + " NOT IN (SELECT MIN(" + Sqlite.COL_ID + ") FROM " + Sqlite.TABLE_STATUSES_CACHE + " GROUP BY " + Sqlite.COL_STATUS_ID + "," + Sqlite.COL_INSTANCE + ")"); } @@ -205,33 +209,34 @@ public class StatusCacheDAO { * Remove stored status * @return int */ - public int remove(int cacheType, Status status, String userId, String instance){ - return db.delete(Sqlite.TABLE_STATUSES_CACHE, Sqlite.COL_CACHED_ACTION + " = \""+ cacheType +"\" AND " + Sqlite.COL_STATUS_ID + " = \"" + status.getId() + "\" AND " + Sqlite.COL_INSTANCE + " = \"" + instance + "\" AND " + Sqlite.COL_USER_ID + " = '" + userId+ "'", null); + public int remove(int cacheType, Status status, String userId, String instance) { + return db.delete(Sqlite.TABLE_STATUSES_CACHE, Sqlite.COL_CACHED_ACTION + " = \"" + cacheType + "\" AND " + Sqlite.COL_STATUS_ID + " = \"" + status.getId() + "\" AND " + Sqlite.COL_INSTANCE + " = \"" + instance + "\" AND " + Sqlite.COL_USER_ID + " = '" + userId + "'", null); } - public int removeAllStatus(int cacheType){ + public int removeAllStatus(int cacheType) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); - return db.delete(Sqlite.TABLE_STATUSES_CACHE, Sqlite.COL_CACHED_ACTION + " = \""+ cacheType +"\" AND " + Sqlite.COL_INSTANCE + " = '" + instance+ "' AND " + Sqlite.COL_USER_ID + " = '" + userId+ "'", null); + return db.delete(Sqlite.TABLE_STATUSES_CACHE, Sqlite.COL_CACHED_ACTION + " = \"" + cacheType + "\" AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'", null); } - public int removeAll(int cacheType){ - return db.delete(Sqlite.TABLE_STATUSES_CACHE, Sqlite.COL_CACHED_ACTION + " = \""+ cacheType +"\"", null); + public int removeAll(int cacheType) { + return db.delete(Sqlite.TABLE_STATUSES_CACHE, Sqlite.COL_CACHED_ACTION + " = \"" + cacheType + "\"", null); } //------- GETTERS ------- /** * Returns all cached Statuses in db depending of their cache type + * * @return stored status List */ - public List getAllStatus(int cacheType){ + public List getAllStatus(int cacheType) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); try { - Cursor c = db.query(Sqlite.TABLE_STATUSES_CACHE, null, Sqlite.COL_CACHED_ACTION + " = '" + cacheType+ "' AND " + Sqlite.COL_INSTANCE + " = '" + instance+ "' AND " + Sqlite.COL_USER_ID + " = '" + userId+ "'", null, null, null, Sqlite.COL_CREATED_AT + " DESC", null); + Cursor c = db.query(Sqlite.TABLE_STATUSES_CACHE, null, Sqlite.COL_CACHED_ACTION + " = '" + cacheType + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'", null, null, null, Sqlite.COL_CREATED_AT + " DESC", null); return cursorToListStatuses(c); } catch (Exception e) { e.printStackTrace(); @@ -242,14 +247,15 @@ public class StatusCacheDAO { /** * Returns all cached Statuses in db depending of their cache type + * * @return stored status List */ - public List getAllStatusId(int cacheType){ + public List getAllStatusId(int cacheType) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); try { - Cursor c = db.query(Sqlite.TABLE_STATUSES_CACHE, new String[]{Sqlite.COL_STATUS_ID}, Sqlite.COL_CACHED_ACTION + " = '" + cacheType+ "' AND " + Sqlite.COL_INSTANCE + " = '" + instance+ "' AND " + Sqlite.COL_USER_ID + " = '" + userId+ "'", null, null, null, Sqlite.COL_CREATED_AT + " DESC", null); + Cursor c = db.query(Sqlite.TABLE_STATUSES_CACHE, new String[]{Sqlite.COL_STATUS_ID}, Sqlite.COL_CACHED_ACTION + " = '" + cacheType + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'", null, null, null, Sqlite.COL_CREATED_AT + " DESC", null); return cursorToListStatusesId(c); } catch (Exception e) { e.printStackTrace(); @@ -260,63 +266,64 @@ public class StatusCacheDAO { /** * Returns all cached Statuses in db depending of their cache type + * * @return stored status List */ - public List getStatusFromID(int cacheType, FilterToots filterToots, String max_id){ + public List getStatusFromID(int cacheType, FilterToots filterToots, String max_id) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); //That the basic selection for all toots StringBuilder selection = new StringBuilder(Sqlite.COL_CACHED_ACTION + " = '" + cacheType + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'"); - if( max_id != null) + if (max_id != null) selection.append(" AND " + Sqlite.COL_STATUS_ID + " < '").append(max_id).append("'"); //BOOST - if(filterToots.getBoosts() == FilterToots.typeFilter.NONE) + if (filterToots.getBoosts() == FilterToots.typeFilter.NONE) selection.append(" AND (" + Sqlite.COL_REBLOG + " IS NULL OR " + Sqlite.COL_REBLOG + " = 'null')"); - else if(filterToots.getBoosts() == FilterToots.typeFilter.ONLY) + else if (filterToots.getBoosts() == FilterToots.typeFilter.ONLY) selection.append(" AND " + Sqlite.COL_REBLOG + " IS NOT NULL AND " + Sqlite.COL_REBLOG + " <> 'null'"); //REPLIES - if(filterToots.getReplies() == FilterToots.typeFilter.NONE) + if (filterToots.getReplies() == FilterToots.typeFilter.NONE) selection.append(" AND (" + Sqlite.COL_IN_REPLY_TO_ID + " IS NULL OR " + Sqlite.COL_IN_REPLY_TO_ID + " = 'null')"); - else if(filterToots.getReplies() == FilterToots.typeFilter.ONLY) + else if (filterToots.getReplies() == FilterToots.typeFilter.ONLY) selection.append(" AND " + Sqlite.COL_IN_REPLY_TO_ID + " IS NOT NULL AND " + Sqlite.COL_IN_REPLY_TO_ID + " <> 'null'"); //PINNED - if(filterToots.getPinned() == FilterToots.typeFilter.NONE) + if (filterToots.getPinned() == FilterToots.typeFilter.NONE) selection.append(" AND " + Sqlite.COL_PINNED + " = 0"); - else if(filterToots.getPinned() == FilterToots.typeFilter.ONLY) + else if (filterToots.getPinned() == FilterToots.typeFilter.ONLY) selection.append(" AND " + Sqlite.COL_PINNED + " = 1"); //PINNED - if(filterToots.getMedia() == FilterToots.typeFilter.NONE) + if (filterToots.getMedia() == FilterToots.typeFilter.NONE) selection.append(" AND " + Sqlite.COL_MEDIA_ATTACHMENTS + " = '[]'"); - else if(filterToots.getMedia() == FilterToots.typeFilter.ONLY) + else if (filterToots.getMedia() == FilterToots.typeFilter.ONLY) selection.append(" AND " + Sqlite.COL_MEDIA_ATTACHMENTS + " <> '[]'"); - if( !filterToots.isV_direct()) + if (!filterToots.isV_direct()) selection.append(" AND " + Sqlite.COL_VISIBILITY + " <> 'direct'"); - if( !filterToots.isV_private()) + if (!filterToots.isV_private()) selection.append(" AND " + Sqlite.COL_VISIBILITY + " <> 'private'"); - if( !filterToots.isV_public()) + if (!filterToots.isV_public()) selection.append(" AND " + Sqlite.COL_VISIBILITY + " <> 'public'"); - if( !filterToots.isV_unlisted()) + if (!filterToots.isV_unlisted()) selection.append(" AND " + Sqlite.COL_VISIBILITY + " <> 'unlisted'"); - if( filterToots.getDateIni() != null) + if (filterToots.getDateIni() != null) selection.append(" AND " + Sqlite.COL_CREATED_AT + " >= '").append(filterToots.getDateIni()).append("'"); - if( filterToots.getDateEnd() != null) + if (filterToots.getDateEnd() != null) selection.append(" AND " + Sqlite.COL_CREATED_AT + " <= '").append(filterToots.getDateEnd()).append("'"); - if( filterToots.getFilter() != null ){ + if (filterToots.getFilter() != null) { String[] keywords = filterToots.getFilter().split(" "); selection.append(" AND ("); int i = 0; - for(String kw: keywords){ + for (String kw : keywords) { - if( i == 0 && keywords.length == 1) + if (i == 0 && keywords.length == 1) selection.append(Sqlite.COL_CONTENT + " LIKE '%").append(kw).append("%'"); - else if( i == 0 && keywords.length > 1) + else if (i == 0 && keywords.length > 1) selection.append(Sqlite.COL_CONTENT + " LIKE '%").append(kw).append("%' OR "); - else if( i == keywords.length -1 ) + else if (i == keywords.length - 1) selection.append(Sqlite.COL_CONTENT + " LIKE '%").append(kw).append("%'"); i++; } @@ -334,14 +341,15 @@ public class StatusCacheDAO { /** * Returns the last date of backup for a user depending of the type of cache + * * @return Date */ - public Date getLastDateCache(int cacheType){ + public Date getLastDateCache(int cacheType) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); try { - Cursor c = db.query(Sqlite.TABLE_STATUSES_CACHE, null, Sqlite.COL_CACHED_ACTION + " = '" + cacheType+ "' AND " + Sqlite.COL_INSTANCE + " = '" + instance+ "' AND " + Sqlite.COL_USER_ID + " = '" + userId+ "'", null, null, null, Sqlite.COL_DATE_BACKUP + " DESC", "1"); + Cursor c = db.query(Sqlite.TABLE_STATUSES_CACHE, null, Sqlite.COL_CACHED_ACTION + " = '" + cacheType + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'", null, null, null, Sqlite.COL_DATE_BACKUP + " DESC", "1"); //No element found if (c.getCount() == 0) { c.close(); @@ -359,14 +367,15 @@ public class StatusCacheDAO { /** * Returns the smaller date + * * @return Date */ - public Date getSmallerDate(int cacheType){ + public Date getSmallerDate(int cacheType) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); try { - Cursor c = db.query(Sqlite.TABLE_STATUSES_CACHE, null, Sqlite.COL_CACHED_ACTION + " = '" + cacheType+ "' AND " + Sqlite.COL_INSTANCE + " = '" + instance+ "' AND " + Sqlite.COL_USER_ID + " = '" + userId+ "'", null, null, null, Sqlite.COL_CREATED_AT + " ASC", "1"); + Cursor c = db.query(Sqlite.TABLE_STATUSES_CACHE, null, Sqlite.COL_CACHED_ACTION + " = '" + cacheType + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'", null, null, null, Sqlite.COL_CREATED_AT + " ASC", "1"); //No element found if (c.getCount() == 0) { c.close(); @@ -384,14 +393,15 @@ public class StatusCacheDAO { /** * Returns the smaller date + * * @return Date */ - public Date getGreaterDate(int cacheType){ + public Date getGreaterDate(int cacheType) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); try { - Cursor c = db.query(Sqlite.TABLE_STATUSES_CACHE, null, Sqlite.COL_CACHED_ACTION + " = '" + cacheType+ "' AND " + Sqlite.COL_INSTANCE + " = '" + instance+ "' AND " + Sqlite.COL_USER_ID + " = '" + userId+ "'", null, null, null, Sqlite.COL_CREATED_AT + " DESC", "1"); + Cursor c = db.query(Sqlite.TABLE_STATUSES_CACHE, null, Sqlite.COL_CACHED_ACTION + " = '" + cacheType + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'", null, null, null, Sqlite.COL_CREATED_AT + " DESC", "1"); //No element found if (c.getCount() == 0) { c.close(); @@ -409,14 +419,15 @@ public class StatusCacheDAO { /** * Returns the last id of backup for a user depending of the type of cache + * * @return Date */ - public String getLastTootIDCache(int cacheType){ + public String getLastTootIDCache(int cacheType) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); try { - Cursor c = db.query(Sqlite.TABLE_STATUSES_CACHE, null, Sqlite.COL_CACHED_ACTION + " = '" + cacheType+ "' AND " + Sqlite.COL_INSTANCE + " = '" + instance+ "' AND " + Sqlite.COL_USER_ID + " = '" + userId+ "'", null, null, null, Sqlite.COL_STATUS_ID + " DESC", "1"); + Cursor c = db.query(Sqlite.TABLE_STATUSES_CACHE, null, Sqlite.COL_CACHED_ACTION + " = '" + cacheType + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'", null, null, null, Sqlite.COL_STATUS_ID + " DESC", "1"); //No element found if (c.getCount() == 0) { c.close(); @@ -434,16 +445,17 @@ public class StatusCacheDAO { /** * Returns the last date of backup for a user depending of the type of cache + * * @return Date */ - public Date getLastTootDateCache(int cacheType, String userId, String instance){ + public Date getLastTootDateCache(int cacheType, String userId, String instance) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - if( userId == null || instance == null) { + if (userId == null || instance == null) { userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); instance = Helper.getLiveInstance(context); } try { - Cursor c = db.query(Sqlite.TABLE_STATUSES_CACHE, null, Sqlite.COL_CACHED_ACTION + " = '" + cacheType+ "' AND " + Sqlite.COL_INSTANCE + " = '" + instance+ "' AND " + Sqlite.COL_USER_ID + " = '" + userId+ "'", null, null, null, Sqlite.COL_CREATED_AT + " DESC", "1"); + Cursor c = db.query(Sqlite.TABLE_STATUSES_CACHE, null, Sqlite.COL_CACHED_ACTION + " = '" + cacheType + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'", null, null, null, Sqlite.COL_CREATED_AT + " DESC", "1"); //No element found if (c.getCount() == 0) { c.close(); @@ -461,14 +473,15 @@ public class StatusCacheDAO { /** * Returns a cached status by id in db + * * @return stored status StoredStatus */ - public Status getStatus(int cacheType, String id){ + public Status getStatus(int cacheType, String id) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); try { - Cursor c = db.query(Sqlite.TABLE_STATUSES_CACHE, null, Sqlite.COL_CACHED_ACTION + " = '" + cacheType+ "' AND " + Sqlite.COL_STATUS_ID + " = '" + id + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance +"' AND " + Sqlite.COL_USER_ID + " = '" + userId+ "'", null, null, null, null, null); + Cursor c = db.query(Sqlite.TABLE_STATUSES_CACHE, null, Sqlite.COL_CACHED_ACTION + " = '" + cacheType + "' AND " + Sqlite.COL_STATUS_ID + " = '" + id + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'", null, null, null, null, null); return cursorToStoredStatus(c); } catch (Exception e) { return null; @@ -478,21 +491,22 @@ public class StatusCacheDAO { /** * Returns a cached status by id in db + * * @return stored status StoredStatus */ - public Status getStatus(String id){ + public Status getStatus(String id) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); try { - Cursor c = db.query(Sqlite.TABLE_STATUSES_CACHE, null, Sqlite.COL_STATUS_ID + " = '" + id + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance +"' AND " + Sqlite.COL_USER_ID + " = '" + userId+ "'", null, null, null, null, null); + Cursor c = db.query(Sqlite.TABLE_STATUSES_CACHE, null, Sqlite.COL_STATUS_ID + " = '" + id + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'", null, null, null, null, null); return cursorToStoredStatus(c); } catch (Exception e) { return null; } } - public Charts getCharts(Date dateIni, Date dateEnd){ + public Charts getCharts(Date dateIni, Date dateEnd) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); @@ -500,15 +514,15 @@ public class StatusCacheDAO { Calendar start = Calendar.getInstance(); start.setTime(dateIni); - start.set(Calendar.HOUR_OF_DAY,0); - start.set(Calendar.MINUTE,0); - start.set(Calendar.SECOND,0); + start.set(Calendar.HOUR_OF_DAY, 0); + start.set(Calendar.MINUTE, 0); + start.set(Calendar.SECOND, 0); Calendar end = Calendar.getInstance(); end.setTime(dateEnd); - end.set(Calendar.HOUR_OF_DAY,23); - end.set(Calendar.MINUTE,59); - end.set(Calendar.SECOND,59); + end.set(Calendar.HOUR_OF_DAY, 23); + end.set(Calendar.MINUTE, 59); + end.set(Calendar.SECOND, 59); StringBuilder selection = new StringBuilder(Sqlite.COL_CACHED_ACTION + " = '" + ARCHIVE_CACHE + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'"); selection.append(" AND " + Sqlite.COL_CREATED_AT + " >= '").append(Helper.dateToString(start.getTime())).append("'"); @@ -526,7 +540,7 @@ public class StatusCacheDAO { charts.setStatuses(new LinkedHashMap<>()); charts.setBoosts(new LinkedHashMap<>()); charts.setReplies(new LinkedHashMap<>()); - if( data != null) { + if (data != null) { for (Status status : data) { Calendar tempdate = Calendar.getInstance(); tempdate.setTime(status.getCreated_at()); @@ -535,23 +549,23 @@ public class StatusCacheDAO { tempdate.set(Calendar.SECOND, 0); long date = tempdate.getTimeInMillis(); if (status.getReblog() != null) { - if(charts.getBoosts().containsKey(date)){ - charts.getBoosts().put(date,(charts.getBoosts().get(date)+1)); - }else{ - charts.getBoosts().put(date,1); + if (charts.getBoosts().containsKey(date)) { + charts.getBoosts().put(date, (charts.getBoosts().get(date) + 1)); + } else { + charts.getBoosts().put(date, 1); } } else if (status.getIn_reply_to_id() != null && !status.getIn_reply_to_id().trim().equals("null")) { - if(charts.getReplies().containsKey(date)){ - charts.getReplies().put(date,(charts.getReplies().get(date)+1)); - }else{ - charts.getReplies().put(date,1); + if (charts.getReplies().containsKey(date)) { + charts.getReplies().put(date, (charts.getReplies().get(date) + 1)); + } else { + charts.getReplies().put(date, 1); } } else { - if(charts.getStatuses().containsKey(date)){ - charts.getStatuses().put(date,(charts.getStatuses().get(date)+1)); - }else{ - charts.getStatuses().put(date,1); + if (charts.getStatuses().containsKey(date)) { + charts.getStatuses().put(date, (charts.getStatuses().get(date) + 1)); + } else { + charts.getStatuses().put(date, 1); } } } @@ -562,18 +576,19 @@ public class StatusCacheDAO { /** * Returns a cached status by id in db + * * @return stored status StoredStatus */ - public Status getStatus(int cacheType, String id, String userId, String instance){ + public Status getStatus(int cacheType, String id, String userId, String instance) { try { - Cursor c = db.query(Sqlite.TABLE_STATUSES_CACHE, null, Sqlite.COL_CACHED_ACTION + " = '" + cacheType+ "' AND " + Sqlite.COL_STATUS_ID + " = '" + id + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance +"' AND " + Sqlite.COL_USER_ID + " = '" + userId+ "'", null, null, null, null, null); + Cursor c = db.query(Sqlite.TABLE_STATUSES_CACHE, null, Sqlite.COL_CACHED_ACTION + " = '" + cacheType + "' AND " + Sqlite.COL_STATUS_ID + " = '" + id + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "'", null, null, null, null, null); return cursorToStoredStatus(c); } catch (Exception e) { return null; } } - public Statistics getStat(){ + public Statistics getStat() { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); @@ -583,7 +598,7 @@ public class StatusCacheDAO { //Count All Cursor mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_STATUSES_CACHE - + " where " + Sqlite.COL_CACHED_ACTION + " = '" + ARCHIVE_CACHE + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance +"'" + + " where " + Sqlite.COL_CACHED_ACTION + " = '" + ARCHIVE_CACHE + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "'" , null); mCount.moveToFirst(); statistics.setTotal_statuses(mCount.getInt(0)); @@ -591,8 +606,8 @@ public class StatusCacheDAO { //Count boosts mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_STATUSES_CACHE - + " where " + Sqlite.COL_CACHED_ACTION + " = '" + ARCHIVE_CACHE + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance +"' AND " - + Sqlite.COL_REBLOG + " IS NOT NULL" + " AND " + Sqlite.COL_REBLOG + " != ''" + + " where " + Sqlite.COL_CACHED_ACTION + " = '" + ARCHIVE_CACHE + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + + Sqlite.COL_REBLOG + " IS NOT NULL" + " AND " + Sqlite.COL_REBLOG + " != ''" , null); mCount.moveToFirst(); statistics.setNumber_boosts(mCount.getInt(0)); @@ -600,8 +615,8 @@ public class StatusCacheDAO { //Count replies mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_STATUSES_CACHE - + " where " + Sqlite.COL_CACHED_ACTION + " = '" + ARCHIVE_CACHE + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance +"' AND " - + Sqlite.COL_IN_REPLY_TO_ID + " IS NOT NULL" + " AND " + Sqlite.COL_IN_REPLY_TO_ID + " != 'null'" + " AND " + Sqlite.COL_REBLOG + " IS NULL" + + " where " + Sqlite.COL_CACHED_ACTION + " = '" + ARCHIVE_CACHE + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + + Sqlite.COL_IN_REPLY_TO_ID + " IS NOT NULL" + " AND " + Sqlite.COL_IN_REPLY_TO_ID + " != 'null'" + " AND " + Sqlite.COL_REBLOG + " IS NULL" , null); mCount.moveToFirst(); statistics.setNumber_replies(mCount.getInt(0)); @@ -611,8 +626,8 @@ public class StatusCacheDAO { //Count media mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_STATUSES_CACHE - + " where " + Sqlite.COL_CACHED_ACTION + " = '" + ARCHIVE_CACHE + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance +"' AND " - + Sqlite.COL_MEDIA_ATTACHMENTS + " IS NOT NULL" + " AND " + Sqlite.COL_MEDIA_ATTACHMENTS + " !='"+Helper.attachmentToStringStorage(new ArrayList<>())+"' " + " AND " + Sqlite.COL_REBLOG + " IS NULL" + + " where " + Sqlite.COL_CACHED_ACTION + " = '" + ARCHIVE_CACHE + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + + Sqlite.COL_MEDIA_ATTACHMENTS + " IS NOT NULL" + " AND " + Sqlite.COL_MEDIA_ATTACHMENTS + " !='" + Helper.attachmentToStringStorage(new ArrayList<>()) + "' " + " AND " + Sqlite.COL_REBLOG + " IS NULL" , null); mCount.moveToFirst(); statistics.setNumber_with_media(mCount.getInt(0)); @@ -621,8 +636,8 @@ public class StatusCacheDAO { //Count sensitive mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_STATUSES_CACHE - + " where " + Sqlite.COL_CACHED_ACTION + " = '" + ARCHIVE_CACHE + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance +"' AND " - + Sqlite.COL_SENSITIVE + "= 1 AND " + Sqlite.COL_MEDIA_ATTACHMENTS + " IS NOT NULL" + " AND " + Sqlite.COL_MEDIA_ATTACHMENTS + " !='"+Helper.attachmentToStringStorage(new ArrayList<>())+"' " + " AND " + Sqlite.COL_REBLOG + " IS NULL" + + " where " + Sqlite.COL_CACHED_ACTION + " = '" + ARCHIVE_CACHE + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + + Sqlite.COL_SENSITIVE + "= 1 AND " + Sqlite.COL_MEDIA_ATTACHMENTS + " IS NOT NULL" + " AND " + Sqlite.COL_MEDIA_ATTACHMENTS + " !='" + Helper.attachmentToStringStorage(new ArrayList<>()) + "' " + " AND " + Sqlite.COL_REBLOG + " IS NULL" , null); mCount.moveToFirst(); statistics.setNumber_with_sensitive_media(mCount.getInt(0)); @@ -631,8 +646,8 @@ public class StatusCacheDAO { //Count sensitive mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_STATUSES_CACHE - + " where " + Sqlite.COL_CACHED_ACTION + " = '" + ARCHIVE_CACHE + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance +"' AND " - + Sqlite.COL_SPOILER_TEXT + " IS NOT NULL" + " AND " + Sqlite.COL_SPOILER_TEXT + " != '' " + " AND " +Sqlite.COL_REBLOG + " IS NULL" + + " where " + Sqlite.COL_CACHED_ACTION + " = '" + ARCHIVE_CACHE + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + + Sqlite.COL_SPOILER_TEXT + " IS NOT NULL" + " AND " + Sqlite.COL_SPOILER_TEXT + " != '' " + " AND " + Sqlite.COL_REBLOG + " IS NULL" , null); mCount.moveToFirst(); statistics.setNumber_with_cw(mCount.getInt(0)); @@ -640,8 +655,8 @@ public class StatusCacheDAO { //Count public mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_STATUSES_CACHE - + " where " + Sqlite.COL_CACHED_ACTION + " = '" + ARCHIVE_CACHE + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance +"' AND " - + Sqlite.COL_VISIBILITY + "='public'" + " AND " + Sqlite.COL_REBLOG + " IS NULL" + + " where " + Sqlite.COL_CACHED_ACTION + " = '" + ARCHIVE_CACHE + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + + Sqlite.COL_VISIBILITY + "='public'" + " AND " + Sqlite.COL_REBLOG + " IS NULL" , null); mCount.moveToFirst(); statistics.setV_public(mCount.getInt(0)); @@ -649,8 +664,8 @@ public class StatusCacheDAO { //Count unlisted mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_STATUSES_CACHE - + " where " + Sqlite.COL_CACHED_ACTION + " = '" + ARCHIVE_CACHE + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance +"' AND " - + Sqlite.COL_VISIBILITY + "='unlisted'" + " AND " + Sqlite.COL_REBLOG + " IS NULL" + + " where " + Sqlite.COL_CACHED_ACTION + " = '" + ARCHIVE_CACHE + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + + Sqlite.COL_VISIBILITY + "='unlisted'" + " AND " + Sqlite.COL_REBLOG + " IS NULL" , null); mCount.moveToFirst(); statistics.setV_unlisted(mCount.getInt(0)); @@ -658,8 +673,8 @@ public class StatusCacheDAO { //Count private mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_STATUSES_CACHE - + " where " + Sqlite.COL_CACHED_ACTION + " = '" + ARCHIVE_CACHE + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance +"' AND " - + Sqlite.COL_VISIBILITY + "='private'" + " AND " + Sqlite.COL_REBLOG + " IS NULL" + + " where " + Sqlite.COL_CACHED_ACTION + " = '" + ARCHIVE_CACHE + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + + Sqlite.COL_VISIBILITY + "='private'" + " AND " + Sqlite.COL_REBLOG + " IS NULL" , null); mCount.moveToFirst(); statistics.setV_private(mCount.getInt(0)); @@ -668,8 +683,8 @@ public class StatusCacheDAO { //Count private mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_STATUSES_CACHE - + " where " + Sqlite.COL_CACHED_ACTION + " = '" + ARCHIVE_CACHE + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance +"' AND " - + Sqlite.COL_VISIBILITY + "='direct'" + " AND " + Sqlite.COL_REBLOG + " IS NULL" + + " where " + Sqlite.COL_CACHED_ACTION + " = '" + ARCHIVE_CACHE + "' AND " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + + Sqlite.COL_VISIBILITY + "='direct'" + " AND " + Sqlite.COL_REBLOG + " IS NULL" , null); mCount.moveToFirst(); statistics.setV_direct(mCount.getInt(0)); @@ -697,9 +712,9 @@ public class StatusCacheDAO { } //Close the cursor c.close(); - if( countTags.size() > 0) { + if (countTags.size() > 0) { statistics.setTagsTrend(Helper.sortByValue(countTags)); - }else{ + } else { statistics.setTagsTrend(countTags); } @@ -708,11 +723,11 @@ public class StatusCacheDAO { statistics.setLastTootDate(getGreaterDate(ARCHIVE_CACHE)); long days = 1; - if( statistics.getLastTootDate() != null && statistics.getFirstTootDate() != null) { + if (statistics.getLastTootDate() != null && statistics.getFirstTootDate() != null) { long diff = statistics.getLastTootDate().getTime() - statistics.getFirstTootDate().getTime(); days = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS); } - statistics.setFrequency((float)statistics.getTotal_statuses()/days); + statistics.setFrequency((float) statistics.getTotal_statuses() / days); return statistics; } @@ -723,7 +738,7 @@ public class StatusCacheDAO { * @param c Cursor * @return Status */ - private Status cursorToStoredStatus(Cursor c){ + private Status cursorToStoredStatus(Cursor c) { //No element found if (c.getCount() == 0) { c.close(); @@ -747,11 +762,11 @@ public class StatusCacheDAO { status.setEmojis(Helper.restoreEmojisFromString(c.getString(c.getColumnIndex(Sqlite.COL_EMOJIS)))); status.setReblogs_count(c.getInt(c.getColumnIndex(Sqlite.COL_REBLOGS_COUNT))); status.setFavourites_count(c.getInt(c.getColumnIndex(Sqlite.COL_FAVOURITES_COUNT))); - status.setReblogged(c.getInt(c.getColumnIndex(Sqlite.COL_REBLOGGED))==1); - status.setFavourited(c.getInt(c.getColumnIndex(Sqlite.COL_FAVOURITED))==1); - status.setMuted(c.getInt(c.getColumnIndex(Sqlite.COL_MUTED))==1); - status.setSensitive(c.getInt(c.getColumnIndex(Sqlite.COL_SENSITIVE))==1); - status.setPinned(c.getInt(c.getColumnIndex(Sqlite.COL_PINNED))==1); + status.setReblogged(c.getInt(c.getColumnIndex(Sqlite.COL_REBLOGGED)) == 1); + status.setFavourited(c.getInt(c.getColumnIndex(Sqlite.COL_FAVOURITED)) == 1); + status.setMuted(c.getInt(c.getColumnIndex(Sqlite.COL_MUTED)) == 1); + status.setSensitive(c.getInt(c.getColumnIndex(Sqlite.COL_SENSITIVE)) == 1); + status.setPinned(c.getInt(c.getColumnIndex(Sqlite.COL_PINNED)) == 1); status.setSpoiler_text(c.getString(c.getColumnIndex(Sqlite.COL_SPOILER_TEXT))); status.setVisibility(c.getString(c.getColumnIndex(Sqlite.COL_VISIBILITY))); status.setMedia_attachments(Helper.restoreAttachmentFromString(c.getString(c.getColumnIndex(Sqlite.COL_MEDIA_ATTACHMENTS)))); @@ -770,14 +785,14 @@ public class StatusCacheDAO { * @param c Cursor * @return List */ - private List cursorToListStatuses(Cursor c){ + private List cursorToListStatuses(Cursor c) { //No element found if (c.getCount() == 0) { c.close(); return null; } List statuses = new ArrayList<>(); - while (c.moveToNext() ) { + while (c.moveToNext()) { //Restore cached status Status status = new Status(); status.setViewType(context); @@ -794,11 +809,11 @@ public class StatusCacheDAO { status.setEmojis(Helper.restoreEmojisFromString(c.getString(c.getColumnIndex(Sqlite.COL_EMOJIS)))); status.setReblogs_count(c.getInt(c.getColumnIndex(Sqlite.COL_REBLOGS_COUNT))); status.setFavourites_count(c.getInt(c.getColumnIndex(Sqlite.COL_FAVOURITES_COUNT))); - status.setReblogged(c.getInt(c.getColumnIndex(Sqlite.COL_REBLOGGED))==1); - status.setFavourited(c.getInt(c.getColumnIndex(Sqlite.COL_FAVOURITED))==1); - status.setMuted(c.getInt(c.getColumnIndex(Sqlite.COL_MUTED))==1); - status.setSensitive(c.getInt(c.getColumnIndex(Sqlite.COL_SENSITIVE))==1); - status.setPinned(c.getInt(c.getColumnIndex(Sqlite.COL_PINNED))==1); + status.setReblogged(c.getInt(c.getColumnIndex(Sqlite.COL_REBLOGGED)) == 1); + status.setFavourited(c.getInt(c.getColumnIndex(Sqlite.COL_FAVOURITED)) == 1); + status.setMuted(c.getInt(c.getColumnIndex(Sqlite.COL_MUTED)) == 1); + status.setSensitive(c.getInt(c.getColumnIndex(Sqlite.COL_SENSITIVE)) == 1); + status.setPinned(c.getInt(c.getColumnIndex(Sqlite.COL_PINNED)) == 1); status.setSpoiler_text(c.getString(c.getColumnIndex(Sqlite.COL_SPOILER_TEXT))); status.setVisibility(c.getString(c.getColumnIndex(Sqlite.COL_VISIBILITY))); status.setMedia_attachments(Helper.restoreAttachmentFromString(c.getString(c.getColumnIndex(Sqlite.COL_MEDIA_ATTACHMENTS)))); @@ -820,14 +835,14 @@ public class StatusCacheDAO { * @param c Cursor * @return List */ - private List cursorToListStatusesId(Cursor c){ + private List cursorToListStatusesId(Cursor c) { //No element found if (c.getCount() == 0) { c.close(); return null; } List statusesId = new ArrayList<>(); - while (c.moveToNext() ) { + while (c.moveToNext()) { //Restore cached status statusesId.add(c.getString(c.getColumnIndex(Sqlite.COL_STATUS_ID))); diff --git a/app/src/main/java/app/fedilab/android/sqlite/StatusStoredDAO.java b/app/src/main/java/app/fedilab/android/sqlite/StatusStoredDAO.java index 127a2e7c1..3544673dc 100644 --- a/app/src/main/java/app/fedilab/android/sqlite/StatusStoredDAO.java +++ b/app/src/main/java/app/fedilab/android/sqlite/StatusStoredDAO.java @@ -50,6 +50,7 @@ public class StatusStoredDAO { /** * Insert a status in database + * * @param status Status * @return boolean */ @@ -60,9 +61,9 @@ public class StatusStoredDAO { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); - if( userId == null || instance == null) + if (userId == null || instance == null) return -1; - if( statusReply != null){ + if (statusReply != null) { String serializedStatusReply = Helper.statusToStringStorage(statusReply); values.put(Sqlite.COL_STATUS_REPLY_SERIALIZED, serializedStatusReply); } @@ -74,10 +75,10 @@ public class StatusStoredDAO { values.put(Sqlite.COL_SENT, 0); //Inserts stored status long last_id; - try{ + try { last_id = db.insert(Sqlite.TABLE_STATUSES_STORED, null, values); - }catch (Exception e) { - last_id = -1; + } catch (Exception e) { + last_id = -1; } return last_id; } @@ -86,10 +87,11 @@ public class StatusStoredDAO { /** * Update a Status in database + * * @param status Status * @return boolean */ - public int updateStatus(long id, Status status ) { + public int updateStatus(long id, Status status) { ContentValues values = new ContentValues(); String serializedStatus = Helper.statusToStringStorage(status); @@ -102,7 +104,8 @@ public class StatusStoredDAO { /** * Update a Status in database - * @param id long + * + * @param id long * @param jobId int * @return int */ @@ -116,12 +119,13 @@ public class StatusStoredDAO { /** * Schedule a status in db - * @param id long - * @param jobId int + * + * @param id long + * @param jobId int * @param date_scheduled Date * @return boolean */ - public int scheduleStatus(long id, int jobId, Date date_scheduled ) { + public int scheduleStatus(long id, int jobId, Date date_scheduled) { ContentValues values = new ContentValues(); values.put(Sqlite.COL_IS_SCHEDULED, jobId); values.put(Sqlite.COL_DATE_SCHEDULED, Helper.dateToString(date_scheduled)); @@ -132,6 +136,7 @@ public class StatusStoredDAO { /** * Update scheduled date for a Status in database + * * @param scheduled_date Date * @return boolean */ @@ -145,7 +150,8 @@ public class StatusStoredDAO { /** * Update date when task is done for a scheduled Status in database - * @param jobid int + * + * @param jobid int * @param date_sent Date * @return boolean */ @@ -164,33 +170,34 @@ public class StatusStoredDAO { * Remove stored status by id * @return int */ - public int remove(long id){ - return db.delete(Sqlite.TABLE_STATUSES_STORED, Sqlite.COL_ID + " = \"" + id + "\"", null); + public int remove(long id) { + return db.delete(Sqlite.TABLE_STATUSES_STORED, Sqlite.COL_ID + " = \"" + id + "\"", null); } - public int removeAllDrafts(){ + public int removeAllDrafts() { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); - return db.delete(Sqlite.TABLE_STATUSES_STORED, Sqlite.COL_IS_SCHEDULED + " = \"0\" AND " + Sqlite.COL_USER_ID + " = '" + userId+ "' AND " + Sqlite.COL_INSTANCE + " = '" + instance+ "'", null); + return db.delete(Sqlite.TABLE_STATUSES_STORED, Sqlite.COL_IS_SCHEDULED + " = \"0\" AND " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "'", null); } - public int removeAllSent(){ - return db.delete(Sqlite.TABLE_STATUSES_STORED, Sqlite.COL_IS_SCHEDULED + " != 0 AND " + Sqlite.COL_SENT + " = 1", null); + public int removeAllSent() { + return db.delete(Sqlite.TABLE_STATUSES_STORED, Sqlite.COL_IS_SCHEDULED + " != 0 AND " + Sqlite.COL_SENT + " = 1", null); } //------- GETTERS ------- /** * Returns all stored Statuses in db + * * @return stored status List */ - public List getAllStatus(){ + public List getAllStatus() { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); try { - Cursor c = db.query(Sqlite.TABLE_STATUSES_STORED, null, Sqlite.COL_USER_ID + " = '" + userId+ "' AND " + Sqlite.COL_INSTANCE + " = '" + instance+ "'", null, null, null, Sqlite.COL_DATE_CREATION + " DESC", null); + Cursor c = db.query(Sqlite.TABLE_STATUSES_STORED, null, Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "'", null, null, null, Sqlite.COL_DATE_CREATION + " DESC", null); return cursorToListStatuses(c); } catch (Exception e) { return null; @@ -199,14 +206,15 @@ public class StatusStoredDAO { /** * Returns all stored Statuses in db + * * @return stored status List */ - public List getAllDrafts(){ + public List getAllDrafts() { try { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); - Cursor c = db.query(Sqlite.TABLE_STATUSES_STORED, null, Sqlite.COL_USER_ID + " = '" + userId+ "' AND " + Sqlite.COL_INSTANCE + " = '" + instance+ "' AND " + Sqlite.COL_IS_SCHEDULED + " = 0", null, null, null, Sqlite.COL_DATE_CREATION + " DESC", null); + Cursor c = db.query(Sqlite.TABLE_STATUSES_STORED, null, Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_IS_SCHEDULED + " = 0", null, null, null, Sqlite.COL_DATE_CREATION + " DESC", null); return cursorToListStatuses(c); } catch (Exception e) { e.printStackTrace(); @@ -217,29 +225,32 @@ public class StatusStoredDAO { /** * Returns all scheduled Statuses in db + * * @return stored status List */ - public List getAllScheduled(){ + public List getAllScheduled() { try { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); - Cursor c = db.query(Sqlite.TABLE_STATUSES_STORED, null, Sqlite.COL_USER_ID + " = '" + userId+ "' AND " + Sqlite.COL_INSTANCE + " = '" + instance+ "' AND " + Sqlite.COL_IS_SCHEDULED + " != 0 AND " + Sqlite.COL_SENT + " = 0", null, null, null, Sqlite.COL_DATE_SCHEDULED + " ASC", null); + Cursor c = db.query(Sqlite.TABLE_STATUSES_STORED, null, Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_IS_SCHEDULED + " != 0 AND " + Sqlite.COL_SENT + " = 0", null, null, null, Sqlite.COL_DATE_SCHEDULED + " ASC", null); return cursorToListStatuses(c); } catch (Exception e) { return null; } } + /** * Returns all not sent Statuses in db + * * @return stored status List */ - public List getAllNotSent(){ + public List getAllNotSent() { try { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); - Cursor c = db.query(Sqlite.TABLE_STATUSES_STORED, null, Sqlite.COL_USER_ID + " = '" + userId+ "' AND " + Sqlite.COL_INSTANCE + " = '" + instance+ "' AND " +Sqlite.COL_IS_SCHEDULED + " != 0 AND " + Sqlite.COL_SENT + " = 0", null, null, null, Sqlite.COL_DATE_CREATION + " DESC", null); + Cursor c = db.query(Sqlite.TABLE_STATUSES_STORED, null, Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_IS_SCHEDULED + " != 0 AND " + Sqlite.COL_SENT + " = 0", null, null, null, Sqlite.COL_DATE_CREATION + " DESC", null); return cursorToListStatuses(c); } catch (Exception e) { return null; @@ -248,14 +259,15 @@ public class StatusStoredDAO { /** * Returns all sent Statuses in db + * * @return stored status List */ - public List getAllSent(){ + public List getAllSent() { try { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); - Cursor c = db.query(Sqlite.TABLE_STATUSES_STORED, null, Sqlite.COL_USER_ID + " = '" + userId+ "' AND " + Sqlite.COL_INSTANCE + " = '" + instance+ "' AND " +Sqlite.COL_IS_SCHEDULED + " != 0 AND " + Sqlite.COL_SENT + " = 1", null, null, null, Sqlite.COL_DATE_CREATION + " DESC", null); + Cursor c = db.query(Sqlite.TABLE_STATUSES_STORED, null, Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_IS_SCHEDULED + " != 0 AND " + Sqlite.COL_SENT + " = 1", null, null, null, Sqlite.COL_DATE_CREATION + " DESC", null); return cursorToListStatuses(c); } catch (Exception e) { return null; @@ -264,9 +276,10 @@ public class StatusStoredDAO { /** * Returns a stored status by id in db + * * @return stored status StoredStatus */ - public StoredStatus getStatus(long id){ + public StoredStatus getStatus(long id) { try { Cursor c = db.query(Sqlite.TABLE_STATUSES_STORED, null, Sqlite.COL_ID + " = '" + id + "'", null, null, null, null, null); return cursorToStoredStatus(c); @@ -278,9 +291,10 @@ public class StatusStoredDAO { /** * Returns a stored status by id of job in db + * * @return stored status StoredStatus */ - public StoredStatus getStatusScheduled(int jobid){ + public StoredStatus getStatusScheduled(int jobid) { try { Cursor c = db.query(Sqlite.TABLE_STATUSES_STORED, null, Sqlite.COL_IS_SCHEDULED + " = '" + jobid + "'", null, null, null, null, null); return cursorToStoredStatus(c); @@ -294,7 +308,7 @@ public class StatusStoredDAO { * @param c Cursor * @return StoredStatus */ - private StoredStatus cursorToStoredStatus(Cursor c){ + private StoredStatus cursorToStoredStatus(Cursor c) { //No element found if (c.getCount() == 0) { c.close(); @@ -306,7 +320,7 @@ public class StatusStoredDAO { StoredStatus storedStatus = new StoredStatus(); storedStatus.setId(c.getInt(c.getColumnIndex(Sqlite.COL_ID))); Status status = Helper.restoreStatusFromString(c.getString(c.getColumnIndex(Sqlite.COL_STATUS_SERIALIZED))); - if( status == null){ + if (status == null) { remove(c.getInt(c.getColumnIndex(Sqlite.COL_ID))); return null; } @@ -331,19 +345,19 @@ public class StatusStoredDAO { * @param c Cursor * @return List */ - private List cursorToListStatuses(Cursor c){ + private List cursorToListStatuses(Cursor c) { //No element found if (c.getCount() == 0) { c.close(); return null; } List storedStatuses = new ArrayList<>(); - while (c.moveToNext() ) { + while (c.moveToNext()) { //Restore the status StoredStatus storedStatus = new StoredStatus(); storedStatus.setId(c.getInt(c.getColumnIndex(Sqlite.COL_ID))); Status status = Helper.restoreStatusFromString(c.getString(c.getColumnIndex(Sqlite.COL_STATUS_SERIALIZED))); - if( status == null){ + if (status == null) { remove(c.getInt(c.getColumnIndex(Sqlite.COL_ID))); continue; } @@ -351,7 +365,7 @@ public class StatusStoredDAO { Status statusReply = Helper.restoreStatusFromString(c.getString(c.getColumnIndex(Sqlite.COL_STATUS_REPLY_SERIALIZED))); storedStatus.setStatusReply(statusReply); storedStatus.setSent(c.getInt(c.getColumnIndex(Sqlite.COL_SENT)) == 1); - storedStatus.setJobId(c.getInt(c.getColumnIndex(Sqlite.COL_IS_SCHEDULED)) ); + storedStatus.setJobId(c.getInt(c.getColumnIndex(Sqlite.COL_IS_SCHEDULED))); storedStatus.setCreation_date(Helper.stringToDate(context, c.getString(c.getColumnIndex(Sqlite.COL_DATE_CREATION)))); storedStatus.setScheduled_date(Helper.stringToDate(context, c.getString(c.getColumnIndex(Sqlite.COL_DATE_SCHEDULED)))); storedStatus.setSent_date(Helper.stringToDate(context, c.getString(c.getColumnIndex(Sqlite.COL_DATE_SENT)))); diff --git a/app/src/main/java/app/fedilab/android/sqlite/TagsCacheDAO.java b/app/src/main/java/app/fedilab/android/sqlite/TagsCacheDAO.java index 20608a19f..1c44d866f 100644 --- a/app/src/main/java/app/fedilab/android/sqlite/TagsCacheDAO.java +++ b/app/src/main/java/app/fedilab/android/sqlite/TagsCacheDAO.java @@ -42,33 +42,37 @@ public class TagsCacheDAO { /** * Insert a tag in database + * * @param tag String */ public void insert(String tag) { ContentValues values = new ContentValues(); values.put(Sqlite.COL_TAGS, tag); - try{ + try { db.insert(Sqlite.TABLE_CACHE_TAGS, null, values); - }catch (Exception ignored) {} + } catch (Exception ignored) { + } } /** * update a tag in database + * * @param oldTag String * @param newTag String */ public void update(String oldTag, String newTag) { ContentValues values = new ContentValues(); values.put(Sqlite.COL_TAGS, newTag); - try{ - db.update(Sqlite.TABLE_CACHE_TAGS, values, Sqlite.COL_TAGS + " = ?",new String[]{ oldTag}); - }catch (Exception ignored) {} + try { + db.update(Sqlite.TABLE_CACHE_TAGS, values, Sqlite.COL_TAGS + " = ?", new String[]{oldTag}); + } catch (Exception ignored) { + } } /*** * Remove all tags */ - public void removeAll(){ + public void removeAll() { db.delete(Sqlite.TABLE_CACHE_TAGS, null, null); } @@ -79,11 +83,12 @@ public class TagsCacheDAO { /** * Returns all tags in db + * * @return string tags List */ - public List getAll(){ + public List getAll() { try { - Cursor c = db.query(Sqlite.TABLE_CACHE_TAGS, null, null, null, null, null, Sqlite.COL_TAGS+ " ASC", null); + Cursor c = db.query(Sqlite.TABLE_CACHE_TAGS, null, null, null, null, null, Sqlite.COL_TAGS + " ASC", null); return cursorToTag(c); } catch (Exception e) { return null; @@ -92,11 +97,12 @@ public class TagsCacheDAO { /** * Returns tags starting by "search" + * * @return boolean present */ - public boolean isPresent(String search){ + public boolean isPresent(String search) { Cursor c = db.query(Sqlite.TABLE_CACHE_TAGS, null, Sqlite.COL_TAGS + " = \"" + search + "\"", null, null, null, null, null); - boolean isPresent = (c!= null && c.getCount() > 0); + boolean isPresent = (c != null && c.getCount() > 0); assert c != null; c.close(); return isPresent; @@ -104,9 +110,10 @@ public class TagsCacheDAO { /** * Returns tags starting by "search" + * * @return tags List */ - public List getBy(String search){ + public List getBy(String search) { Cursor c = db.query(Sqlite.TABLE_CACHE_TAGS, null, Sqlite.COL_TAGS + " LIKE \"%" + search + "%\"", null, null, null, null, null); return cursorToTag(c); } @@ -116,14 +123,14 @@ public class TagsCacheDAO { * @param c Cursor * @return List */ - private List cursorToTag(Cursor c){ + private List cursorToTag(Cursor c) { //No element found if (c.getCount() == 0) { c.close(); return null; } List tags = new ArrayList<>(); - while (c.moveToNext() ) { + while (c.moveToNext()) { tags.add(c.getString(c.getColumnIndex(Sqlite.COL_TAGS))); } //Close the cursor diff --git a/app/src/main/java/app/fedilab/android/sqlite/TempMuteDAO.java b/app/src/main/java/app/fedilab/android/sqlite/TempMuteDAO.java index 1ec6f027b..14a93d6da 100644 --- a/app/src/main/java/app/fedilab/android/sqlite/TempMuteDAO.java +++ b/app/src/main/java/app/fedilab/android/sqlite/TempMuteDAO.java @@ -18,6 +18,7 @@ import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; + import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -46,9 +47,10 @@ public class TempMuteDAO { /** * Insert a keyword in database - * @param account Account + * + * @param account Account * @param targeted_id String - * @param date Date + * @param date Date */ public void insert(Account account, String targeted_id, Date date) { ContentValues values = new ContentValues(); @@ -58,9 +60,10 @@ public class TempMuteDAO { values.put(Sqlite.COL_DATE_CREATION, Helper.dateToString(new Date())); values.put(Sqlite.COL_DATE_END, Helper.dateToString(date)); //Inserts temp mute - try{ + try { db.insert(Sqlite.TABLE_TEMP_MUTE, null, values); - }catch (Exception ignored) {} + } catch (Exception ignored) { + } } //------- REMOVE ------- @@ -69,26 +72,27 @@ public class TempMuteDAO { * Remove mute by its id for the authenticated user * @return int */ - public int remove(Account account, String targeted_id){ - return db.delete(Sqlite.TABLE_TEMP_MUTE, Sqlite.COL_TARGETED_USER_ID + " = \"" + targeted_id + "\" AND " + Sqlite.COL_ACCT + " = \"" + account.getAcct()+ "\" AND " + Sqlite.COL_INSTANCE + " = \"" + account.getInstance()+ "\"", null); + public int remove(Account account, String targeted_id) { + return db.delete(Sqlite.TABLE_TEMP_MUTE, Sqlite.COL_TARGETED_USER_ID + " = \"" + targeted_id + "\" AND " + Sqlite.COL_ACCT + " = \"" + account.getAcct() + "\" AND " + Sqlite.COL_INSTANCE + " = \"" + account.getInstance() + "\"", null); } /*** * Remove mute by its id */ - public void removeOld(){ - db.delete(Sqlite.TABLE_TEMP_MUTE, Sqlite.COL_DATE_END + " < \"" + Helper.dateToString(new Date())+ "\"", null); + public void removeOld() { + db.delete(Sqlite.TABLE_TEMP_MUTE, Sqlite.COL_DATE_END + " < \"" + Helper.dateToString(new Date()) + "\"", null); } //------- GETTERS ------- /** * Returns all id of timed mute in db + * * @return time muted List */ - public List getAllTimeMuted(Account account){ + public List getAllTimeMuted(Account account) { try { - Cursor c = db.query(Sqlite.TABLE_TEMP_MUTE, null, Sqlite.COL_DATE_END + " >= \"" + Helper.dateToString(new Date())+ "\" AND " + Sqlite.COL_ACCT + " = \"" + account.getAcct()+ "\" AND " + Sqlite.COL_INSTANCE + " = \"" + account.getInstance()+ "\"", null, null, null, null, null); + Cursor c = db.query(Sqlite.TABLE_TEMP_MUTE, null, Sqlite.COL_DATE_END + " >= \"" + Helper.dateToString(new Date()) + "\" AND " + Sqlite.COL_ACCT + " = \"" + account.getAcct() + "\" AND " + Sqlite.COL_INSTANCE + " = \"" + account.getInstance() + "\"", null, null, null, null, null); return cursorToTimeMute(c); } catch (Exception e) { return null; @@ -98,11 +102,12 @@ public class TempMuteDAO { /** * Returns true if user is temp muted by the authenticated user + * * @return keywords List */ - public boolean isTempMuted(Account account, String targeted_id){ + public boolean isTempMuted(Account account, String targeted_id) { try { - Cursor c = db.query(Sqlite.TABLE_TEMP_MUTE, null, Sqlite.COL_TARGETED_USER_ID + " = \"" + targeted_id + "\" AND " + Sqlite.COL_DATE_END + " >= \"" + Helper.dateToString(new Date())+ "\" AND " + Sqlite.COL_ACCT + " = \"" + account.getAcct()+ "\" AND " + Sqlite.COL_INSTANCE + " = \"" + account.getInstance()+ "\"", null, null, null, null, null); + Cursor c = db.query(Sqlite.TABLE_TEMP_MUTE, null, Sqlite.COL_TARGETED_USER_ID + " = \"" + targeted_id + "\" AND " + Sqlite.COL_DATE_END + " >= \"" + Helper.dateToString(new Date()) + "\" AND " + Sqlite.COL_ACCT + " = \"" + account.getAcct() + "\" AND " + Sqlite.COL_INSTANCE + " = \"" + account.getInstance() + "\"", null, null, null, null, null); return cursorToTimeMute(c) != null; } catch (Exception e) { return false; @@ -112,11 +117,12 @@ public class TempMuteDAO { /** * Returns true if user is temp muted by the authenticated user + * * @return keywords List */ - public String getMuteDateByID(Account account, String targeted_id){ + public String getMuteDateByID(Account account, String targeted_id) { try { - Cursor c = db.query(Sqlite.TABLE_TEMP_MUTE, null, Sqlite.COL_TARGETED_USER_ID + " = \"" + targeted_id + "\" AND " + Sqlite.COL_DATE_END + " >= \"" + Helper.dateToString(new Date())+ "\" AND " + Sqlite.COL_ACCT + " = \"" + account.getAcct()+ "\" AND " + Sqlite.COL_INSTANCE + " = \"" + account.getInstance()+ "\"", null, null, null, Sqlite.COL_DATE_END + " DESC", "1"); + Cursor c = db.query(Sqlite.TABLE_TEMP_MUTE, null, Sqlite.COL_TARGETED_USER_ID + " = \"" + targeted_id + "\" AND " + Sqlite.COL_DATE_END + " >= \"" + Helper.dateToString(new Date()) + "\" AND " + Sqlite.COL_ACCT + " = \"" + account.getAcct() + "\" AND " + Sqlite.COL_INSTANCE + " = \"" + account.getInstance() + "\"", null, null, null, Sqlite.COL_DATE_END + " DESC", "1"); return cursorToDate(c); } catch (Exception e) { e.printStackTrace(); @@ -125,20 +131,19 @@ public class TempMuteDAO { } - /*** * Method to hydrate time mute id from database * @param c Cursor * @return List */ - private List cursorToTimeMute(Cursor c){ + private List cursorToTimeMute(Cursor c) { //No element found if (c.getCount() == 0) { c.close(); return null; } List timeMutes = new ArrayList<>(); - while (c.moveToNext() ) { + while (c.moveToNext()) { timeMutes.add(c.getString(c.getColumnIndex(Sqlite.COL_TARGETED_USER_ID))); } //Close the cursor @@ -152,7 +157,7 @@ public class TempMuteDAO { * @param c Cursor * @return String */ - private String cursorToDate(Cursor c){ + private String cursorToDate(Cursor c) { //No element found if (c.getCount() == 0) { c.close(); diff --git a/app/src/main/java/app/fedilab/android/sqlite/TimelineCacheDAO.java b/app/src/main/java/app/fedilab/android/sqlite/TimelineCacheDAO.java index 5beee6a39..b83f0fea2 100644 --- a/app/src/main/java/app/fedilab/android/sqlite/TimelineCacheDAO.java +++ b/app/src/main/java/app/fedilab/android/sqlite/TimelineCacheDAO.java @@ -49,8 +49,10 @@ public class TimelineCacheDAO { //------- INSERTIONS ------- + /** * Insert a status in database + * * @return boolean */ public long insert(String statusId, String jsonString, String userId, String instance) { @@ -62,16 +64,17 @@ public class TimelineCacheDAO { values.put(Sqlite.COL_CACHE, jsonString); //Inserts cached status long last_id; - try{ + try { last_id = db.insert(Sqlite.TABLE_TIMELINE_CACHE, null, values); - }catch (Exception e) { - last_id = -1; + } catch (Exception e) { + last_id = -1; e.printStackTrace(); } return last_id; } //------- UPDATE ------- + /** * Update a status in database */ @@ -79,9 +82,10 @@ public class TimelineCacheDAO { ContentValues values = new ContentValues(); values.put(Sqlite.COL_DATE, Helper.dateToString(new Date())); values.put(Sqlite.COL_CACHE, jsonString); - try{ - db.update(Sqlite.TABLE_TIMELINE_CACHE, values, Sqlite.COL_INSTANCE + " = ? AND " + Sqlite.COL_STATUS_ID + " = ? AND " + Sqlite.COL_USER_ID + " = ?", new String[]{instance, statusId, userId}); - }catch (Exception ignored) {} + try { + db.update(Sqlite.TABLE_TIMELINE_CACHE, values, Sqlite.COL_INSTANCE + " = ? AND " + Sqlite.COL_STATUS_ID + " = ? AND " + Sqlite.COL_USER_ID + " = ?", new String[]{instance, statusId, userId}); + } catch (Exception ignored) { + } } //------- REMOVE ------- @@ -94,7 +98,7 @@ public class TimelineCacheDAO { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); - return db.delete(Sqlite.TABLE_TIMELINE_CACHE, Sqlite.COL_STATUS_ID + " = \""+ statusId +"\" AND " + Sqlite.COL_INSTANCE + " = \"" + instance + "\" AND " + Sqlite.COL_USER_ID + " = \"" + userId + "\"", null); + return db.delete(Sqlite.TABLE_TIMELINE_CACHE, Sqlite.COL_STATUS_ID + " = \"" + statusId + "\" AND " + Sqlite.COL_INSTANCE + " = \"" + instance + "\" AND " + Sqlite.COL_USER_ID + " = \"" + userId + "\"", null); } @@ -106,18 +110,18 @@ public class TimelineCacheDAO { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); - return db.delete(Sqlite.TABLE_TIMELINE_CACHE, Sqlite.COL_DATE + " < \""+ date +"\" AND " + Sqlite.COL_INSTANCE + " = \"" + instance + "\" AND " + Sqlite.COL_USER_ID + " = \"" + userId + "\"", null); + return db.delete(Sqlite.TABLE_TIMELINE_CACHE, Sqlite.COL_DATE + " < \"" + date + "\" AND " + Sqlite.COL_INSTANCE + " = \"" + instance + "\" AND " + Sqlite.COL_USER_ID + " = \"" + userId + "\"", null); } /*** * Remove stored status * @return int */ - public int removeAllConnected(){ + public int removeAllConnected() { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); - return db.delete(Sqlite.TABLE_TIMELINE_CACHE, Sqlite.COL_INSTANCE + " = \"" + instance + "\" AND " + Sqlite.COL_USER_ID + " = \"" + userId + "\"", null); + return db.delete(Sqlite.TABLE_TIMELINE_CACHE, Sqlite.COL_INSTANCE + " = \"" + instance + "\" AND " + Sqlite.COL_USER_ID + " = \"" + userId + "\"", null); } @@ -125,26 +129,27 @@ public class TimelineCacheDAO { * Remove stored status * @return int */ - public int removeAll(){ - return db.delete(Sqlite.TABLE_TIMELINE_CACHE, null, null); + public int removeAll() { + return db.delete(Sqlite.TABLE_TIMELINE_CACHE, null, null); } //------- GETTERS ------- /** * Returns all cached Statuses + * * @return stored Status List */ - public List get(String max_id){ + public List get(String max_id) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); try { Cursor c; - if( max_id != null) - c = db.query(Sqlite.TABLE_TIMELINE_CACHE, null, Sqlite.COL_INSTANCE + " = \"" + instance + "\" AND " + Sqlite.COL_USER_ID + " = \"" + userId + "\" AND "+ Sqlite.COL_STATUS_ID + " <= " + max_id, null, null, null, Sqlite.COL_STATUS_ID+ " DESC", "40"); + if (max_id != null) + c = db.query(Sqlite.TABLE_TIMELINE_CACHE, null, Sqlite.COL_INSTANCE + " = \"" + instance + "\" AND " + Sqlite.COL_USER_ID + " = \"" + userId + "\" AND " + Sqlite.COL_STATUS_ID + " <= " + max_id, null, null, null, Sqlite.COL_STATUS_ID + " DESC", "40"); else - c = db.query(Sqlite.TABLE_TIMELINE_CACHE, null, Sqlite.COL_INSTANCE + " = \"" + instance + "\" AND " + Sqlite.COL_USER_ID + " = \"" + userId + "\"", null, null, null, Sqlite.COL_STATUS_ID+ " DESC", "40"); + c = db.query(Sqlite.TABLE_TIMELINE_CACHE, null, Sqlite.COL_INSTANCE + " = \"" + instance + "\" AND " + Sqlite.COL_USER_ID + " = \"" + userId + "\"", null, null, null, Sqlite.COL_STATUS_ID + " DESC", "40"); return cursorToListStatus(c); } catch (Exception e) { return null; @@ -154,17 +159,18 @@ public class TimelineCacheDAO { /** * Returns all cached Statuses + * * @return stored Status List */ - public List search(String word, String max_id){ + public List search(String word, String max_id) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); try { Cursor c; - if (word != null){ + if (word != null) { StringBuilder query; - if( !word.contains("\"")) { + if (!word.contains("\"")) { String[] searches = word.split(" "); query = new StringBuilder(" ("); for (String search : searches) { @@ -172,8 +178,8 @@ public class TimelineCacheDAO { } query = new StringBuilder(query.substring(0, query.length() - 3)); query.append(") "); - }else{ - String search = word.replace("\"",""); + } else { + String search = word.replace("\"", ""); query = new StringBuilder(Sqlite.COL_CACHE + " LIKE '%").append(search).append("%'"); } if (max_id != null) { @@ -193,14 +199,15 @@ public class TimelineCacheDAO { /** * Returns one cached Statuses + * * @return stored Status List */ - public Status getSingle(String statusId){ + public Status getSingle(String statusId) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); try { - Cursor c = db.query(Sqlite.TABLE_TIMELINE_CACHE, null, Sqlite.COL_INSTANCE + " = \"" + instance + "\" AND " + Sqlite.COL_USER_ID + " = \"" + userId + "\" AND "+ Sqlite.COL_STATUS_ID + " ='" + statusId +"'", null, null, null, Sqlite.COL_STATUS_ID+ " DESC", "1"); + Cursor c = db.query(Sqlite.TABLE_TIMELINE_CACHE, null, Sqlite.COL_INSTANCE + " = \"" + instance + "\" AND " + Sqlite.COL_USER_ID + " = \"" + userId + "\" AND " + Sqlite.COL_STATUS_ID + " ='" + statusId + "'", null, null, null, Sqlite.COL_STATUS_ID + " DESC", "1"); return cursorToSingleStatus(c); } catch (Exception e) { return null; @@ -212,7 +219,7 @@ public class TimelineCacheDAO { * @param c Cursor * @return Status */ - private Status cursorToSingleStatus(Cursor c){ + private Status cursorToSingleStatus(Cursor c) { //No element found if (c.getCount() == 0) { c.close(); @@ -237,14 +244,14 @@ public class TimelineCacheDAO { * @param c Cursor * @return List */ - private List cursorToListStatus(Cursor c){ + private List cursorToListStatus(Cursor c) { //No element found if (c.getCount() == 0) { c.close(); return null; } List statuses = new ArrayList<>(); - while (c.moveToNext() ) { + while (c.moveToNext()) { //Restore cached status try { Status status = API.parseStatuses(context, new JSONObject(c.getString(c.getColumnIndex(Sqlite.COL_CACHE)))); diff --git a/app/src/main/java/app/fedilab/android/sqlite/TimelinesDAO.java b/app/src/main/java/app/fedilab/android/sqlite/TimelinesDAO.java index 559ff2ee0..019534d6d 100644 --- a/app/src/main/java/app/fedilab/android/sqlite/TimelinesDAO.java +++ b/app/src/main/java/app/fedilab/android/sqlite/TimelinesDAO.java @@ -49,28 +49,29 @@ public class TimelinesDAO { values.put(Sqlite.COL_POSITION, timeline.getPosition()); values.put(Sqlite.COL_USER_ID, userId); values.put(Sqlite.COL_INSTANCE, instance); - if( timeline.getTagTimeline() != null) + if (timeline.getTagTimeline() != null) values.put(Sqlite.COL_TAG_TIMELINE, Helper.tagTimelineToStringStorage(timeline.getTagTimeline())); - if( timeline.getRemoteInstance() != null) + if (timeline.getRemoteInstance() != null) values.put(Sqlite.COL_REMOTE_INSTANCE, Helper.remoteInstanceToStringStorage(timeline.getRemoteInstance())); - if( timeline.getListTimeline() != null) + if (timeline.getListTimeline() != null) values.put(Sqlite.COL_LIST_TIMELINE, Helper.listTimelineToStringStorage(timeline.getListTimeline())); - try{ + try { db.insert(Sqlite.TABLE_TIMELINES, null, values); - }catch (Exception ignored) {} + } catch (Exception ignored) { + } } //------- REMOVE ------- - public int remove(ManageTimelines timeline){ - return db.delete(Sqlite.TABLE_TIMELINES, Sqlite.COL_ID + " = \"" + timeline.getId() + "\"", null); + public int remove(ManageTimelines timeline) { + return db.delete(Sqlite.TABLE_TIMELINES, Sqlite.COL_ID + " = \"" + timeline.getId() + "\"", null); } //------- REMOVE ------- - public int removeAll(){ + public int removeAll() { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); - return db.delete(Sqlite.TABLE_TIMELINES, Sqlite.COL_USER_ID + " = '" + userId+ "' AND " + Sqlite.COL_INSTANCE + " = '" + instance+ "'", null); + return db.delete(Sqlite.TABLE_TIMELINES, Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "'", null); } //------- UPDATE ------- @@ -88,7 +89,7 @@ public class TimelinesDAO { public void updateTag(ManageTimelines timeline) { ContentValues values = new ContentValues(); values.put(Sqlite.COL_DISPLAYED, timeline.isDisplayed()); - if( timeline.getTagTimeline() != null) + if (timeline.getTagTimeline() != null) values.put(Sqlite.COL_TAG_TIMELINE, Helper.tagTimelineToStringStorage(timeline.getTagTimeline())); db.update(Sqlite.TABLE_TIMELINES, values, Sqlite.COL_ID + " = ? ", @@ -99,43 +100,43 @@ public class TimelinesDAO { public void updateRemoteInstance(ManageTimelines timeline) { ContentValues values = new ContentValues(); values.put(Sqlite.COL_DISPLAYED, timeline.isDisplayed()); - if( timeline.getTagTimeline() != null) + if (timeline.getTagTimeline() != null) values.put(Sqlite.COL_REMOTE_INSTANCE, Helper.remoteInstanceToStringStorage(timeline.getRemoteInstance())); db.update(Sqlite.TABLE_TIMELINES, values, Sqlite.COL_ID + " = ? ", new String[]{String.valueOf(timeline.getId())}); } - public int countVisibleTimelines(){ + public int countVisibleTimelines() { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); - Cursor mCount= db.rawQuery("select count(*) from " + Sqlite.TABLE_TIMELINES - + " where " + Sqlite.COL_USER_ID + " = '" + userId+ "' AND " + Sqlite.COL_INSTANCE + " = '" + instance+ "' AND " + Sqlite.COL_DISPLAYED + "= 1", null); + Cursor mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_TIMELINES + + " where " + Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_DISPLAYED + "= 1", null); mCount.moveToFirst(); int count = mCount.getInt(0); mCount.close(); return count; } - public List getAllTimelines(){ + public List getAllTimelines() { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); try { - Cursor c = db.query(Sqlite.TABLE_TIMELINES, null, Sqlite.COL_USER_ID + " = '" + userId+ "' AND " + Sqlite.COL_INSTANCE + " = '" + instance+ "'", null, null, null, Sqlite.COL_POSITION + " ASC", null); + Cursor c = db.query(Sqlite.TABLE_TIMELINES, null, Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "'", null, null, null, Sqlite.COL_POSITION + " ASC", null); return cursorToTimelines(c); } catch (Exception e) { return null; } } - public List getDisplayedTimelines(){ + public List getDisplayedTimelines() { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = Helper.getLiveInstance(context); try { - Cursor c = db.query(Sqlite.TABLE_TIMELINES, null, Sqlite.COL_USER_ID + " = '" + userId+ "' AND " + Sqlite.COL_INSTANCE + " = '" + instance+ "' AND " + Sqlite.COL_DISPLAYED + " = '1'", null, null, null, Sqlite.COL_POSITION + " ASC", null); + Cursor c = db.query(Sqlite.TABLE_TIMELINES, null, Sqlite.COL_USER_ID + " = '" + userId + "' AND " + Sqlite.COL_INSTANCE + " = '" + instance + "' AND " + Sqlite.COL_DISPLAYED + " = '1'", null, null, null, Sqlite.COL_POSITION + " ASC", null); return cursorToTimelines(c); } catch (Exception e) { return null; @@ -143,9 +144,9 @@ public class TimelinesDAO { } - public ManageTimelines getById(int id){ + public ManageTimelines getById(int id) { try { - Cursor c = db.query(Sqlite.TABLE_TIMELINES, null, Sqlite.COL_ID + " = '" + id+ "'", null, null, null, Sqlite.COL_POSITION + " ASC", null); + Cursor c = db.query(Sqlite.TABLE_TIMELINES, null, Sqlite.COL_ID + " = '" + id + "'", null, null, null, Sqlite.COL_POSITION + " ASC", null); return cursorToTimeline(c); } catch (Exception e) { return null; @@ -158,7 +159,7 @@ public class TimelinesDAO { * @param c Cursor * @return ManageTimelines */ - private ManageTimelines cursorToTimeline(Cursor c){ + private ManageTimelines cursorToTimeline(Cursor c) { //No element found if (c.getCount() == 0) { c.close(); @@ -171,11 +172,11 @@ public class TimelinesDAO { manageTimelines.setId(c.getInt(c.getColumnIndex(Sqlite.COL_ID))); manageTimelines.setDisplayed(c.getInt(c.getColumnIndex(Sqlite.COL_DISPLAYED)) == 1); manageTimelines.setPosition(c.getInt(c.getColumnIndex(Sqlite.COL_POSITION))); - if( c.getString(c.getColumnIndex(Sqlite.COL_TAG_TIMELINE)) != null ) + if (c.getString(c.getColumnIndex(Sqlite.COL_TAG_TIMELINE)) != null) manageTimelines.setTagTimeline(Helper.restoreTagTimelineFromString(c.getString(c.getColumnIndex(Sqlite.COL_TAG_TIMELINE)))); - if( c.getString(c.getColumnIndex(Sqlite.COL_REMOTE_INSTANCE)) != null ) + if (c.getString(c.getColumnIndex(Sqlite.COL_REMOTE_INSTANCE)) != null) manageTimelines.setRemoteInstance(Helper.restoreRemoteInstanceFromString(c.getString(c.getColumnIndex(Sqlite.COL_REMOTE_INSTANCE)))); - if( c.getString(c.getColumnIndex(Sqlite.COL_LIST_TIMELINE)) != null ) + if (c.getString(c.getColumnIndex(Sqlite.COL_LIST_TIMELINE)) != null) manageTimelines.setListTimeline(Helper.restoreListtimelineFromString(c.getString(c.getColumnIndex(Sqlite.COL_LIST_TIMELINE)))); manageTimelines.setType(ManageTimelines.typeFromDb(c.getString(c.getColumnIndex(Sqlite.COL_TYPE)))); //Close the cursor @@ -190,24 +191,24 @@ public class TimelinesDAO { * @param c Cursor * @return List */ - private List cursorToTimelines(Cursor c){ + private List cursorToTimelines(Cursor c) { //No element found if (c.getCount() == 0) { c.close(); return null; } List remoteInstances = new ArrayList<>(); - while (c.moveToNext() ) { + while (c.moveToNext()) { ManageTimelines manageTimelines = new ManageTimelines(); manageTimelines.setId(c.getInt(c.getColumnIndex(Sqlite.COL_ID))); manageTimelines.setDisplayed(c.getInt(c.getColumnIndex(Sqlite.COL_DISPLAYED)) == 1); manageTimelines.setPosition(c.getInt(c.getColumnIndex(Sqlite.COL_POSITION))); - if( c.getString(c.getColumnIndex(Sqlite.COL_TAG_TIMELINE)) != null ) + if (c.getString(c.getColumnIndex(Sqlite.COL_TAG_TIMELINE)) != null) manageTimelines.setTagTimeline(Helper.restoreTagTimelineFromString(c.getString(c.getColumnIndex(Sqlite.COL_TAG_TIMELINE)))); - if( c.getString(c.getColumnIndex(Sqlite.COL_REMOTE_INSTANCE)) != null ) + if (c.getString(c.getColumnIndex(Sqlite.COL_REMOTE_INSTANCE)) != null) manageTimelines.setRemoteInstance(Helper.restoreRemoteInstanceFromString(c.getString(c.getColumnIndex(Sqlite.COL_REMOTE_INSTANCE)))); - if( c.getString(c.getColumnIndex(Sqlite.COL_LIST_TIMELINE)) != null ) + if (c.getString(c.getColumnIndex(Sqlite.COL_LIST_TIMELINE)) != null) manageTimelines.setListTimeline(Helper.restoreListtimelineFromString(c.getString(c.getColumnIndex(Sqlite.COL_LIST_TIMELINE)))); manageTimelines.setType(ManageTimelines.typeFromDb(c.getString(c.getColumnIndex(Sqlite.COL_TYPE)))); remoteInstances.add(manageTimelines); diff --git a/app/src/main/java/app/fedilab/android/webview/MastalabWebChromeClient.java b/app/src/main/java/app/fedilab/android/webview/MastalabWebChromeClient.java index f05a14d90..b240072c3 100644 --- a/app/src/main/java/app/fedilab/android/webview/MastalabWebChromeClient.java +++ b/app/src/main/java/app/fedilab/android/webview/MastalabWebChromeClient.java @@ -13,12 +13,15 @@ package app.fedilab.android.webview; * * You should have received a copy of the GNU General Public License along with Fedilab; if not, * see . */ + import android.annotation.SuppressLint; import android.app.Activity; import android.graphics.Bitmap; import android.media.MediaPlayer; + import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; + import android.view.LayoutInflater; import android.view.SurfaceView; import android.view.View; @@ -40,73 +43,74 @@ import app.fedilab.android.R; public class MastalabWebChromeClient extends WebChromeClient implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener { - private FrameLayout videoViewContainer; - private WebChromeClient.CustomViewCallback videoViewCallback; + private FrameLayout videoViewContainer; + private WebChromeClient.CustomViewCallback videoViewCallback; - private ToggledFullscreenCallback toggledFullscreenCallback; + private ToggledFullscreenCallback toggledFullscreenCallback; - private WebView webView; - private View activityNonVideoView; - private ViewGroup activityVideoView; - private ProgressBar pbar; - private boolean isVideoFullscreen; - private Activity activity; + private WebView webView; + private View activityNonVideoView; + private ViewGroup activityVideoView; + private ProgressBar pbar; + private boolean isVideoFullscreen; + private Activity activity; - public interface ToggledFullscreenCallback { - void toggledFullscreen(boolean fullscreen); - } + public interface ToggledFullscreenCallback { + void toggledFullscreen(boolean fullscreen); + } - public MastalabWebChromeClient(Activity activity, WebView webView, FrameLayout activityNonVideoView, ViewGroup activityVideoView){ - this.activity = activity; - this.isVideoFullscreen = false; - this.webView = webView; - this.pbar = activity.findViewById(R.id.progress_bar); - this.activityNonVideoView = activityNonVideoView; - this.activityVideoView = activityVideoView; - } + public MastalabWebChromeClient(Activity activity, WebView webView, FrameLayout activityNonVideoView, ViewGroup activityVideoView) { + this.activity = activity; + this.isVideoFullscreen = false; + this.webView = webView; + this.pbar = activity.findViewById(R.id.progress_bar); + this.activityNonVideoView = activityNonVideoView; + this.activityVideoView = activityVideoView; + } - @Override - public void onProgressChanged(WebView view, int progress) { - if( pbar != null){ - if (progress < 100 && pbar.getVisibility() == ProgressBar.GONE) { - pbar.setVisibility(ProgressBar.VISIBLE); - } - pbar.setProgress(progress); - if (progress == 100) { - pbar.setVisibility(ProgressBar.GONE); - } + @Override + public void onProgressChanged(WebView view, int progress) { + if (pbar != null) { + if (progress < 100 && pbar.getVisibility() == ProgressBar.GONE) { + pbar.setVisibility(ProgressBar.VISIBLE); + } + pbar.setProgress(progress); + if (progress == 100) { + pbar.setVisibility(ProgressBar.GONE); } } + } - @Override - public void onReceivedIcon(WebView view, Bitmap icon) { - super.onReceivedIcon(view, icon); - LayoutInflater mInflater = LayoutInflater.from(activity); - ActionBar actionBar = ((AppCompatActivity) activity).getSupportActionBar(); - if( actionBar != null){ - View webview_actionbar = mInflater.inflate(R.layout.webview_actionbar, new LinearLayout(activity), false); - TextView webview_title = webview_actionbar.findViewById(R.id.webview_title); - webview_title.setText(view.getTitle()); - ImageView webview_favicon = webview_actionbar.findViewById(R.id.webview_favicon); - if( icon != null) - webview_favicon.setImageBitmap(icon); - actionBar.setCustomView(webview_actionbar); - actionBar.setDisplayShowCustomEnabled(true); - }else { - activity.setTitle(view.getTitle()); - } - + @Override + public void onReceivedIcon(WebView view, Bitmap icon) { + super.onReceivedIcon(view, icon); + LayoutInflater mInflater = LayoutInflater.from(activity); + ActionBar actionBar = ((AppCompatActivity) activity).getSupportActionBar(); + if (actionBar != null) { + View webview_actionbar = mInflater.inflate(R.layout.webview_actionbar, new LinearLayout(activity), false); + TextView webview_title = webview_actionbar.findViewById(R.id.webview_title); + webview_title.setText(view.getTitle()); + ImageView webview_favicon = webview_actionbar.findViewById(R.id.webview_favicon); + if (icon != null) + webview_favicon.setImageBitmap(icon); + actionBar.setCustomView(webview_actionbar); + actionBar.setDisplayShowCustomEnabled(true); + } else { + activity.setTitle(view.getTitle()); } - //FULLSCREEN VIDEO - //Code from https://stackoverflow.com/a/16179544/3197259 + } - /** - * Set a callback that will be fired when the video starts or finishes displaying using a custom view (typically full-screen) - * @param callback A VideoEnabledWebChromeClient.ToggledFullscreenCallback callback - */ + //FULLSCREEN VIDEO + //Code from https://stackoverflow.com/a/16179544/3197259 + + /** + * Set a callback that will be fired when the video starts or finishes displaying using a custom view (typically full-screen) + * + * @param callback A VideoEnabledWebChromeClient.ToggledFullscreenCallback callback + */ public void setOnToggledFullscreen(ToggledFullscreenCallback callback) { this.toggledFullscreenCallback = callback; } @@ -114,7 +118,7 @@ public class MastalabWebChromeClient extends WebChromeClient implements MediaPla @Override public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) { if (view instanceof FrameLayout) { - if( ((AppCompatActivity) activity).getSupportActionBar() != null) + if (((AppCompatActivity) activity).getSupportActionBar() != null) //noinspection ConstantConditions ((AppCompatActivity) activity).getSupportActionBar().hide(); // A video wants to be shown @@ -171,14 +175,15 @@ public class MastalabWebChromeClient extends WebChromeClient implements MediaPla } // Available in API level 14+, deprecated in API level 18+ - @Override @SuppressWarnings("deprecation") + @Override + @SuppressWarnings("deprecation") public void onShowCustomView(View view, int requestedOrientation, WebChromeClient.CustomViewCallback callback) { onShowCustomView(view, callback); } @Override public void onHideCustomView() { - if( ((AppCompatActivity) activity).getSupportActionBar() != null) + 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. diff --git a/app/src/main/java/app/fedilab/android/webview/MastalabWebViewClient.java b/app/src/main/java/app/fedilab/android/webview/MastalabWebViewClient.java index 896847bb2..f4cd20a4c 100644 --- a/app/src/main/java/app/fedilab/android/webview/MastalabWebViewClient.java +++ b/app/src/main/java/app/fedilab/android/webview/MastalabWebViewClient.java @@ -18,8 +18,10 @@ package app.fedilab.android.webview; import android.app.Activity; import android.graphics.Bitmap; import android.net.http.SslError; + import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; + import android.view.LayoutInflater; import android.view.View; import android.webkit.SslErrorHandler; @@ -50,10 +52,12 @@ public class MastalabWebViewClient extends WebViewClient { private Activity activity; private int count = 0; - public MastalabWebViewClient(Activity activity){ + public MastalabWebViewClient(Activity activity) { this.activity = activity; } + public List domains = new ArrayList<>(); + @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); @@ -61,22 +65,22 @@ public class MastalabWebViewClient extends WebViewClient { @Override - public WebResourceResponse shouldInterceptRequest (final WebView view, String url) { - if( WebviewActivity.trackingDomains != null){ + public WebResourceResponse shouldInterceptRequest(final WebView view, String url) { + if (WebviewActivity.trackingDomains != null) { URI uri; try { uri = new URI(url); String domain = uri.getHost(); - if( domain != null) { + if (domain != null) { domain = domain.startsWith("www.") ? domain.substring(4) : domain; } if (domain != null && WebviewActivity.trackingDomains.contains(domain)) { - if( activity instanceof WebviewActivity){ + if (activity instanceof WebviewActivity) { count++; domains.add(url); - ((WebviewActivity)activity).setCount(activity, String.valueOf(count)); + ((WebviewActivity) activity).setCount(activity, String.valueOf(count)); } - ByteArrayInputStream nothing = new ByteArrayInputStream("".getBytes()); + ByteArrayInputStream nothing = new ByteArrayInputStream("".getBytes()); return new WebResourceResponse("text/plain", "utf-8", nothing); } } catch (URISyntaxException e) { @@ -105,25 +109,25 @@ public class MastalabWebViewClient extends WebViewClient { return super.shouldInterceptRequest(view, url); } - public List getDomains(){ + public List getDomains() { return this.domains; } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { String instance = Helper.getLiveInstance(activity); - if( instance != null && instance.endsWith(".onion")) { + if (instance != null && instance.endsWith(".onion")) { handler.proceed(); - }else{ + } else { super.onReceivedSslError(view, handler, error); } } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { - if( URLUtil.isNetworkUrl(url) ) { + if (URLUtil.isNetworkUrl(url)) { return false; - }else{ + } else { view.stopLoading(); view.goBack(); } @@ -131,27 +135,28 @@ public class MastalabWebViewClient extends WebViewClient { } @Override - public void onPageStarted (WebView view, String url, Bitmap favicon) { + public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); count = 0; domains = new ArrayList<>(); domains.clear(); ActionBar actionBar = ((AppCompatActivity) activity).getSupportActionBar(); LayoutInflater mInflater = LayoutInflater.from(activity); - if( actionBar != null){ - View webview_actionbar = mInflater.inflate(R.layout.webview_actionbar, new LinearLayout(activity), false); + if (actionBar != null) { + View webview_actionbar = mInflater.inflate(R.layout.webview_actionbar, new LinearLayout(activity), false); TextView webview_title = webview_actionbar.findViewById(R.id.webview_title); webview_title.setText(url); actionBar.setCustomView(webview_actionbar); actionBar.setDisplayShowCustomEnabled(true); - }else { + } else { activity.setTitle(url); } //Changes the url in webview activity so that it can be opened with an external app - try{ - if( activity instanceof WebviewActivity) - ((WebviewActivity)activity).setUrl(url); - }catch (Exception ignore){} + try { + if (activity instanceof WebviewActivity) + ((WebviewActivity) activity).setUrl(url); + } catch (Exception ignore) { + } } diff --git a/app/src/main/java/app/fedilab/android/webview/ProxyHelper.java b/app/src/main/java/app/fedilab/android/webview/ProxyHelper.java index f93caf6df..033797868 100644 --- a/app/src/main/java/app/fedilab/android/webview/ProxyHelper.java +++ b/app/src/main/java/app/fedilab/android/webview/ProxyHelper.java @@ -13,6 +13,7 @@ package app.fedilab.android.webview; * * You should have received a copy of the GNU General Public License along with Fedilab; if not, * see . */ + import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; @@ -30,23 +31,21 @@ import java.lang.reflect.Method; public class ProxyHelper { - public static void setProxy(Context context, WebView webview, String host, int port, String applicationClassName) { if (Build.VERSION.SDK_INT <= 18) { - setProxyJB(webview, host, port); + setProxyJB(webview, host, port); } // 4.4 (KK) & 5.0 (Lollipop) else { - setProxyKKPlus(context, webview, host, port, applicationClassName); + setProxyKKPlus(context, webview, host, port, applicationClassName); } } @SuppressWarnings("all") private static boolean setProxyICS(WebView webview, String host, int port) { - try - { + try { Class jwcjb = Class.forName("android.webkit.JWebCoreJavaBridge"); Class params[] = new Class[1]; params[0] = Class.forName("android.net.ProxyProperties"); @@ -73,8 +72,7 @@ public class ProxyHelper { updateProxyInstance.invoke(sJavaBridge, ppcont.newInstance(host, port, null)); return true; - } - catch (Exception ex) { + } catch (Exception ex) { return false; } } diff --git a/app/src/main/res/anim/enter_from_left.xml b/app/src/main/res/anim/enter_from_left.xml index b4d93d925..9f125e05f 100644 --- a/app/src/main/res/anim/enter_from_left.xml +++ b/app/src/main/res/anim/enter_from_left.xml @@ -2,7 +2,9 @@ + android:fromXDelta="-100%" + android:toXDelta="0%" + android:fromYDelta="0%" + android:toYDelta="0%" + android:duration="300" /> \ No newline at end of file diff --git a/app/src/main/res/anim/enter_from_right.xml b/app/src/main/res/anim/enter_from_right.xml index aaed2a84f..735ae4224 100644 --- a/app/src/main/res/anim/enter_from_right.xml +++ b/app/src/main/res/anim/enter_from_right.xml @@ -2,7 +2,9 @@ \ No newline at end of file diff --git a/app/src/main/res/anim/exit_to_left.xml b/app/src/main/res/anim/exit_to_left.xml index 2533835ea..44e65a752 100644 --- a/app/src/main/res/anim/exit_to_left.xml +++ b/app/src/main/res/anim/exit_to_left.xml @@ -2,7 +2,9 @@ + android:fromXDelta="0%" + android:toXDelta="-100%" + android:fromYDelta="0%" + android:toYDelta="0%" + android:duration="300" /> \ No newline at end of file diff --git a/app/src/main/res/anim/exit_to_right.xml b/app/src/main/res/anim/exit_to_right.xml index 1d299d849..6c68a61b7 100644 --- a/app/src/main/res/anim/exit_to_right.xml +++ b/app/src/main/res/anim/exit_to_right.xml @@ -2,7 +2,9 @@ \ No newline at end of file diff --git a/app/src/main/res/anim/fadein.xml b/app/src/main/res/anim/fadein.xml index 40560da83..fe9e8b96a 100644 --- a/app/src/main/res/anim/fadein.xml +++ b/app/src/main/res/anim/fadein.xml @@ -3,6 +3,5 @@ + android:duration="1000" /> \ No newline at end of file diff --git a/app/src/main/res/anim/fadeout.xml b/app/src/main/res/anim/fadeout.xml index 69e4eedb0..77de55f71 100644 --- a/app/src/main/res/anim/fadeout.xml +++ b/app/src/main/res/anim/fadeout.xml @@ -3,6 +3,5 @@ + android:duration="1000" /> \ No newline at end of file diff --git a/app/src/main/res/drawable-anydpi/ic_add.xml b/app/src/main/res/drawable-anydpi/ic_add.xml index b9b8eca8b..d29480261 100644 --- a/app/src/main/res/drawable-anydpi/ic_add.xml +++ b/app/src/main/res/drawable-anydpi/ic_add.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_add_instance.xml b/app/src/main/res/drawable-anydpi/ic_add_instance.xml index f88ddb1d5..3720a72a8 100644 --- a/app/src/main/res/drawable-anydpi/ic_add_instance.xml +++ b/app/src/main/res/drawable-anydpi/ic_add_instance.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM17,13h-4v4h-2v-4L7,13v-2h4L11,7h2v4h4v2z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_arrow_drop_down.xml b/app/src/main/res/drawable-anydpi/ic_arrow_drop_down.xml index b82186765..588d26403 100644 --- a/app/src/main/res/drawable-anydpi/ic_arrow_drop_down.xml +++ b/app/src/main/res/drawable-anydpi/ic_arrow_drop_down.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M7,10l5,5 5,-5z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_arrow_drop_up.xml b/app/src/main/res/drawable-anydpi/ic_arrow_drop_up.xml index c63c8c652..2a2ceba52 100644 --- a/app/src/main/res/drawable-anydpi/ic_arrow_drop_up.xml +++ b/app/src/main/res/drawable-anydpi/ic_arrow_drop_up.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M7,14l5,-5 5,5z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_attach_money.xml b/app/src/main/res/drawable-anydpi/ic_attach_money.xml index b520fc98d..dd93a7599 100644 --- a/app/src/main/res/drawable-anydpi/ic_attach_money.xml +++ b/app/src/main/res/drawable-anydpi/ic_attach_money.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M11.8,10.9c-2.27,-0.59 -3,-1.2 -3,-2.15 0,-1.09 1.01,-1.85 2.7,-1.85 1.78,0 2.44,0.85 2.5,2.1h2.21c-0.07,-1.72 -1.12,-3.3 -3.21,-3.81V3h-3v2.16c-1.94,0.42 -3.5,1.68 -3.5,3.61 0,2.31 1.91,3.46 4.7,4.13 2.5,0.6 3,1.48 3,2.41 0,0.69 -0.49,1.79 -2.7,1.79 -2.06,0 -2.87,-0.92 -2.98,-2.1h-2.2c0.12,2.19 1.76,3.42 3.68,3.83V21h3v-2.15c1.95,-0.37 3.5,-1.5 3.5,-3.55 0,-2.84 -2.43,-3.81 -4.7,-4.4z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_back.xml b/app/src/main/res/drawable-anydpi/ic_back.xml index 26abc5351..d04b3cbb4 100644 --- a/app/src/main/res/drawable-anydpi/ic_back.xml +++ b/app/src/main/res/drawable-anydpi/ic_back.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_block.xml b/app/src/main/res/drawable-anydpi/ic_block.xml index 9a8d0b88e..5247c31e4 100644 --- a/app/src/main/res/drawable-anydpi/ic_block.xml +++ b/app/src/main/res/drawable-anydpi/ic_block.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM4,12c0,-4.42 3.58,-8 8,-8 1.85,0 3.55,0.63 4.9,1.69L5.69,16.9C4.63,15.55 4,13.85 4,12zM12,20c-1.85,0 -3.55,-0.63 -4.9,-1.69L18.31,7.1C19.37,8.45 20,10.15 20,12c0,4.42 -3.58,8 -8,8z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_block_script.xml b/app/src/main/res/drawable-anydpi/ic_block_script.xml index 9a8d0b88e..5247c31e4 100644 --- a/app/src/main/res/drawable-anydpi/ic_block_script.xml +++ b/app/src/main/res/drawable-anydpi/ic_block_script.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM4,12c0,-4.42 3.58,-8 8,-8 1.85,0 3.55,0.63 4.9,1.69L5.69,16.9C4.63,15.55 4,13.85 4,12zM12,20c-1.85,0 -3.55,-0.63 -4.9,-1.69L18.31,7.1C19.37,8.45 20,10.15 20,12c0,4.42 -3.58,8 -8,8z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_bookmark_menu.xml b/app/src/main/res/drawable-anydpi/ic_bookmark_menu.xml index 6a6a1b39d..5bf2e951c 100644 --- a/app/src/main/res/drawable-anydpi/ic_bookmark_menu.xml +++ b/app/src/main/res/drawable-anydpi/ic_bookmark_menu.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M17,3H7c-1.1,0 -1.99,0.9 -1.99,2L5,21l7,-3 7,3V5c0,-1.1 -0.9,-2 -2,-2z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_bookmark_peertube.xml b/app/src/main/res/drawable-anydpi/ic_bookmark_peertube.xml index b8c26706c..3684c66d7 100644 --- a/app/src/main/res/drawable-anydpi/ic_bookmark_peertube.xml +++ b/app/src/main/res/drawable-anydpi/ic_bookmark_peertube.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,21.35l-1.45,-1.32C5.4,15.36 2,12.28 2,8.5 2,5.42 4.42,3 7.5,3c1.74,0 3.41,0.81 4.5,2.09C13.09,3.81 14.76,3 16.5,3 19.58,3 22,5.42 22,8.5c0,3.78 -3.4,6.86 -8.55,11.54L12,21.35z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_bookmark_peertube_border.xml b/app/src/main/res/drawable-anydpi/ic_bookmark_peertube_border.xml index 1348ada67..9fc59ba5b 100644 --- a/app/src/main/res/drawable-anydpi/ic_bookmark_peertube_border.xml +++ b/app/src/main/res/drawable-anydpi/ic_bookmark_peertube_border.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M16.5,3c-1.74,0 -3.41,0.81 -4.5,2.09C10.91,3.81 9.24,3 7.5,3 4.42,3 2,5.42 2,8.5c0,3.78 3.4,6.86 8.55,11.54L12,21.35l1.45,-1.32C18.6,15.36 22,12.28 22,8.5 22,5.42 19.58,3 16.5,3zM12.1,18.55l-0.1,0.1 -0.1,-0.1C7.14,14.24 4,11.39 4,8.5 4,6.5 5.5,5 7.5,5c1.54,0 3.04,0.99 3.57,2.36h1.87C13.46,5.99 14.96,5 16.5,5c2,0 3.5,1.5 3.5,3.5 0,2.89 -3.14,5.74 -7.9,10.05z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_boost_pixelfed.xml b/app/src/main/res/drawable-anydpi/ic_boost_pixelfed.xml index e7c67d710..a10f3b451 100644 --- a/app/src/main/res/drawable-anydpi/ic_boost_pixelfed.xml +++ b/app/src/main/res/drawable-anydpi/ic_boost_pixelfed.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M7,7h10v3l4,-4 -4,-4v3L5,5v6h2L7,7zM17,17L7,17v-3l-4,4 4,4v-3h12v-6h-2v4z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_brush.xml b/app/src/main/res/drawable-anydpi/ic_brush.xml index 54730dbe2..4e5affa20 100644 --- a/app/src/main/res/drawable-anydpi/ic_brush.xml +++ b/app/src/main/res/drawable-anydpi/ic_brush.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M7,14c-1.66,0 -3,1.34 -3,3 0,1.31 -1.16,2 -2,2 0.92,1.22 2.49,2 4,2 2.21,0 4,-1.79 4,-4 0,-1.66 -1.34,-3 -3,-3zM20.71,4.63l-1.34,-1.34c-0.39,-0.39 -1.02,-0.39 -1.41,0L9,12.25 11.75,15l8.96,-8.96c0.39,-0.39 0.39,-1.02 0,-1.41z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_brush_white.xml b/app/src/main/res/drawable-anydpi/ic_brush_white.xml index 500cb4a5f..461cc1de7 100644 --- a/app/src/main/res/drawable-anydpi/ic_brush_white.xml +++ b/app/src/main/res/drawable-anydpi/ic_brush_white.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M7,14c-1.66,0 -3,1.34 -3,3 0,1.31 -1.16,2 -2,2 0.92,1.22 2.49,2 4,2 2.21,0 4,-1.79 4,-4 0,-1.66 -1.34,-3 -3,-3zM20.71,4.63l-1.34,-1.34c-0.39,-0.39 -1.02,-0.39 -1.41,0L9,12.25 11.75,15l8.96,-8.96c0.39,-0.39 0.39,-1.02 0,-1.41z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_bug_report.xml b/app/src/main/res/drawable-anydpi/ic_bug_report.xml index 4d83902b8..206702ff2 100644 --- a/app/src/main/res/drawable-anydpi/ic_bug_report.xml +++ b/app/src/main/res/drawable-anydpi/ic_bug_report.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M20,8h-2.81c-0.45,-0.78 -1.07,-1.45 -1.82,-1.96L17,4.41 15.59,3l-2.17,2.17C12.96,5.06 12.49,5 12,5c-0.49,0 -0.96,0.06 -1.41,0.17L8.41,3 7,4.41l1.62,1.63C7.88,6.55 7.26,7.22 6.81,8L4,8v2h2.09c-0.05,0.33 -0.09,0.66 -0.09,1v1L4,12v2h2v1c0,0.34 0.04,0.67 0.09,1L4,16v2h2.81c1.04,1.79 2.97,3 5.19,3s4.15,-1.21 5.19,-3L20,18v-2h-2.09c0.05,-0.33 0.09,-0.66 0.09,-1v-1h2v-2h-2v-1c0,-0.34 -0.04,-0.67 -0.09,-1L20,10L20,8zM14,16h-4v-2h4v2zM14,12h-4v-2h4v2z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_cancel.xml b/app/src/main/res/drawable-anydpi/ic_cancel.xml index 7d2b57eb2..85166f175 100644 --- a/app/src/main/res/drawable-anydpi/ic_cancel.xml +++ b/app/src/main/res/drawable-anydpi/ic_cancel.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,2C6.47,2 2,6.47 2,12s4.47,10 10,10 10,-4.47 10,-10S17.53,2 12,2zM17,15.59L15.59,17 12,13.41 8.41,17 7,15.59 10.59,12 7,8.41 8.41,7 12,10.59 15.59,7 17,8.41 13.41,12 17,15.59z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_card_travel.xml b/app/src/main/res/drawable-anydpi/ic_card_travel.xml index 29cd27ee2..727736e37 100644 --- a/app/src/main/res/drawable-anydpi/ic_card_travel.xml +++ b/app/src/main/res/drawable-anydpi/ic_card_travel.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M20,6h-3L17,4c0,-1.11 -0.89,-2 -2,-2L9,2c-1.11,0 -2,0.89 -2,2v2L4,6c-1.11,0 -2,0.89 -2,2v11c0,1.11 0.89,2 2,2h16c1.11,0 2,-0.89 2,-2L22,8c0,-1.11 -0.89,-2 -2,-2zM9,4h6v2L9,6L9,4zM20,19L4,19v-2h16v2zM20,14L4,14L4,8h3v2h2L9,8h6v2h2L17,8h3v6z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_chat_bubble_outline.xml b/app/src/main/res/drawable-anydpi/ic_chat_bubble_outline.xml index 880a1b1a9..6b23f94a9 100644 --- a/app/src/main/res/drawable-anydpi/ic_chat_bubble_outline.xml +++ b/app/src/main/res/drawable-anydpi/ic_chat_bubble_outline.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M20,2L4,2c-1.1,0 -2,0.9 -2,2v18l4,-4h14c1.1,0 2,-0.9 2,-2L22,4c0,-1.1 -0.9,-2 -2,-2zM20,16L6,16l-2,2L4,4h16v12z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_check.xml b/app/src/main/res/drawable-anydpi/ic_check.xml index 3c728c59f..620bc9133 100644 --- a/app/src/main/res/drawable-anydpi/ic_check.xml +++ b/app/src/main/res/drawable-anydpi/ic_check.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M9,16.17L4.83,12l-1.42,1.41L9,19 21,7l-1.41,-1.41z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_clear_toot.xml b/app/src/main/res/drawable-anydpi/ic_clear_toot.xml index ede4b7108..f50fd991b 100644 --- a/app/src/main/res/drawable-anydpi/ic_clear_toot.xml +++ b/app/src/main/res/drawable-anydpi/ic_clear_toot.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M19,6.41L17.59,5 12,10.59 6.41,5 5,6.41 10.59,12 5,17.59 6.41,19 12,13.41 17.59,19 19,17.59 13.41,12z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_close.xml b/app/src/main/res/drawable-anydpi/ic_close.xml index d11cc5c9c..c63eeb597 100644 --- a/app/src/main/res/drawable-anydpi/ic_close.xml +++ b/app/src/main/res/drawable-anydpi/ic_close.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M19,6.41L17.59,5 12,10.59 6.41,5 5,6.41 10.59,12 5,17.59 6.41,19 12,13.41 17.59,19 19,17.59 13.41,12z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_cloud_download_peertube.xml b/app/src/main/res/drawable-anydpi/ic_cloud_download_peertube.xml index d11e9d8d2..95710602a 100644 --- a/app/src/main/res/drawable-anydpi/ic_cloud_download_peertube.xml +++ b/app/src/main/res/drawable-anydpi/ic_cloud_download_peertube.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M19.35,10.04C18.67,6.59 15.64,4 12,4 9.11,4 6.6,5.64 5.35,8.04 2.34,8.36 0,10.91 0,14c0,3.31 2.69,6 6,6h13c2.76,0 5,-2.24 5,-5 0,-2.64 -2.05,-4.78 -4.65,-4.96zM17,13l-5,5 -5,-5h3V9h4v4h3z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_color_lens.xml b/app/src/main/res/drawable-anydpi/ic_color_lens.xml index f75e2fbe3..71c37ddac 100644 --- a/app/src/main/res/drawable-anydpi/ic_color_lens.xml +++ b/app/src/main/res/drawable-anydpi/ic_color_lens.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,3c-4.97,0 -9,4.03 -9,9s4.03,9 9,9c0.83,0 1.5,-0.67 1.5,-1.5 0,-0.39 -0.15,-0.74 -0.39,-1.01 -0.23,-0.26 -0.38,-0.61 -0.38,-0.99 0,-0.83 0.67,-1.5 1.5,-1.5L16,16c2.76,0 5,-2.24 5,-5 0,-4.42 -4.03,-8 -9,-8zM6.5,12c-0.83,0 -1.5,-0.67 -1.5,-1.5S5.67,9 6.5,9 8,9.67 8,10.5 7.33,12 6.5,12zM9.5,8C8.67,8 8,7.33 8,6.5S8.67,5 9.5,5s1.5,0.67 1.5,1.5S10.33,8 9.5,8zM14.5,8c-0.83,0 -1.5,-0.67 -1.5,-1.5S13.67,5 14.5,5s1.5,0.67 1.5,1.5S15.33,8 14.5,8zM17.5,12c-0.83,0 -1.5,-0.67 -1.5,-1.5S16.67,9 17.5,9s1.5,0.67 1.5,1.5 -0.67,1.5 -1.5,1.5z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_contacts.xml b/app/src/main/res/drawable-anydpi/ic_contacts.xml index fbcf8c2bf..6e592b467 100644 --- a/app/src/main/res/drawable-anydpi/ic_contacts.xml +++ b/app/src/main/res/drawable-anydpi/ic_contacts.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M20,0L4,0v2h16L20,0zM4,24h16v-2L4,22v2zM20,4L4,4c-1.1,0 -2,0.9 -2,2v12c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2L22,6c0,-1.1 -0.9,-2 -2,-2zM12,6.75c1.24,0 2.25,1.01 2.25,2.25s-1.01,2.25 -2.25,2.25S9.75,10.24 9.75,9 10.76,6.75 12,6.75zM17,17L7,17v-1.5c0,-1.67 3.33,-2.5 5,-2.5s5,0.83 5,2.5L17,17z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_conversation.xml b/app/src/main/res/drawable-anydpi/ic_conversation.xml index 26eda0900..4932df431 100644 --- a/app/src/main/res/drawable-anydpi/ic_conversation.xml +++ b/app/src/main/res/drawable-anydpi/ic_conversation.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M21,6h-2v9L6,15v2c0,0.55 0.45,1 1,1h11l4,4L22,7c0,-0.55 -0.45,-1 -1,-1zM17,12L17,3c0,-0.55 -0.45,-1 -1,-1L3,2c-0.55,0 -1,0.45 -1,1v14l4,-4h10c0.55,0 1,-0.45 1,-1z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_delete.xml b/app/src/main/res/drawable-anydpi/ic_delete.xml index f9213d2b5..1014e3d92 100644 --- a/app/src/main/res/drawable-anydpi/ic_delete.xml +++ b/app/src/main/res/drawable-anydpi/ic_delete.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M6,19c0,1.1 0.9,2 2,2h8c1.1,0 2,-0.9 2,-2V7H6v12zM19,4h-3.5l-1,-1h-5l-1,1H5v2h14V4z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_delete_floating.xml b/app/src/main/res/drawable-anydpi/ic_delete_floating.xml index f9213d2b5..1014e3d92 100644 --- a/app/src/main/res/drawable-anydpi/ic_delete_floating.xml +++ b/app/src/main/res/drawable-anydpi/ic_delete_floating.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M6,19c0,1.1 0.9,2 2,2h8c1.1,0 2,-0.9 2,-2V7H6v12zM19,4h-3.5l-1,-1h-5l-1,1H5v2h14V4z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_delete_instance.xml b/app/src/main/res/drawable-anydpi/ic_delete_instance.xml index 688d346a3..881052451 100644 --- a/app/src/main/res/drawable-anydpi/ic_delete_instance.xml +++ b/app/src/main/res/drawable-anydpi/ic_delete_instance.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M6,19c0,1.1 0.9,2 2,2h8c1.1,0 2,-0.9 2,-2V7H6v12zM19,4h-3.5l-1,-1h-5l-1,1H5v2h14V4z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_direct_messages.xml b/app/src/main/res/drawable-anydpi/ic_direct_messages.xml index c300537f6..824abfbd0 100644 --- a/app/src/main/res/drawable-anydpi/ic_direct_messages.xml +++ b/app/src/main/res/drawable-anydpi/ic_direct_messages.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M20,4L4,4c-1.1,0 -1.99,0.9 -1.99,2L2,18c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2L22,6c0,-1.1 -0.9,-2 -2,-2zM20,8l-8,5 -8,-5L4,6l8,5 8,-5v2z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_edit.xml b/app/src/main/res/drawable-anydpi/ic_edit.xml index 35a774a51..85d32985f 100644 --- a/app/src/main/res/drawable-anydpi/ic_edit.xml +++ b/app/src/main/res/drawable-anydpi/ic_edit.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M3,17.25V21h3.75L17.81,9.94l-3.75,-3.75L3,17.25zM20.71,7.04c0.39,-0.39 0.39,-1.02 0,-1.41l-2.34,-2.34c-0.39,-0.39 -1.02,-0.39 -1.41,0l-1.83,1.83 3.75,3.75 1.83,-1.83z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_email.xml b/app/src/main/res/drawable-anydpi/ic_email.xml index c300537f6..824abfbd0 100644 --- a/app/src/main/res/drawable-anydpi/ic_email.xml +++ b/app/src/main/res/drawable-anydpi/ic_email.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M20,4L4,4c-1.1,0 -1.99,0.9 -1.99,2L2,18c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2L22,6c0,-1.1 -0.9,-2 -2,-2zM20,8l-8,5 -8,-5L4,6l8,5 8,-5v2z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_expand_less.xml b/app/src/main/res/drawable-anydpi/ic_expand_less.xml index d58421a2f..2648fbba7 100644 --- a/app/src/main/res/drawable-anydpi/ic_expand_less.xml +++ b/app/src/main/res/drawable-anydpi/ic_expand_less.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,8l-6,6 1.41,1.41L12,10.83l4.59,4.58L18,14z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_expand_more.xml b/app/src/main/res/drawable-anydpi/ic_expand_more.xml index fd3ce4a46..e1ccfc24a 100644 --- a/app/src/main/res/drawable-anydpi/ic_expand_more.xml +++ b/app/src/main/res/drawable-anydpi/ic_expand_more.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M16.59,8.59L12,13.17 7.41,8.59 6,10l6,6 6,-6z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_fetch_more.xml b/app/src/main/res/drawable-anydpi/ic_fetch_more.xml index fd3ce4a46..e1ccfc24a 100644 --- a/app/src/main/res/drawable-anydpi/ic_fetch_more.xml +++ b/app/src/main/res/drawable-anydpi/ic_fetch_more.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M16.59,8.59L12,13.17 7.41,8.59 6,10l6,6 6,-6z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_fiber_new.xml b/app/src/main/res/drawable-anydpi/ic_fiber_new.xml index 86fecf037..f3d1bc6ae 100644 --- a/app/src/main/res/drawable-anydpi/ic_fiber_new.xml +++ b/app/src/main/res/drawable-anydpi/ic_fiber_new.xml @@ -1,12 +1,12 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M3 8h18v9H3z" /> + android:pathData="M20,4L4,4c-1.11,0 -1.99,0.89 -1.99,2L2,18c0,1.11 0.89,2 2,2h16c1.11,0 2,-0.89 2,-2L22,6c0,-1.11 -0.89,-2 -2,-2zM8.5,15L7.3,15l-2.55,-3.5L4.75,15L3.5,15L3.5,9h1.25l2.5,3.5L7.25,9L8.5,9v6zM13.5,10.26L11,10.26v1.12h2.5v1.26L11,12.64v1.11h2.5L13.5,15h-4L9.5,9h4v1.26zM20.5,14c0,0.55 -0.45,1 -1,1h-4c-0.55,0 -1,-0.45 -1,-1L14.5,9h1.25v4.51h1.13L16.88,9.99h1.25v3.51h1.12L19.25,9h1.25v5z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_fiber_new_dark.xml b/app/src/main/res/drawable-anydpi/ic_fiber_new_dark.xml index 97c16f621..42a5d11d5 100644 --- a/app/src/main/res/drawable-anydpi/ic_fiber_new_dark.xml +++ b/app/src/main/res/drawable-anydpi/ic_fiber_new_dark.xml @@ -1,12 +1,12 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M3 8h18v9H3z" /> + android:pathData="M20,4L4,4c-1.11,0 -1.99,0.89 -1.99,2L2,18c0,1.11 0.89,2 2,2h16c1.11,0 2,-0.89 2,-2L22,6c0,-1.11 -0.89,-2 -2,-2zM8.5,15L7.3,15l-2.55,-3.5L4.75,15L3.5,15L3.5,9h1.25l2.5,3.5L7.25,9L8.5,9v6zM13.5,10.26L11,10.26v1.12h2.5v1.26L11,12.64v1.11h2.5L13.5,15h-4L9.5,9h4v1.26zM20.5,14c0,0.55 -0.45,1 -1,1h-4c-0.55,0 -1,-0.45 -1,-1L14.5,9h1.25v4.51h1.13L16.88,9.99h1.25v3.51h1.12L19.25,9h1.25v5z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_file_download.xml b/app/src/main/res/drawable-anydpi/ic_file_download.xml index 492b41d34..370bba93d 100644 --- a/app/src/main/res/drawable-anydpi/ic_file_download.xml +++ b/app/src/main/res/drawable-anydpi/ic_file_download.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M19,9h-4V3H9v6H5l7,7 7,-7zM5,18v2h14v-2H5z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_first_page.xml b/app/src/main/res/drawable-anydpi/ic_first_page.xml index 483f56c7c..65d50afd9 100644 --- a/app/src/main/res/drawable-anydpi/ic_first_page.xml +++ b/app/src/main/res/drawable-anydpi/ic_first_page.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M18.41,16.59L13.82,12l4.59,-4.59L17,6l-6,6 6,6zM6,6h2v12H6z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_follow_notif_tab.xml b/app/src/main/res/drawable-anydpi/ic_follow_notif_tab.xml index 225ae0a86..9c533518c 100644 --- a/app/src/main/res/drawable-anydpi/ic_follow_notif_tab.xml +++ b/app/src/main/res/drawable-anydpi/ic_follow_notif_tab.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M15,12c2.21,0 4,-1.79 4,-4s-1.79,-4 -4,-4 -4,1.79 -4,4 1.79,4 4,4zM6,10L6,7L4,7v3L1,10v2h3v3h2v-3h3v-2L6,10zM15,14c-2.67,0 -8,1.34 -8,4v2h16v-2c0,-2.66 -5.33,-4 -8,-4z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_group_add.xml b/app/src/main/res/drawable-anydpi/ic_group_add.xml index b3a2fb3d0..3fcd762e7 100644 --- a/app/src/main/res/drawable-anydpi/ic_group_add.xml +++ b/app/src/main/res/drawable-anydpi/ic_group_add.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M8,10L5,10L5,7L3,7v3L0,10v2h3v3h2v-3h3v-2zM18,11c1.66,0 2.99,-1.34 2.99,-3S19.66,5 18,5c-0.32,0 -0.63,0.05 -0.91,0.14 0.57,0.81 0.9,1.79 0.9,2.86s-0.34,2.04 -0.9,2.86c0.28,0.09 0.59,0.14 0.91,0.14zM13,11c1.66,0 2.99,-1.34 2.99,-3S14.66,5 13,5c-1.66,0 -3,1.34 -3,3s1.34,3 3,3zM19.62,13.16c0.83,0.73 1.38,1.66 1.38,2.84v2h3v-2c0,-1.54 -2.37,-2.49 -4.38,-2.84zM13,13c-2,0 -6,1 -6,3v2h12v-2c0,-2 -4,-3 -6,-3z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_home.xml b/app/src/main/res/drawable-anydpi/ic_home.xml index 70fb2910c..f8bb0b556 100644 --- a/app/src/main/res/drawable-anydpi/ic_home.xml +++ b/app/src/main/res/drawable-anydpi/ic_home.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M10,20v-6h4v6h5v-8h3L12,3 2,12h3v8z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_http.xml b/app/src/main/res/drawable-anydpi/ic_http.xml index bd4e91529..5e33649a5 100644 --- a/app/src/main/res/drawable-anydpi/ic_http.xml +++ b/app/src/main/res/drawable-anydpi/ic_http.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M4.5,11h-2L2.5,9L1,9v6h1.5v-2.5h2L4.5,15L6,15L6,9L4.5,9v2zM7,10.5h1.5L8.5,15L10,15v-4.5h1.5L11.5,9L7,9v1.5zM12.5,10.5L14,10.5L14,15h1.5v-4.5L17,10.5L17,9h-4.5v1.5zM21.5,9L18,9v6h1.5v-2h2c0.8,0 1.5,-0.7 1.5,-1.5v-1c0,-0.8 -0.7,-1.5 -1.5,-1.5zM21.5,11.5h-2v-1h2v1z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_info_login.xml b/app/src/main/res/drawable-anydpi/ic_info_login.xml index 2b9862f21..95efe16b7 100644 --- a/app/src/main/res/drawable-anydpi/ic_info_login.xml +++ b/app/src/main/res/drawable-anydpi/ic_info_login.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM13,17h-2v-6h2v6zM13,9h-2L11,7h2v2z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_info_outline.xml b/app/src/main/res/drawable-anydpi/ic_info_outline.xml index 9567ecd77..a6ad5d39b 100644 --- a/app/src/main/res/drawable-anydpi/ic_info_outline.xml +++ b/app/src/main/res/drawable-anydpi/ic_info_outline.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M11,17h2v-6h-2v6zM12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM12,20c-4.41,0 -8,-3.59 -8,-8s3.59,-8 8,-8 8,3.59 8,8 -3.59,8 -8,8zM11,9h2L13,7h-2v2z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_insert_emoticon.xml b/app/src/main/res/drawable-anydpi/ic_insert_emoticon.xml index c242c6e52..08dccef56 100644 --- a/app/src/main/res/drawable-anydpi/ic_insert_emoticon.xml +++ b/app/src/main/res/drawable-anydpi/ic_insert_emoticon.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M11.99,2C6.47,2 2,6.48 2,12s4.47,10 9.99,10C17.52,22 22,17.52 22,12S17.52,2 11.99,2zM12,20c-4.42,0 -8,-3.58 -8,-8s3.58,-8 8,-8 8,3.58 8,8 -3.58,8 -8,8zM15.5,11c0.83,0 1.5,-0.67 1.5,-1.5S16.33,8 15.5,8 14,8.67 14,9.5s0.67,1.5 1.5,1.5zM8.5,11c0.83,0 1.5,-0.67 1.5,-1.5S9.33,8 8.5,8 7,8.67 7,9.5 7.67,11 8.5,11zM12,17.5c2.33,0 4.31,-1.46 5.11,-3.5L6.89,14c0.8,2.04 2.78,3.5 5.11,3.5z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_insert_photo.xml b/app/src/main/res/drawable-anydpi/ic_insert_photo.xml index 0b56f71ae..24432ed9f 100644 --- a/app/src/main/res/drawable-anydpi/ic_insert_photo.xml +++ b/app/src/main/res/drawable-anydpi/ic_insert_photo.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M21,19V5c0,-1.1 -0.9,-2 -2,-2H5c-1.1,0 -2,0.9 -2,2v14c0,1.1 0.9,2 2,2h14c1.1,0 2,-0.9 2,-2zM8.5,13.5l2.5,3.01L14.5,12l4.5,6H5l3.5,-4.5z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_keyboard_arrow_right.xml b/app/src/main/res/drawable-anydpi/ic_keyboard_arrow_right.xml index a3d162229..138fcc3eb 100644 --- a/app/src/main/res/drawable-anydpi/ic_keyboard_arrow_right.xml +++ b/app/src/main/res/drawable-anydpi/ic_keyboard_arrow_right.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M8.59,16.34l4.58,-4.59 -4.58,-4.59L10,5.75l6,6 -6,6z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_last_page.xml b/app/src/main/res/drawable-anydpi/ic_last_page.xml index 0d04354c1..9aa1cc745 100644 --- a/app/src/main/res/drawable-anydpi/ic_last_page.xml +++ b/app/src/main/res/drawable-anydpi/ic_last_page.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M5.59,7.41L10.18,12l-4.59,4.59L7,18l6,-6 -6,-6zM16,6h2v12h-2z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_list.xml b/app/src/main/res/drawable-anydpi/ic_list.xml index 4c2fb8834..1471c52f5 100644 --- a/app/src/main/res/drawable-anydpi/ic_list.xml +++ b/app/src/main/res/drawable-anydpi/ic_list.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M3,13h2v-2L3,11v2zM3,17h2v-2L3,15v2zM3,9h2L5,7L3,7v2zM7,13h14v-2L7,11v2zM7,17h14v-2L7,15v2zM7,7v2h14L21,7L7,7z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_list_instance.xml b/app/src/main/res/drawable-anydpi/ic_list_instance.xml index fd7111d5d..6cca0d54a 100644 --- a/app/src/main/res/drawable-anydpi/ic_list_instance.xml +++ b/app/src/main/res/drawable-anydpi/ic_list_instance.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M3,13h2v-2L3,11v2zM3,17h2v-2L3,15v2zM3,9h2L5,7L3,7v2zM7,13h14v-2L7,11v2zM7,17h14v-2L7,15v2zM7,7v2h14L21,7L7,7z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_lock_open.xml b/app/src/main/res/drawable-anydpi/ic_lock_open.xml index f54491132..65845ca0a 100644 --- a/app/src/main/res/drawable-anydpi/ic_lock_open.xml +++ b/app/src/main/res/drawable-anydpi/ic_lock_open.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,17c1.1,0 2,-0.9 2,-2s-0.9,-2 -2,-2 -2,0.9 -2,2 0.9,2 2,2zM18,8h-1L17,6c0,-2.76 -2.24,-5 -5,-5S7,3.24 7,6h1.9c0,-1.71 1.39,-3.1 3.1,-3.1 1.71,0 3.1,1.39 3.1,3.1v2L6,8c-1.1,0 -2,0.9 -2,2v10c0,1.1 0.9,2 2,2h12c1.1,0 2,-0.9 2,-2L20,10c0,-1.1 -0.9,-2 -2,-2zM18,20L6,20L6,10h12v10z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_lock_open_toot.xml b/app/src/main/res/drawable-anydpi/ic_lock_open_toot.xml index f54491132..65845ca0a 100644 --- a/app/src/main/res/drawable-anydpi/ic_lock_open_toot.xml +++ b/app/src/main/res/drawable-anydpi/ic_lock_open_toot.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,17c1.1,0 2,-0.9 2,-2s-0.9,-2 -2,-2 -2,0.9 -2,2 0.9,2 2,2zM18,8h-1L17,6c0,-2.76 -2.24,-5 -5,-5S7,3.24 7,6h1.9c0,-1.71 1.39,-3.1 3.1,-3.1 1.71,0 3.1,1.39 3.1,3.1v2L6,8c-1.1,0 -2,0.9 -2,2v10c0,1.1 0.9,2 2,2h12c1.1,0 2,-0.9 2,-2L20,10c0,-1.1 -0.9,-2 -2,-2zM18,20L6,20L6,10h12v10z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_lock_outline.xml b/app/src/main/res/drawable-anydpi/ic_lock_outline.xml index 1a12247ec..a75dd85b6 100644 --- a/app/src/main/res/drawable-anydpi/ic_lock_outline.xml +++ b/app/src/main/res/drawable-anydpi/ic_lock_outline.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,17c1.1,0 2,-0.9 2,-2s-0.9,-2 -2,-2 -2,0.9 -2,2 0.9,2 2,2zM18,8h-1L17,6c0,-2.76 -2.24,-5 -5,-5S7,3.24 7,6v2L6,8c-1.1,0 -2,0.9 -2,2v10c0,1.1 0.9,2 2,2h12c1.1,0 2,-0.9 2,-2L20,10c0,-1.1 -0.9,-2 -2,-2zM8.9,6c0,-1.71 1.39,-3.1 3.1,-3.1s3.1,1.39 3.1,3.1v2L8.9,8L8.9,6zM18,20L6,20L6,10h12v10z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_lock_outline_toot.xml b/app/src/main/res/drawable-anydpi/ic_lock_outline_toot.xml index 1a12247ec..a75dd85b6 100644 --- a/app/src/main/res/drawable-anydpi/ic_lock_outline_toot.xml +++ b/app/src/main/res/drawable-anydpi/ic_lock_outline_toot.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,17c1.1,0 2,-0.9 2,-2s-0.9,-2 -2,-2 -2,0.9 -2,2 0.9,2 2,2zM18,8h-1L17,6c0,-2.76 -2.24,-5 -5,-5S7,3.24 7,6v2L6,8c-1.1,0 -2,0.9 -2,2v10c0,1.1 0.9,2 2,2h12c1.1,0 2,-0.9 2,-2L20,10c0,-1.1 -0.9,-2 -2,-2zM8.9,6c0,-1.71 1.39,-3.1 3.1,-3.1s3.1,1.39 3.1,3.1v2L8.9,8L8.9,6zM18,20L6,20L6,10h12v10z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_mail_outline.xml b/app/src/main/res/drawable-anydpi/ic_mail_outline.xml index 755712da7..2e3ce5b9c 100644 --- a/app/src/main/res/drawable-anydpi/ic_mail_outline.xml +++ b/app/src/main/res/drawable-anydpi/ic_mail_outline.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M20,4L4,4c-1.1,0 -1.99,0.9 -1.99,2L2,18c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2L22,6c0,-1.1 -0.9,-2 -2,-2zM20,18L4,18L4,8l8,5 8,-5v10zM12,11L4,6h16l-8,5z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_mail_outline_toot.xml b/app/src/main/res/drawable-anydpi/ic_mail_outline_toot.xml index 755712da7..2e3ce5b9c 100644 --- a/app/src/main/res/drawable-anydpi/ic_mail_outline_toot.xml +++ b/app/src/main/res/drawable-anydpi/ic_mail_outline_toot.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M20,4L4,4c-1.1,0 -1.99,0.9 -1.99,2L2,18c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2L22,6c0,-1.1 -0.9,-2 -2,-2zM20,18L4,18L4,8l8,5 8,-5v10zM12,11L4,6h16l-8,5z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_mention_notif_tab.xml b/app/src/main/res/drawable-anydpi/ic_mention_notif_tab.xml index 3eeab8286..d044ac15a 100644 --- a/app/src/main/res/drawable-anydpi/ic_mention_notif_tab.xml +++ b/app/src/main/res/drawable-anydpi/ic_mention_notif_tab.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M20,2H4c-1.1,0 -2,0.9 -2,2v18l4,-4h14c1.1,0 2,-0.9 2,-2V4c0,-1.1 -0.9,-2 -2,-2z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_mic.xml b/app/src/main/res/drawable-anydpi/ic_mic.xml index c0633e87a..c0c92fcc7 100644 --- a/app/src/main/res/drawable-anydpi/ic_mic.xml +++ b/app/src/main/res/drawable-anydpi/ic_mic.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,14c1.66,0 2.99,-1.34 2.99,-3L15,5c0,-1.66 -1.34,-3 -3,-3S9,3.34 9,5v6c0,1.66 1.34,3 3,3zM17.3,11c0,3 -2.54,5.1 -5.3,5.1S6.7,14 6.7,11L5,11c0,3.41 2.72,6.23 6,6.72L11,21h2v-3.28c3.28,-0.48 6,-3.3 6,-6.72h-1.7z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_more_horiz.xml b/app/src/main/res/drawable-anydpi/ic_more_horiz.xml index da83afdb1..031cb39e0 100644 --- a/app/src/main/res/drawable-anydpi/ic_more_horiz.xml +++ b/app/src/main/res/drawable-anydpi/ic_more_horiz.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M6,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2zM18,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2zM12,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_more_toot_content.xml b/app/src/main/res/drawable-anydpi/ic_more_toot_content.xml index da83afdb1..031cb39e0 100644 --- a/app/src/main/res/drawable-anydpi/ic_more_toot_content.xml +++ b/app/src/main/res/drawable-anydpi/ic_more_toot_content.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M6,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2zM18,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2zM12,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_more_vert.xml b/app/src/main/res/drawable-anydpi/ic_more_vert.xml index 3dfd99efc..61e8792ad 100644 --- a/app/src/main/res/drawable-anydpi/ic_more_vert.xml +++ b/app/src/main/res/drawable-anydpi/ic_more_vert.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,8c1.1,0 2,-0.9 2,-2s-0.9,-2 -2,-2 -2,0.9 -2,2 0.9,2 2,2zM12,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2zM12,16c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_notifications.xml b/app/src/main/res/drawable-anydpi/ic_notifications.xml index 7009a6763..78b75c39b 100644 --- a/app/src/main/res/drawable-anydpi/ic_notifications.xml +++ b/app/src/main/res/drawable-anydpi/ic_notifications.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,22c1.1,0 2,-0.9 2,-2h-4c0,1.1 0.89,2 2,2zM18,16v-5c0,-3.07 -1.64,-5.64 -4.5,-6.32L13.5,4c0,-0.83 -0.67,-1.5 -1.5,-1.5s-1.5,0.67 -1.5,1.5v0.68C7.63,5.36 6,7.92 6,11v5l-2,2v1h16v-1l-2,-2z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_notifications_active.xml b/app/src/main/res/drawable-anydpi/ic_notifications_active.xml index 2b956d16d..26b365fcc 100644 --- a/app/src/main/res/drawable-anydpi/ic_notifications_active.xml +++ b/app/src/main/res/drawable-anydpi/ic_notifications_active.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M7.58,4.08L6.15,2.65C3.75,4.48 2.17,7.3 2.03,10.5h2c0.15,-2.65 1.51,-4.97 3.55,-6.42zM19.97,10.5h2c-0.15,-3.2 -1.73,-6.02 -4.12,-7.85l-1.42,1.43c2.02,1.45 3.39,3.77 3.54,6.42zM18,11c0,-3.07 -1.64,-5.64 -4.5,-6.32L13.5,4c0,-0.83 -0.67,-1.5 -1.5,-1.5s-1.5,0.67 -1.5,1.5v0.68C7.63,5.36 6,7.92 6,11v5l-2,2v1h16v-1l-2,-2v-5zM12,22c0.14,0 0.27,-0.01 0.4,-0.04 0.65,-0.14 1.18,-0.58 1.44,-1.18 0.1,-0.24 0.15,-0.5 0.15,-0.78h-4c0.01,1.1 0.9,2 2.01,2z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_notifications_off.xml b/app/src/main/res/drawable-anydpi/ic_notifications_off.xml index b40f82d36..b48ae1c9b 100644 --- a/app/src/main/res/drawable-anydpi/ic_notifications_off.xml +++ b/app/src/main/res/drawable-anydpi/ic_notifications_off.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M20,18.69L7.84,6.14 5.27,3.49 4,4.76l2.8,2.8v0.01c-0.52,0.99 -0.8,2.16 -0.8,3.42v5l-2,2v1h13.73l2,2L21,19.72l-1,-1.03zM12,22c1.11,0 2,-0.89 2,-2h-4c0,1.11 0.89,2 2,2zM18,14.68L18,11c0,-3.08 -1.64,-5.64 -4.5,-6.32L13.5,4c0,-0.83 -0.67,-1.5 -1.5,-1.5s-1.5,0.67 -1.5,1.5v0.68c-0.15,0.03 -0.29,0.08 -0.42,0.12 -0.1,0.03 -0.2,0.07 -0.3,0.11h-0.01c-0.01,0 -0.01,0 -0.02,0.01 -0.23,0.09 -0.46,0.2 -0.68,0.31 0,0 -0.01,0 -0.01,0.01L18,14.68z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_notifications_peertube.xml b/app/src/main/res/drawable-anydpi/ic_notifications_peertube.xml index 7009a6763..78b75c39b 100644 --- a/app/src/main/res/drawable-anydpi/ic_notifications_peertube.xml +++ b/app/src/main/res/drawable-anydpi/ic_notifications_peertube.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,22c1.1,0 2,-0.9 2,-2h-4c0,1.1 0.89,2 2,2zM18,16v-5c0,-3.07 -1.64,-5.64 -4.5,-6.32L13.5,4c0,-0.83 -0.67,-1.5 -1.5,-1.5s-1.5,0.67 -1.5,1.5v0.68C7.63,5.36 6,7.92 6,11v5l-2,2v1h16v-1l-2,-2z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_notifications_settings.xml b/app/src/main/res/drawable-anydpi/ic_notifications_settings.xml index 7009a6763..78b75c39b 100644 --- a/app/src/main/res/drawable-anydpi/ic_notifications_settings.xml +++ b/app/src/main/res/drawable-anydpi/ic_notifications_settings.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,22c1.1,0 2,-0.9 2,-2h-4c0,1.1 0.89,2 2,2zM18,16v-5c0,-3.07 -1.64,-5.64 -4.5,-6.32L13.5,4c0,-0.83 -0.67,-1.5 -1.5,-1.5s-1.5,0.67 -1.5,1.5v0.68C7.63,5.36 6,7.92 6,11v5l-2,2v1h16v-1l-2,-2z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_open_with.xml b/app/src/main/res/drawable-anydpi/ic_open_with.xml index e1ea78347..c5948c723 100644 --- a/app/src/main/res/drawable-anydpi/ic_open_with.xml +++ b/app/src/main/res/drawable-anydpi/ic_open_with.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M10,9h4L14,6h3l-5,-5 -5,5h3v3zM9,10L6,10L6,7l-5,5 5,5v-3h3v-4zM23,12l-5,-5v3h-3v4h3v3l5,-5zM14,15h-4v3L7,18l5,5 5,-5h-3v-3z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_overview.xml b/app/src/main/res/drawable-anydpi/ic_overview.xml index d07324c87..340a4bf0f 100644 --- a/app/src/main/res/drawable-anydpi/ic_overview.xml +++ b/app/src/main/res/drawable-anydpi/ic_overview.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M11.99,2C6.47,2 2,6.48 2,12s4.47,10 9.99,10C17.52,22 22,17.52 22,12S17.52,2 11.99,2zM18.92,8h-2.95c-0.32,-1.25 -0.78,-2.45 -1.38,-3.56 1.84,0.63 3.37,1.91 4.33,3.56zM12,4.04c0.83,1.2 1.48,2.53 1.91,3.96h-3.82c0.43,-1.43 1.08,-2.76 1.91,-3.96zM4.26,14C4.1,13.36 4,12.69 4,12s0.1,-1.36 0.26,-2h3.38c-0.08,0.66 -0.14,1.32 -0.14,2 0,0.68 0.06,1.34 0.14,2L4.26,14zM5.08,16h2.95c0.32,1.25 0.78,2.45 1.38,3.56 -1.84,-0.63 -3.37,-1.9 -4.33,-3.56zM8.03,8L5.08,8c0.96,-1.66 2.49,-2.93 4.33,-3.56C8.81,5.55 8.35,6.75 8.03,8zM12,19.96c-0.83,-1.2 -1.48,-2.53 -1.91,-3.96h3.82c-0.43,1.43 -1.08,2.76 -1.91,3.96zM14.34,14L9.66,14c-0.09,-0.66 -0.16,-1.32 -0.16,-2 0,-0.68 0.07,-1.35 0.16,-2h4.68c0.09,0.65 0.16,1.32 0.16,2 0,0.68 -0.07,1.34 -0.16,2zM14.59,19.56c0.6,-1.11 1.06,-2.31 1.38,-3.56h2.95c-0.96,1.65 -2.49,2.93 -4.33,3.56zM16.36,14c0.08,-0.66 0.14,-1.32 0.14,-2 0,-0.68 -0.06,-1.34 -0.14,-2h3.38c0.16,0.64 0.26,1.31 0.26,2s-0.1,1.36 -0.26,2h-3.38z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_people.xml b/app/src/main/res/drawable-anydpi/ic_people.xml index 4cfd86960..603c006db 100644 --- a/app/src/main/res/drawable-anydpi/ic_people.xml +++ b/app/src/main/res/drawable-anydpi/ic_people.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M16,11c1.66,0 2.99,-1.34 2.99,-3S17.66,5 16,5c-1.66,0 -3,1.34 -3,3s1.34,3 3,3zM8,11c1.66,0 2.99,-1.34 2.99,-3S9.66,5 8,5C6.34,5 5,6.34 5,8s1.34,3 3,3zM8,13c-2.33,0 -7,1.17 -7,3.5L1,19h14v-2.5c0,-2.33 -4.67,-3.5 -7,-3.5zM16,13c-0.29,0 -0.62,0.02 -0.97,0.05 1.16,0.84 1.97,1.97 1.97,3.45L17,19h6v-2.5c0,-2.33 -4.67,-3.5 -7,-3.5z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_perm_media.xml b/app/src/main/res/drawable-anydpi/ic_perm_media.xml index 346d9c770..0a45102de 100644 --- a/app/src/main/res/drawable-anydpi/ic_perm_media.xml +++ b/app/src/main/res/drawable-anydpi/ic_perm_media.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M2,6L0,6v5h0.01L0,20c0,1.1 0.9,2 2,2h18v-2L2,20L2,6zM22,4h-8l-2,-2L6,2c-1.1,0 -1.99,0.9 -1.99,2L4,16c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2L24,6c0,-1.1 -0.9,-2 -2,-2zM7,15l4.5,-6 3.5,4.51 2.5,-3.01L21,15L7,15z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_person.xml b/app/src/main/res/drawable-anydpi/ic_person.xml index b2cb337b0..55495d5a0 100644 --- a/app/src/main/res/drawable-anydpi/ic_person.xml +++ b/app/src/main/res/drawable-anydpi/ic_person.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,12c2.21,0 4,-1.79 4,-4s-1.79,-4 -4,-4 -4,1.79 -4,4 1.79,4 4,4zM12,14c-2.67,0 -8,1.34 -8,4v2h16v-2c0,-2.66 -5.33,-4 -8,-4z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_person_add.xml b/app/src/main/res/drawable-anydpi/ic_person_add.xml index 225ae0a86..9c533518c 100644 --- a/app/src/main/res/drawable-anydpi/ic_person_add.xml +++ b/app/src/main/res/drawable-anydpi/ic_person_add.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M15,12c2.21,0 4,-1.79 4,-4s-1.79,-4 -4,-4 -4,1.79 -4,4 1.79,4 4,4zM6,10L6,7L4,7v3L1,10v2h3v3h2v-3h3v-2L6,10zM15,14c-2.67,0 -8,1.34 -8,4v2h16v-2c0,-2.66 -5.33,-4 -8,-4z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_person_outline.xml b/app/src/main/res/drawable-anydpi/ic_person_outline.xml index f828a57e6..4f248aa8f 100644 --- a/app/src/main/res/drawable-anydpi/ic_person_outline.xml +++ b/app/src/main/res/drawable-anydpi/ic_person_outline.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,5.9c1.16,0 2.1,0.94 2.1,2.1s-0.94,2.1 -2.1,2.1S9.9,9.16 9.9,8s0.94,-2.1 2.1,-2.1m0,9c2.97,0 6.1,1.46 6.1,2.1v1.1L5.9,18.1L5.9,17c0,-0.64 3.13,-2.1 6.1,-2.1M12,4C9.79,4 8,5.79 8,8s1.79,4 4,4 4,-1.79 4,-4 -1.79,-4 -4,-4zM12,13c-2.67,0 -8,1.34 -8,4v3h16v-3c0,-2.66 -5.33,-4 -8,-4z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_photo.xml b/app/src/main/res/drawable-anydpi/ic_photo.xml index b2018595e..d0300632a 100644 --- a/app/src/main/res/drawable-anydpi/ic_photo.xml +++ b/app/src/main/res/drawable-anydpi/ic_photo.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M21,19V5c0,-1.1 -0.9,-2 -2,-2H5c-1.1,0 -2,0.9 -2,2v14c0,1.1 0.9,2 2,2h14c1.1,0 2,-0.9 2,-2zM8.5,13.5l2.5,3.01L14.5,12l4.5,6H5l3.5,-4.5z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_photo_camera.xml b/app/src/main/res/drawable-anydpi/ic_photo_camera.xml index 4fa7158a0..d7a3c0f9b 100644 --- a/app/src/main/res/drawable-anydpi/ic_photo_camera.xml +++ b/app/src/main/res/drawable-anydpi/ic_photo_camera.xml @@ -1,12 +1,12 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,12m-3.2,0a3.2,3.2 0,1 1,6.4 0a3.2,3.2 0,1 1,-6.4 0" /> + android:pathData="M9,2L7.17,4L4,4c-1.1,0 -2,0.9 -2,2v12c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2L22,6c0,-1.1 -0.9,-2 -2,-2h-3.17L15,2L9,2zM12,17c-2.76,0 -5,-2.24 -5,-5s2.24,-5 5,-5 5,2.24 5,5 -2.24,5 -5,5z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_pixelfed_favorite.xml b/app/src/main/res/drawable-anydpi/ic_pixelfed_favorite.xml index cfba5d846..17cea9270 100644 --- a/app/src/main/res/drawable-anydpi/ic_pixelfed_favorite.xml +++ b/app/src/main/res/drawable-anydpi/ic_pixelfed_favorite.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,21.35l-1.45,-1.32C5.4,15.36 2,12.28 2,8.5 2,5.42 4.42,3 7.5,3c1.74,0 3.41,0.81 4.5,2.09C13.09,3.81 14.76,3 16.5,3 19.58,3 22,5.42 22,8.5c0,3.78 -3.4,6.86 -8.55,11.54L12,21.35z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_pixelfed_favorite_border.xml b/app/src/main/res/drawable-anydpi/ic_pixelfed_favorite_border.xml index 0cfbad645..feccba749 100644 --- a/app/src/main/res/drawable-anydpi/ic_pixelfed_favorite_border.xml +++ b/app/src/main/res/drawable-anydpi/ic_pixelfed_favorite_border.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M16.5,3c-1.74,0 -3.41,0.81 -4.5,2.09C10.91,3.81 9.24,3 7.5,3 4.42,3 2,5.42 2,8.5c0,3.78 3.4,6.86 8.55,11.54L12,21.35l1.45,-1.32C18.6,15.36 22,12.28 22,8.5 22,5.42 19.58,3 16.5,3zM12.1,18.55l-0.1,0.1 -0.1,-0.1C7.14,14.24 4,11.39 4,8.5 4,6.5 5.5,5 7.5,5c1.54,0 3.04,0.99 3.57,2.36h1.87C13.46,5.99 14.96,5 16.5,5c2,0 3.5,1.5 3.5,3.5 0,2.89 -3.14,5.74 -7.9,10.05z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_pixelfed_media.xml b/app/src/main/res/drawable-anydpi/ic_pixelfed_media.xml index d2bf51285..1106f563c 100644 --- a/app/src/main/res/drawable-anydpi/ic_pixelfed_media.xml +++ b/app/src/main/res/drawable-anydpi/ic_pixelfed_media.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M2,6L0,6v5h0.01L0,20c0,1.1 0.9,2 2,2h18v-2L2,20L2,6zM22,4h-8l-2,-2L6,2c-1.1,0 -1.99,0.9 -1.99,2L4,16c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2L24,6c0,-1.1 -0.9,-2 -2,-2zM7,15l4.5,-6 3.5,4.51 2.5,-3.01L21,15L7,15z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_play_arrow.xml b/app/src/main/res/drawable-anydpi/ic_play_arrow.xml index 81a8f74f6..4250d72cb 100644 --- a/app/src/main/res/drawable-anydpi/ic_play_arrow.xml +++ b/app/src/main/res/drawable-anydpi/ic_play_arrow.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M8,5v14l11,-7z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_public.xml b/app/src/main/res/drawable-anydpi/ic_public.xml index e2bc72fd7..9827dad96 100644 --- a/app/src/main/res/drawable-anydpi/ic_public.xml +++ b/app/src/main/res/drawable-anydpi/ic_public.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM11,19.93c-3.95,-0.49 -7,-3.85 -7,-7.93 0,-0.62 0.08,-1.21 0.21,-1.79L9,15v1c0,1.1 0.9,2 2,2v1.93zM17.9,17.39c-0.26,-0.81 -1,-1.39 -1.9,-1.39h-1v-3c0,-0.55 -0.45,-1 -1,-1L8,12v-2h2c0.55,0 1,-0.45 1,-1L11,7h2c1.1,0 2,-0.9 2,-2v-0.41c2.93,1.19 5,4.06 5,7.41 0,2.08 -0.8,3.97 -2.1,5.39z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_public_toot.xml b/app/src/main/res/drawable-anydpi/ic_public_toot.xml index e2bc72fd7..9827dad96 100644 --- a/app/src/main/res/drawable-anydpi/ic_public_toot.xml +++ b/app/src/main/res/drawable-anydpi/ic_public_toot.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM11,19.93c-3.95,-0.49 -7,-3.85 -7,-7.93 0,-0.62 0.08,-1.21 0.21,-1.79L9,15v1c0,1.1 0.9,2 2,2v1.93zM17.9,17.39c-0.26,-0.81 -1,-1.39 -1.9,-1.39h-1v-3c0,-0.55 -0.45,-1 -1,-1L8,12v-2h2c0.55,0 1,-0.45 1,-1L11,7h2c1.1,0 2,-0.9 2,-2v-0.41c2.93,1.19 5,4.06 5,7.41 0,2.08 -0.8,3.97 -2.1,5.39z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_recently_added.xml b/app/src/main/res/drawable-anydpi/ic_recently_added.xml index 900f2275e..1596099f3 100644 --- a/app/src/main/res/drawable-anydpi/ic_recently_added.xml +++ b/app/src/main/res/drawable-anydpi/ic_recently_added.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M13,7h-2v4L7,11v2h4v4h2v-4h4v-2h-4L13,7zM12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM12,20c-4.41,0 -8,-3.59 -8,-8s3.59,-8 8,-8 8,3.59 8,8 -3.59,8 -8,8z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_refresh.xml b/app/src/main/res/drawable-anydpi/ic_refresh.xml index a8175c316..f0cb4befb 100644 --- a/app/src/main/res/drawable-anydpi/ic_refresh.xml +++ b/app/src/main/res/drawable-anydpi/ic_refresh.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M17.65,6.35C16.2,4.9 14.21,4 12,4c-4.42,0 -7.99,3.58 -7.99,8s3.57,8 7.99,8c3.73,0 6.84,-2.55 7.73,-6h-2.08c-0.82,2.33 -3.04,4 -5.65,4 -3.31,0 -6,-2.69 -6,-6s2.69,-6 6,-6c1.66,0 3.14,0.69 4.22,1.78L13,11h7V4l-2.35,2.35z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_remove_red_eye.xml b/app/src/main/res/drawable-anydpi/ic_remove_red_eye.xml index 6c95a5d29..5bab335a2 100644 --- a/app/src/main/res/drawable-anydpi/ic_remove_red_eye.xml +++ b/app/src/main/res/drawable-anydpi/ic_remove_red_eye.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,4.5C7,4.5 2.73,7.61 1,12c1.73,4.39 6,7.5 11,7.5s9.27,-3.11 11,-7.5c-1.73,-4.39 -6,-7.5 -11,-7.5zM12,17c-2.76,0 -5,-2.24 -5,-5s2.24,-5 5,-5 5,2.24 5,5 -2.24,5 -5,5zM12,9c-1.66,0 -3,1.34 -3,3s1.34,3 3,3 3,-1.34 3,-3 -1.34,-3 -3,-3z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_remove_red_eye_img.xml b/app/src/main/res/drawable-anydpi/ic_remove_red_eye_img.xml index 6c95a5d29..5bab335a2 100644 --- a/app/src/main/res/drawable-anydpi/ic_remove_red_eye_img.xml +++ b/app/src/main/res/drawable-anydpi/ic_remove_red_eye_img.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,4.5C7,4.5 2.73,7.61 1,12c1.73,4.39 6,7.5 11,7.5s9.27,-3.11 11,-7.5c-1.73,-4.39 -6,-7.5 -11,-7.5zM12,17c-2.76,0 -5,-2.24 -5,-5s2.24,-5 5,-5 5,2.24 5,5 -2.24,5 -5,5zM12,9c-1.66,0 -3,1.34 -3,3s1.34,3 3,3 3,-1.34 3,-3 -1.34,-3 -3,-3z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_repeat.xml b/app/src/main/res/drawable-anydpi/ic_repeat.xml index e7c67d710..a10f3b451 100644 --- a/app/src/main/res/drawable-anydpi/ic_repeat.xml +++ b/app/src/main/res/drawable-anydpi/ic_repeat.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M7,7h10v3l4,-4 -4,-4v3L5,5v6h2L7,7zM17,17L7,17v-3l-4,4 4,4v-3h12v-6h-2v4z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_repeat_boost.xml b/app/src/main/res/drawable-anydpi/ic_repeat_boost.xml index e7c67d710..a10f3b451 100644 --- a/app/src/main/res/drawable-anydpi/ic_repeat_boost.xml +++ b/app/src/main/res/drawable-anydpi/ic_repeat_boost.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M7,7h10v3l4,-4 -4,-4v3L5,5v6h2L7,7zM17,17L7,17v-3l-4,4 4,4v-3h12v-6h-2v4z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_repeat_head.xml b/app/src/main/res/drawable-anydpi/ic_repeat_head.xml index e7c67d710..a10f3b451 100644 --- a/app/src/main/res/drawable-anydpi/ic_repeat_head.xml +++ b/app/src/main/res/drawable-anydpi/ic_repeat_head.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M7,7h10v3l4,-4 -4,-4v3L5,5v6h2L7,7zM17,17L7,17v-3l-4,4 4,4v-3h12v-6h-2v4z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_repeat_head_toot.xml b/app/src/main/res/drawable-anydpi/ic_repeat_head_toot.xml index e7c67d710..a10f3b451 100644 --- a/app/src/main/res/drawable-anydpi/ic_repeat_head_toot.xml +++ b/app/src/main/res/drawable-anydpi/ic_repeat_head_toot.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M7,7h10v3l4,-4 -4,-4v3L5,5v6h2L7,7zM17,17L7,17v-3l-4,4 4,4v-3h12v-6h-2v4z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_repeat_notif_tab.xml b/app/src/main/res/drawable-anydpi/ic_repeat_notif_tab.xml index e7c67d710..a10f3b451 100644 --- a/app/src/main/res/drawable-anydpi/ic_repeat_notif_tab.xml +++ b/app/src/main/res/drawable-anydpi/ic_repeat_notif_tab.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M7,7h10v3l4,-4 -4,-4v3L5,5v6h2L7,7zM17,17L7,17v-3l-4,4 4,4v-3h12v-6h-2v4z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_reply.xml b/app/src/main/res/drawable-anydpi/ic_reply.xml index 46b19a0d3..bd8ff553b 100644 --- a/app/src/main/res/drawable-anydpi/ic_reply.xml +++ b/app/src/main/res/drawable-anydpi/ic_reply.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M10,9V5l-7,7 7,7v-4.1c5,0 8.5,1.6 11,5.1 -1,-5 -4,-10 -11,-11z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_report.xml b/app/src/main/res/drawable-anydpi/ic_report.xml index e20d8899c..b024fc676 100644 --- a/app/src/main/res/drawable-anydpi/ic_report.xml +++ b/app/src/main/res/drawable-anydpi/ic_report.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M15.73,3L8.27,3L3,8.27v7.46L8.27,21h7.46L21,15.73L21,8.27L15.73,3zM12,17.3c-0.72,0 -1.3,-0.58 -1.3,-1.3 0,-0.72 0.58,-1.3 1.3,-1.3 0.72,0 1.3,0.58 1.3,1.3 0,0.72 -0.58,1.3 -1.3,1.3zM13,13h-2L11,7h2v6z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_restore.xml b/app/src/main/res/drawable-anydpi/ic_restore.xml index 9d163b91c..bb75fb8b8 100644 --- a/app/src/main/res/drawable-anydpi/ic_restore.xml +++ b/app/src/main/res/drawable-anydpi/ic_restore.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M13,3c-4.97,0 -9,4.03 -9,9L1,12l3.89,3.89 0.07,0.14L9,12L6,12c0,-3.87 3.13,-7 7,-7s7,3.13 7,7 -3.13,7 -7,7c-1.93,0 -3.68,-0.79 -4.94,-2.06l-1.42,1.42C8.27,19.99 10.51,21 13,21c4.97,0 9,-4.03 9,-9s-4.03,-9 -9,-9zM12,8v5l4.28,2.54 0.72,-1.21 -3.5,-2.08L13.5,8L12,8z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_save.xml b/app/src/main/res/drawable-anydpi/ic_save.xml index a561d632a..0651fcc6c 100644 --- a/app/src/main/res/drawable-anydpi/ic_save.xml +++ b/app/src/main/res/drawable-anydpi/ic_save.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M17,3L5,3c-1.11,0 -2,0.9 -2,2v14c0,1.1 0.89,2 2,2h14c1.1,0 2,-0.9 2,-2L21,7l-4,-4zM12,19c-1.66,0 -3,-1.34 -3,-3s1.34,-3 3,-3 3,1.34 3,3 -1.34,3 -3,3zM15,9L5,9L5,5h10v4z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_save_white.xml b/app/src/main/res/drawable-anydpi/ic_save_white.xml index a7a81a25d..47a925197 100644 --- a/app/src/main/res/drawable-anydpi/ic_save_white.xml +++ b/app/src/main/res/drawable-anydpi/ic_save_white.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M17,3L5,3c-1.11,0 -2,0.9 -2,2v14c0,1.1 0.89,2 2,2h14c1.1,0 2,-0.9 2,-2L21,7l-4,-4zM12,19c-1.66,0 -3,-1.34 -3,-3s1.34,-3 3,-3 3,1.34 3,3 -1.34,3 -3,3zM15,9L5,9L5,5h10v4z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_schedule.xml b/app/src/main/res/drawable-anydpi/ic_schedule.xml index d16ec92b5..a0d274a54 100644 --- a/app/src/main/res/drawable-anydpi/ic_schedule.xml +++ b/app/src/main/res/drawable-anydpi/ic_schedule.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M11.99,2C6.47,2 2,6.48 2,12s4.47,10 9.99,10C17.52,22 22,17.52 22,12S17.52,2 11.99,2zM12,20c-4.42,0 -8,-3.58 -8,-8s3.58,-8 8,-8 8,3.58 8,8 -3.58,8 -8,8zM12.5,7L11,7v6l5.25,3.15 0.75,-1.23 -4.5,-2.67z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_search.xml b/app/src/main/res/drawable-anydpi/ic_search.xml index 47432c174..55da240a2 100644 --- a/app/src/main/res/drawable-anydpi/ic_search.xml +++ b/app/src/main/res/drawable-anydpi/ic_search.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M15.5,14h-0.79l-0.28,-0.27C15.41,12.59 16,11.11 16,9.5 16,5.91 13.09,3 9.5,3S3,5.91 3,9.5 5.91,16 9.5,16c1.61,0 3.09,-0.59 4.23,-1.57l0.27,0.28v0.79l5,4.99L20.49,19l-4.99,-5zM9.5,14C7.01,14 5,11.99 5,9.5S7.01,5 9.5,5 14,7.01 14,9.5 11.99,14 9.5,14z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_send.xml b/app/src/main/res/drawable-anydpi/ic_send.xml index e145ca83c..fdf1c9009 100644 --- a/app/src/main/res/drawable-anydpi/ic_send.xml +++ b/app/src/main/res/drawable-anydpi/ic_send.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M2.01,21L23,12 2.01,3 2,10l15,2 -15,2z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_settings.xml b/app/src/main/res/drawable-anydpi/ic_settings.xml index ace746c40..7c0394bbe 100644 --- a/app/src/main/res/drawable-anydpi/ic_settings.xml +++ b/app/src/main/res/drawable-anydpi/ic_settings.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M19.43,12.98c0.04,-0.32 0.07,-0.64 0.07,-0.98s-0.03,-0.66 -0.07,-0.98l2.11,-1.65c0.19,-0.15 0.24,-0.42 0.12,-0.64l-2,-3.46c-0.12,-0.22 -0.39,-0.3 -0.61,-0.22l-2.49,1c-0.52,-0.4 -1.08,-0.73 -1.69,-0.98l-0.38,-2.65C14.46,2.18 14.25,2 14,2h-4c-0.25,0 -0.46,0.18 -0.49,0.42l-0.38,2.65c-0.61,0.25 -1.17,0.59 -1.69,0.98l-2.49,-1c-0.23,-0.09 -0.49,0 -0.61,0.22l-2,3.46c-0.13,0.22 -0.07,0.49 0.12,0.64l2.11,1.65c-0.04,0.32 -0.07,0.65 -0.07,0.98s0.03,0.66 0.07,0.98l-2.11,1.65c-0.19,0.15 -0.24,0.42 -0.12,0.64l2,3.46c0.12,0.22 0.39,0.3 0.61,0.22l2.49,-1c0.52,0.4 1.08,0.73 1.69,0.98l0.38,2.65c0.03,0.24 0.24,0.42 0.49,0.42h4c0.25,0 0.46,-0.18 0.49,-0.42l0.38,-2.65c0.61,-0.25 1.17,-0.59 1.69,-0.98l2.49,1c0.23,0.09 0.49,0 0.61,-0.22l2,-3.46c0.12,-0.22 0.07,-0.49 -0.12,-0.64l-2.11,-1.65zM12,15.5c-1.93,0 -3.5,-1.57 -3.5,-3.5s1.57,-3.5 3.5,-3.5 3.5,1.57 3.5,3.5 -1.57,3.5 -3.5,3.5z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_share_media.xml b/app/src/main/res/drawable-anydpi/ic_share_media.xml index 904066636..b09d63e85 100644 --- a/app/src/main/res/drawable-anydpi/ic_share_media.xml +++ b/app/src/main/res/drawable-anydpi/ic_share_media.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M18,16.08c-0.76,0 -1.44,0.3 -1.96,0.77L8.91,12.7c0.05,-0.23 0.09,-0.46 0.09,-0.7s-0.04,-0.47 -0.09,-0.7l7.05,-4.11c0.54,0.5 1.25,0.81 2.04,0.81 1.66,0 3,-1.34 3,-3s-1.34,-3 -3,-3 -3,1.34 -3,3c0,0.24 0.04,0.47 0.09,0.7L8.04,9.81C7.5,9.31 6.79,9 6,9c-1.66,0 -3,1.34 -3,3s1.34,3 3,3c0.79,0 1.5,-0.31 2.04,-0.81l7.12,4.16c-0.05,0.21 -0.08,0.43 -0.08,0.65 0,1.61 1.31,2.92 2.92,2.92 1.61,0 2.92,-1.31 2.92,-2.92s-1.31,-2.92 -2.92,-2.92z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_share_peertube.xml b/app/src/main/res/drawable-anydpi/ic_share_peertube.xml index 5f7aed400..8515dd194 100644 --- a/app/src/main/res/drawable-anydpi/ic_share_peertube.xml +++ b/app/src/main/res/drawable-anydpi/ic_share_peertube.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M18,16.08c-0.76,0 -1.44,0.3 -1.96,0.77L8.91,12.7c0.05,-0.23 0.09,-0.46 0.09,-0.7s-0.04,-0.47 -0.09,-0.7l7.05,-4.11c0.54,0.5 1.25,0.81 2.04,0.81 1.66,0 3,-1.34 3,-3s-1.34,-3 -3,-3 -3,1.34 -3,3c0,0.24 0.04,0.47 0.09,0.7L8.04,9.81C7.5,9.31 6.79,9 6,9c-1.66,0 -3,1.34 -3,3s1.34,3 3,3c0.79,0 1.5,-0.31 2.04,-0.81l7.12,4.16c-0.05,0.21 -0.08,0.43 -0.08,0.65 0,1.61 1.31,2.92 2.92,2.92 1.61,0 2.92,-1.31 2.92,-2.92s-1.31,-2.92 -2.92,-2.92z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_show_hidden.xml b/app/src/main/res/drawable-anydpi/ic_show_hidden.xml index 6c95a5d29..5bab335a2 100644 --- a/app/src/main/res/drawable-anydpi/ic_show_hidden.xml +++ b/app/src/main/res/drawable-anydpi/ic_show_hidden.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,4.5C7,4.5 2.73,7.61 1,12c1.73,4.39 6,7.5 11,7.5s9.27,-3.11 11,-7.5c-1.73,-4.39 -6,-7.5 -11,-7.5zM12,17c-2.76,0 -5,-2.24 -5,-5s2.24,-5 5,-5 5,2.24 5,5 -2.24,5 -5,5zM12,9c-1.66,0 -3,1.34 -3,3s1.34,3 3,3 3,-1.34 3,-3 -1.34,-3 -3,-3z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_skip_next.xml b/app/src/main/res/drawable-anydpi/ic_skip_next.xml index 1253ff063..eae4da1bf 100644 --- a/app/src/main/res/drawable-anydpi/ic_skip_next.xml +++ b/app/src/main/res/drawable-anydpi/ic_skip_next.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M6,18l8.5,-6L6,6v12zM16,6v12h2V6h-2z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_skip_previous.xml b/app/src/main/res/drawable-anydpi/ic_skip_previous.xml index cd05efeb6..abb9944fc 100644 --- a/app/src/main/res/drawable-anydpi/ic_skip_previous.xml +++ b/app/src/main/res/drawable-anydpi/ic_skip_previous.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M6,6h2v12L6,18zM9.5,12l8.5,6L18,6z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_star.xml b/app/src/main/res/drawable-anydpi/ic_star.xml index a87ca098d..a2ebf3532 100644 --- a/app/src/main/res/drawable-anydpi/ic_star.xml +++ b/app/src/main/res/drawable-anydpi/ic_star.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,17.27L18.18,21l-1.64,-7.03L22,9.24l-7.19,-0.61L12,2 9.19,8.63 2,9.24l5.46,4.73L5.82,21z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_star_border.xml b/app/src/main/res/drawable-anydpi/ic_star_border.xml index b36536b99..c452e47ec 100644 --- a/app/src/main/res/drawable-anydpi/ic_star_border.xml +++ b/app/src/main/res/drawable-anydpi/ic_star_border.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M22,9.24l-7.19,-0.62L12,2 9.19,8.63 2,9.24l5.46,4.73L5.82,21 12,17.27 18.18,21l-1.63,-7.03L22,9.24zM12,15.4l-3.76,2.27 1,-4.28 -3.32,-2.88 4.38,-0.38L12,6.1l1.71,4.04 4.38,0.38 -3.32,2.88 1,4.28L12,15.4z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_star_border_header.xml b/app/src/main/res/drawable-anydpi/ic_star_border_header.xml index b36536b99..c452e47ec 100644 --- a/app/src/main/res/drawable-anydpi/ic_star_border_header.xml +++ b/app/src/main/res/drawable-anydpi/ic_star_border_header.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M22,9.24l-7.19,-0.62L12,2 9.19,8.63 2,9.24l5.46,4.73L5.82,21 12,17.27 18.18,21l-1.63,-7.03L22,9.24zM12,15.4l-3.76,2.27 1,-4.28 -3.32,-2.88 4.38,-0.38L12,6.1l1.71,4.04 4.38,0.38 -3.32,2.88 1,4.28L12,15.4z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_star_menu.xml b/app/src/main/res/drawable-anydpi/ic_star_menu.xml index a87ca098d..a2ebf3532 100644 --- a/app/src/main/res/drawable-anydpi/ic_star_menu.xml +++ b/app/src/main/res/drawable-anydpi/ic_star_menu.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,17.27L18.18,21l-1.64,-7.03L22,9.24l-7.19,-0.61L12,2 9.19,8.63 2,9.24l5.46,4.73L5.82,21z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_star_notif_tab.xml b/app/src/main/res/drawable-anydpi/ic_star_notif_tab.xml index a87ca098d..a2ebf3532 100644 --- a/app/src/main/res/drawable-anydpi/ic_star_notif_tab.xml +++ b/app/src/main/res/drawable-anydpi/ic_star_notif_tab.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,17.27L18.18,21l-1.64,-7.03L22,9.24l-7.19,-0.61L12,2 9.19,8.63 2,9.24l5.46,4.73L5.82,21z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_subscriptions.xml b/app/src/main/res/drawable-anydpi/ic_subscriptions.xml index 6f0ed4551..7337e77a1 100644 --- a/app/src/main/res/drawable-anydpi/ic_subscriptions.xml +++ b/app/src/main/res/drawable-anydpi/ic_subscriptions.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M20,8L4,8L4,6h16v2zM18,2L6,2v2h12L18,2zM22,12v8c0,1.1 -0.9,2 -2,2L4,22c-1.1,0 -2,-0.9 -2,-2v-8c0,-1.1 0.9,-2 2,-2h16c1.1,0 2,0.9 2,2zM16,16l-6,-3.27v6.53L16,16z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_thumb_down_peertube.xml b/app/src/main/res/drawable-anydpi/ic_thumb_down_peertube.xml index 6cb0649c9..9172d8ef9 100644 --- a/app/src/main/res/drawable-anydpi/ic_thumb_down_peertube.xml +++ b/app/src/main/res/drawable-anydpi/ic_thumb_down_peertube.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M15,3L6,3c-0.83,0 -1.54,0.5 -1.84,1.22l-3.02,7.05c-0.09,0.23 -0.14,0.47 -0.14,0.73v1.91l0.01,0.01L1,14c0,1.1 0.9,2 2,2h6.31l-0.95,4.57 -0.03,0.32c0,0.41 0.17,0.79 0.44,1.06L9.83,23l6.59,-6.59c0.36,-0.36 0.58,-0.86 0.58,-1.41L17,5c0,-1.1 -0.9,-2 -2,-2zM19,3v12h4L23,3h-4z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_thumb_up_peertube.xml b/app/src/main/res/drawable-anydpi/ic_thumb_up_peertube.xml index fb115d5d2..100064bb8 100644 --- a/app/src/main/res/drawable-anydpi/ic_thumb_up_peertube.xml +++ b/app/src/main/res/drawable-anydpi/ic_thumb_up_peertube.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M1,21h4L5,9L1,9v12zM23,10c0,-1.1 -0.9,-2 -2,-2h-6.31l0.95,-4.57 0.03,-0.32c0,-0.41 -0.17,-0.79 -0.44,-1.06L14.17,1 7.59,7.59C7.22,7.95 7,8.45 7,9v10c0,1.1 0.9,2 2,2h9c0.83,0 1.54,-0.5 1.84,-1.22l3.02,-7.05c0.09,-0.23 0.14,-0.47 0.14,-0.73v-1.91l-0.01,-0.01L23,10z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_translate.xml b/app/src/main/res/drawable-anydpi/ic_translate.xml index f686f7ef3..f7f2cf09f 100644 --- a/app/src/main/res/drawable-anydpi/ic_translate.xml +++ b/app/src/main/res/drawable-anydpi/ic_translate.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12.87,15.07l-2.54,-2.51 0.03,-0.03c1.74,-1.94 2.98,-4.17 3.71,-6.53L17,6L17,4h-7L10,2L8,2v2L1,4v1.99h11.17C11.5,7.92 10.44,9.75 9,11.35 8.07,10.32 7.3,9.19 6.69,8h-2c0.73,1.63 1.73,3.17 2.98,4.56l-5.09,5.02L4,19l5,-5 3.11,3.11 0.76,-2.04zM18.5,10h-2L12,22h2l1.12,-3h4.75L21,22h2l-4.5,-12zM15.88,17l1.62,-4.33L19.12,17h-3.24z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_translate_menu.xml b/app/src/main/res/drawable-anydpi/ic_translate_menu.xml index f686f7ef3..f7f2cf09f 100644 --- a/app/src/main/res/drawable-anydpi/ic_translate_menu.xml +++ b/app/src/main/res/drawable-anydpi/ic_translate_menu.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12.87,15.07l-2.54,-2.51 0.03,-0.03c1.74,-1.94 2.98,-4.17 3.71,-6.53L17,6L17,4h-7L10,2L8,2v2L1,4v1.99h11.17C11.5,7.92 10.44,9.75 9,11.35 8.07,10.32 7.3,9.19 6.69,8h-2c0.73,1.63 1.73,3.17 2.98,4.56l-5.09,5.02L4,19l5,-5 3.11,3.11 0.76,-2.04zM18.5,10h-2L12,22h2l1.12,-3h4.75L21,22h2l-4.5,-12zM15.88,17l1.62,-4.33L19.12,17h-3.24z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_trending_up.xml b/app/src/main/res/drawable-anydpi/ic_trending_up.xml index 4c9da94b9..c00c42e43 100644 --- a/app/src/main/res/drawable-anydpi/ic_trending_up.xml +++ b/app/src/main/res/drawable-anydpi/ic_trending_up.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M16,6l2.29,2.29 -4.88,4.88 -4,-4L2,16.59 3.41,18l6,-6 4,4 6.3,-6.29L22,12V6z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_video_channel.xml b/app/src/main/res/drawable-anydpi/ic_video_channel.xml index 3cc63f78a..a2b8e9d87 100644 --- a/app/src/main/res/drawable-anydpi/ic_video_channel.xml +++ b/app/src/main/res/drawable-anydpi/ic_video_channel.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M4,6L2,6v14c0,1.1 0.9,2 2,2h14v-2L4,20L4,6zM20,2L8,2c-1.1,0 -2,0.9 -2,2v12c0,1.1 0.9,2 2,2h12c1.1,0 2,-0.9 2,-2L22,4c0,-1.1 -0.9,-2 -2,-2zM12,14.5v-9l6,4.5 -6,4.5z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_video_library.xml b/app/src/main/res/drawable-anydpi/ic_video_library.xml index f808aee58..a616252a6 100644 --- a/app/src/main/res/drawable-anydpi/ic_video_library.xml +++ b/app/src/main/res/drawable-anydpi/ic_video_library.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M4,6L2,6v14c0,1.1 0.9,2 2,2h14v-2L4,20L4,6zM20,2L8,2c-1.1,0 -2,0.9 -2,2v12c0,1.1 0.9,2 2,2h12c1.1,0 2,-0.9 2,-2L22,4c0,-1.1 -0.9,-2 -2,-2zM12,14.5v-9l6,4.5 -6,4.5z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_visibility.xml b/app/src/main/res/drawable-anydpi/ic_visibility.xml index 6c95a5d29..5bab335a2 100644 --- a/app/src/main/res/drawable-anydpi/ic_visibility.xml +++ b/app/src/main/res/drawable-anydpi/ic_visibility.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,4.5C7,4.5 2.73,7.61 1,12c1.73,4.39 6,7.5 11,7.5s9.27,-3.11 11,-7.5c-1.73,-4.39 -6,-7.5 -11,-7.5zM12,17c-2.76,0 -5,-2.24 -5,-5s2.24,-5 5,-5 5,2.24 5,5 -2.24,5 -5,5zM12,9c-1.66,0 -3,1.34 -3,3s1.34,3 3,3 3,-1.34 3,-3 -1.34,-3 -3,-3z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_visibility_peertube.xml b/app/src/main/res/drawable-anydpi/ic_visibility_peertube.xml index 42ed85bee..d03ce805b 100644 --- a/app/src/main/res/drawable-anydpi/ic_visibility_peertube.xml +++ b/app/src/main/res/drawable-anydpi/ic_visibility_peertube.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,4.5C7,4.5 2.73,7.61 1,12c1.73,4.39 6,7.5 11,7.5s9.27,-3.11 11,-7.5c-1.73,-4.39 -6,-7.5 -11,-7.5zM12,17c-2.76,0 -5,-2.24 -5,-5s2.24,-5 5,-5 5,2.24 5,5 -2.24,5 -5,5zM12,9c-1.66,0 -3,1.34 -3,3s1.34,3 3,3 3,-1.34 3,-3 -1.34,-3 -3,-3z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_volume_mute.xml b/app/src/main/res/drawable-anydpi/ic_volume_mute.xml index 81e8892c1..de6f3d386 100644 --- a/app/src/main/res/drawable-anydpi/ic_volume_mute.xml +++ b/app/src/main/res/drawable-anydpi/ic_volume_mute.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M7,9v6h4l5,5V4l-5,5H7z" /> diff --git a/app/src/main/res/drawable-anydpi/ic_volume_up.xml b/app/src/main/res/drawable-anydpi/ic_volume_up.xml index 5e5cb11fb..5d604f823 100644 --- a/app/src/main/res/drawable-anydpi/ic_volume_up.xml +++ b/app/src/main/res/drawable-anydpi/ic_volume_up.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M3,9v6h4l5,5L12,4L7,9L3,9zM16.5,12c0,-1.77 -1.02,-3.29 -2.5,-4.03v8.05c1.48,-0.73 2.5,-2.25 2.5,-4.02zM14,3.23v2.06c2.89,0.86 5,3.54 5,6.71s-2.11,5.85 -5,6.71v2.06c4.01,-0.91 7,-4.49 7,-8.77s-2.99,-7.86 -7,-8.77z" /> diff --git a/app/src/main/res/drawable-v26/ic_launcher_foreground.xml b/app/src/main/res/drawable-v26/ic_launcher_foreground.xml index f79d24a3f..7fb19b5bf 100644 --- a/app/src/main/res/drawable-v26/ic_launcher_foreground.xml +++ b/app/src/main/res/drawable-v26/ic_launcher_foreground.xml @@ -1,33 +1,66 @@ - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/drawable/background_splash.xml b/app/src/main/res/drawable/background_splash.xml index 386b48047..7b36af3d2 100644 --- a/app/src/main/res/drawable/background_splash.xml +++ b/app/src/main/res/drawable/background_splash.xml @@ -1,5 +1,4 @@ - - - + + android:src="@drawable/mastodonlogo" /> \ No newline at end of file diff --git a/app/src/main/res/drawable/blue_border.xml b/app/src/main/res/drawable/blue_border.xml index 5a63b6ee2..b1903f8ee 100644 --- a/app/src/main/res/drawable/blue_border.xml +++ b/app/src/main/res/drawable/blue_border.xml @@ -1,11 +1,13 @@ - + - - - - + + + android:top="1dip" /> \ No newline at end of file diff --git a/app/src/main/res/drawable/blue_color.xml b/app/src/main/res/drawable/blue_color.xml index 3426d3213..538216236 100644 --- a/app/src/main/res/drawable/blue_color.xml +++ b/app/src/main/res/drawable/blue_color.xml @@ -1,5 +1,4 @@ - - + + \ No newline at end of file diff --git a/app/src/main/res/drawable/border_bottom.xml b/app/src/main/res/drawable/border_bottom.xml index 9bc08f339..1f4865872 100644 --- a/app/src/main/res/drawable/border_bottom.xml +++ b/app/src/main/res/drawable/border_bottom.xml @@ -8,8 +8,7 @@ android:right="-1dp" android:top="-1dp" android:bottom="1dp"> - + diff --git a/app/src/main/res/drawable/bot_background_round_corner.xml b/app/src/main/res/drawable/bot_background_round_corner.xml index c2e14f6bd..ba7f62473 100644 --- a/app/src/main/res/drawable/bot_background_round_corner.xml +++ b/app/src/main/res/drawable/bot_background_round_corner.xml @@ -1,6 +1,6 @@ - - + + diff --git a/app/src/main/res/drawable/card_border_black.xml b/app/src/main/res/drawable/card_border_black.xml index 94e454167..e34a2d7c8 100644 --- a/app/src/main/res/drawable/card_border_black.xml +++ b/app/src/main/res/drawable/card_border_black.xml @@ -1,11 +1,14 @@ - + - + - + \ No newline at end of file diff --git a/app/src/main/res/drawable/card_border_dark.xml b/app/src/main/res/drawable/card_border_dark.xml index 62c307b1d..ce2832e8e 100644 --- a/app/src/main/res/drawable/card_border_dark.xml +++ b/app/src/main/res/drawable/card_border_dark.xml @@ -1,11 +1,14 @@ - + - + - + \ No newline at end of file diff --git a/app/src/main/res/drawable/card_border_light.xml b/app/src/main/res/drawable/card_border_light.xml index a51e4e321..e29aa9164 100644 --- a/app/src/main/res/drawable/card_border_light.xml +++ b/app/src/main/res/drawable/card_border_light.xml @@ -1,11 +1,14 @@ - + - + - + \ No newline at end of file diff --git a/app/src/main/res/drawable/circular.xml b/app/src/main/res/drawable/circular.xml index 8a605c487..398fc7492 100644 --- a/app/src/main/res/drawable/circular.xml +++ b/app/src/main/res/drawable/circular.xml @@ -3,10 +3,10 @@ android:shape="oval" android:thicknessRatio="1.9" - android:useLevel="false" > + android:useLevel="false"> + android:width="10dp" + android:color="@android:color/white" /> \ No newline at end of file diff --git a/app/src/main/res/drawable/circular_black.xml b/app/src/main/res/drawable/circular_black.xml index f89d22c35..913217870 100644 --- a/app/src/main/res/drawable/circular_black.xml +++ b/app/src/main/res/drawable/circular_black.xml @@ -3,10 +3,10 @@ android:shape="oval" android:thicknessRatio="1.9" - android:useLevel="false" > + android:useLevel="false"> + android:width="10dp" + android:color="@android:color/black" /> \ No newline at end of file diff --git a/app/src/main/res/drawable/circular_dark.xml b/app/src/main/res/drawable/circular_dark.xml index ab66bb19f..fc729f48c 100644 --- a/app/src/main/res/drawable/circular_dark.xml +++ b/app/src/main/res/drawable/circular_dark.xml @@ -3,10 +3,10 @@ android:shape="oval" android:thicknessRatio="1.9" - android:useLevel="false" > + android:useLevel="false"> + android:width="10dp" + android:color="@color/notif_dark_3" /> \ No newline at end of file diff --git a/app/src/main/res/drawable/circular_mastodon.xml b/app/src/main/res/drawable/circular_mastodon.xml index 6f8bb6b80..a99d57810 100644 --- a/app/src/main/res/drawable/circular_mastodon.xml +++ b/app/src/main/res/drawable/circular_mastodon.xml @@ -3,10 +3,10 @@ android:shape="oval" android:thicknessRatio="1.9" - android:useLevel="false" > + android:useLevel="false"> + android:width="10dp" + android:color="@color/mastodonC4" /> \ No newline at end of file diff --git a/app/src/main/res/drawable/circular_peertube.xml b/app/src/main/res/drawable/circular_peertube.xml index f3607ce86..b9dce83ac 100644 --- a/app/src/main/res/drawable/circular_peertube.xml +++ b/app/src/main/res/drawable/circular_peertube.xml @@ -3,10 +3,10 @@ android:shape="oval" android:thicknessRatio="1.9" - android:useLevel="false" > + android:useLevel="false"> + android:width="10dp" + android:color="@color/peertube_orange" /> \ No newline at end of file diff --git a/app/src/main/res/drawable/default_banner.xml b/app/src/main/res/drawable/default_banner.xml index 90a7e8f63..e5ed7539e 100644 --- a/app/src/main/res/drawable/default_banner.xml +++ b/app/src/main/res/drawable/default_banner.xml @@ -3,8 +3,8 @@ android:height="90dp" android:viewportWidth="42.333332" android:viewportHeight="23.812502"> - + diff --git a/app/src/main/res/drawable/green_border.xml b/app/src/main/res/drawable/green_border.xml index dcf5c8e81..52ba23b5c 100644 --- a/app/src/main/res/drawable/green_border.xml +++ b/app/src/main/res/drawable/green_border.xml @@ -1,11 +1,13 @@ - + - - - - + + + android:top="1dip" /> \ No newline at end of file diff --git a/app/src/main/res/drawable/ic_all_inclusive_menu.xml b/app/src/main/res/drawable/ic_all_inclusive_menu.xml index cc4611da3..56656b07b 100644 --- a/app/src/main/res/drawable/ic_all_inclusive_menu.xml +++ b/app/src/main/res/drawable/ic_all_inclusive_menu.xml @@ -1,5 +1,10 @@ - - + + diff --git a/app/src/main/res/drawable/ic_audio_wave.xml b/app/src/main/res/drawable/ic_audio_wave.xml index 985e54381..07e9096c0 100644 --- a/app/src/main/res/drawable/ic_audio_wave.xml +++ b/app/src/main/res/drawable/ic_audio_wave.xml @@ -3,200 +3,200 @@ android:height="150dp" android:viewportWidth="105.83" android:viewportHeight="79.372"> - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_battery_alert_menu.xml b/app/src/main/res/drawable/ic_battery_alert_menu.xml index 7326767f5..39b1010ee 100644 --- a/app/src/main/res/drawable/ic_battery_alert_menu.xml +++ b/app/src/main/res/drawable/ic_battery_alert_menu.xml @@ -1,5 +1,10 @@ - - + + diff --git a/app/src/main/res/drawable/ic_bookmark_white.xml b/app/src/main/res/drawable/ic_bookmark_white.xml index 4b895836e..406c421ce 100644 --- a/app/src/main/res/drawable/ic_bookmark_white.xml +++ b/app/src/main/res/drawable/ic_bookmark_white.xml @@ -1,5 +1,10 @@ - - + + diff --git a/app/src/main/res/drawable/ic_bookmark_white_full.xml b/app/src/main/res/drawable/ic_bookmark_white_full.xml index feb16ed63..d0cd56690 100644 --- a/app/src/main/res/drawable/ic_bookmark_white_full.xml +++ b/app/src/main/res/drawable/ic_bookmark_white_full.xml @@ -1,5 +1,10 @@ - - + + diff --git a/app/src/main/res/drawable/ic_bot.xml b/app/src/main/res/drawable/ic_bot.xml index c9887221f..3a7d228f3 100644 --- a/app/src/main/res/drawable/ic_bot.xml +++ b/app/src/main/res/drawable/ic_bot.xml @@ -1,37 +1,73 @@ - - + - + - - - + + + - + - + - - + + - - + android:strokeColor="#B6E9FF" + android:strokeLineCap="round" + android:strokeLineJoin="round" + android:strokeWidth="2" /> + + diff --git a/app/src/main/res/drawable/ic_brush_edit.xml b/app/src/main/res/drawable/ic_brush_edit.xml index 2d95aa7a3..ca0e73f08 100644 --- a/app/src/main/res/drawable/ic_brush_edit.xml +++ b/app/src/main/res/drawable/ic_brush_edit.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M7,14c-1.66,0 -3,1.34 -3,3 0,1.31 -1.16,2 -2,2 0.92,1.22 2.49,2 4,2 2.21,0 4,-1.79 4,-4 0,-1.66 -1.34,-3 -3,-3zM20.71,4.63l-1.34,-1.34c-0.39,-0.39 -1.02,-0.39 -1.41,0L9,12.25 11.75,15l8.96,-8.96c0.39,-0.39 0.39,-1.02 0,-1.41z" /> diff --git a/app/src/main/res/drawable/ic_cached_black.xml b/app/src/main/res/drawable/ic_cached_black.xml index 5e776beb1..bb905c533 100644 --- a/app/src/main/res/drawable/ic_cached_black.xml +++ b/app/src/main/res/drawable/ic_cached_black.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M19,8l-4,4h3c0,3.31 -2.69,6 -6,6 -1.01,0 -1.97,-0.25 -2.8,-0.7l-1.46,1.46C8.97,19.54 10.43,20 12,20c4.42,0 8,-3.58 8,-8h3l-4,-4zM6,12c0,-3.31 2.69,-6 6,-6 1.01,0 1.97,0.25 2.8,0.7l1.46,-1.46C15.03,4.46 13.57,4 12,4c-4.42,0 -8,3.58 -8,8H1l4,4 4,-4H6z" /> diff --git a/app/src/main/res/drawable/ic_camera.xml b/app/src/main/res/drawable/ic_camera.xml index 371b59182..895218b51 100644 --- a/app/src/main/res/drawable/ic_camera.xml +++ b/app/src/main/res/drawable/ic_camera.xml @@ -1,12 +1,12 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,12m-3.2,0a3.2,3.2 0,1 1,6.4 0a3.2,3.2 0,1 1,-6.4 0" /> + android:pathData="M9,2L7.17,4L4,4c-1.1,0 -2,0.9 -2,2v12c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2L22,6c0,-1.1 -0.9,-2 -2,-2h-3.17L15,2L9,2zM12,17c-2.76,0 -5,-2.24 -5,-5s2.24,-5 5,-5 5,2.24 5,5 -2.24,5 -5,5z" /> diff --git a/app/src/main/res/drawable/ic_check_white_24.xml b/app/src/main/res/drawable/ic_check_white_24.xml index 17aca2af1..609f5657a 100644 --- a/app/src/main/res/drawable/ic_check_white_24.xml +++ b/app/src/main/res/drawable/ic_check_white_24.xml @@ -1,5 +1,10 @@ - - + + diff --git a/app/src/main/res/drawable/ic_crop.xml b/app/src/main/res/drawable/ic_crop.xml index cf5462c0d..c092bd084 100644 --- a/app/src/main/res/drawable/ic_crop.xml +++ b/app/src/main/res/drawable/ic_crop.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M17,15h2V7c0,-1.1 -0.9,-2 -2,-2H9v2h8v8zM7,17V1H5v4H1v2h4v10c0,1.1 0.9,2 2,2h10v4h2v-4h4v-2H7z" /> diff --git a/app/src/main/res/drawable/ic_drag_handle.xml b/app/src/main/res/drawable/ic_drag_handle.xml index 68a719052..8f7f335a3 100644 --- a/app/src/main/res/drawable/ic_drag_handle.xml +++ b/app/src/main/res/drawable/ic_drag_handle.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M20,9H4v2h16V9zM4,15h16v-2H4v2z" /> diff --git a/app/src/main/res/drawable/ic_drag_handle_menu.xml b/app/src/main/res/drawable/ic_drag_handle_menu.xml index 68a719052..8f7f335a3 100644 --- a/app/src/main/res/drawable/ic_drag_handle_menu.xml +++ b/app/src/main/res/drawable/ic_drag_handle_menu.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M20,9H4v2h16V9zM4,15h16v-2H4v2z" /> diff --git a/app/src/main/res/drawable/ic_edit_black_menu.xml b/app/src/main/res/drawable/ic_edit_black_menu.xml index 46462b572..133ea4462 100644 --- a/app/src/main/res/drawable/ic_edit_black_menu.xml +++ b/app/src/main/res/drawable/ic_edit_black_menu.xml @@ -1,5 +1,10 @@ - - + + diff --git a/app/src/main/res/drawable/ic_eraser.xml b/app/src/main/res/drawable/ic_eraser.xml index 688d346a3..881052451 100644 --- a/app/src/main/res/drawable/ic_eraser.xml +++ b/app/src/main/res/drawable/ic_eraser.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M6,19c0,1.1 0.9,2 2,2h8c1.1,0 2,-0.9 2,-2V7H6v12zM19,4h-3.5l-1,-1h-5l-1,1H5v2h14V4z" /> diff --git a/app/src/main/res/drawable/ic_fedilab_fg.xml b/app/src/main/res/drawable/ic_fedilab_fg.xml index f79d24a3f..7fb19b5bf 100644 --- a/app/src/main/res/drawable/ic_fedilab_fg.xml +++ b/app/src/main/res/drawable/ic_fedilab_fg.xml @@ -1,33 +1,66 @@ - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_gallery.xml b/app/src/main/res/drawable/ic_gallery.xml index eeed2d891..e468e5e3b 100644 --- a/app/src/main/res/drawable/ic_gallery.xml +++ b/app/src/main/res/drawable/ic_gallery.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M21,19V5c0,-1.1 -0.9,-2 -2,-2H5c-1.1,0 -2,0.9 -2,2v14c0,1.1 0.9,2 2,2h14c1.1,0 2,-0.9 2,-2zM8.5,13.5l2.5,3.01L14.5,12l4.5,6H5l3.5,-4.5z" /> diff --git a/app/src/main/res/drawable/ic_gif_preview.xml b/app/src/main/res/drawable/ic_gif_preview.xml index 18cc61bfc..312f39e87 100644 --- a/app/src/main/res/drawable/ic_gif_preview.xml +++ b/app/src/main/res/drawable/ic_gif_preview.xml @@ -3,26 +3,26 @@ android:height="32dp" android:viewportWidth="32" android:viewportHeight="32"> - - - - - + + + + + diff --git a/app/src/main/res/drawable/ic_gnu_social.xml b/app/src/main/res/drawable/ic_gnu_social.xml index a14c90623..da2b3e174 100644 --- a/app/src/main/res/drawable/ic_gnu_social.xml +++ b/app/src/main/res/drawable/ic_gnu_social.xml @@ -1,13 +1,31 @@ - - - - - - + + + + + + diff --git a/app/src/main/res/drawable/ic_group_work.xml b/app/src/main/res/drawable/ic_group_work.xml index 5c202b834..24adef271 100644 --- a/app/src/main/res/drawable/ic_group_work.xml +++ b/app/src/main/res/drawable/ic_group_work.xml @@ -1,5 +1,10 @@ - - + + diff --git a/app/src/main/res/drawable/ic_hide_status_bar.xml b/app/src/main/res/drawable/ic_hide_status_bar.xml index 743220b56..3a4ce3d93 100644 --- a/app/src/main/res/drawable/ic_hide_status_bar.xml +++ b/app/src/main/res/drawable/ic_hide_status_bar.xml @@ -1,5 +1,10 @@ - - + + diff --git a/app/src/main/res/drawable/ic_history_black.xml b/app/src/main/res/drawable/ic_history_black.xml index a61de1bc9..d9f75ea6d 100644 --- a/app/src/main/res/drawable/ic_history_black.xml +++ b/app/src/main/res/drawable/ic_history_black.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M13,3c-4.97,0 -9,4.03 -9,9L1,12l3.89,3.89 0.07,0.14L9,12L6,12c0,-3.87 3.13,-7 7,-7s7,3.13 7,7 -3.13,7 -7,7c-1.93,0 -3.68,-0.79 -4.94,-2.06l-1.42,1.42C8.27,19.99 10.51,21 13,21c4.97,0 9,-4.03 9,-9s-4.03,-9 -9,-9zM12,8v5l4.28,2.54 0.72,-1.21 -3.5,-2.08L13.5,8L12,8z" /> diff --git a/app/src/main/res/drawable/ic_info_white.xml b/app/src/main/res/drawable/ic_info_white.xml index 7be014728..ce292018b 100644 --- a/app/src/main/res/drawable/ic_info_white.xml +++ b/app/src/main/res/drawable/ic_info_white.xml @@ -1,5 +1,10 @@ - - + + diff --git a/app/src/main/res/drawable/ic_insert_chart.xml b/app/src/main/res/drawable/ic_insert_chart.xml index 13cfc8fad..69c53ba58 100644 --- a/app/src/main/res/drawable/ic_insert_chart.xml +++ b/app/src/main/res/drawable/ic_insert_chart.xml @@ -1,5 +1,10 @@ - - + + diff --git a/app/src/main/res/drawable/ic_insert_emoticon_media.xml b/app/src/main/res/drawable/ic_insert_emoticon_media.xml index d615de91a..b514b2f5a 100644 --- a/app/src/main/res/drawable/ic_insert_emoticon_media.xml +++ b/app/src/main/res/drawable/ic_insert_emoticon_media.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M11.99,2C6.47,2 2,6.48 2,12s4.47,10 9.99,10C17.52,22 22,17.52 22,12S17.52,2 11.99,2zM12,20c-4.42,0 -8,-3.58 -8,-8s3.58,-8 8,-8 8,3.58 8,8 -3.58,8 -8,8zM15.5,11c0.83,0 1.5,-0.67 1.5,-1.5S16.33,8 15.5,8 14,8.67 14,9.5s0.67,1.5 1.5,1.5zM8.5,11c0.83,0 1.5,-0.67 1.5,-1.5S9.33,8 8.5,8 7,8.67 7,9.5 7.67,11 8.5,11zM12,17.5c2.33,0 4.31,-1.46 5.11,-3.5L6.89,14c0.8,2.04 2.78,3.5 5.11,3.5z" /> diff --git a/app/src/main/res/drawable/ic_label_top_menu.xml b/app/src/main/res/drawable/ic_label_top_menu.xml index 230e2185c..c87bb221d 100644 --- a/app/src/main/res/drawable/ic_label_top_menu.xml +++ b/app/src/main/res/drawable/ic_label_top_menu.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M17.63,5.84C17.27,5.33 16.67,5 16,5L5,5.01C3.9,5.01 3,5.9 3,7v10c0,1.1 0.9,1.99 2,1.99L16,19c0.67,0 1.27,-0.33 1.63,-0.84L22,12l-4.37,-6.16z" /> diff --git a/app/src/main/res/drawable/ic_launcher_foreground.xml b/app/src/main/res/drawable/ic_launcher_foreground.xml index 58908eb3a..a24166cae 100644 --- a/app/src/main/res/drawable/ic_launcher_foreground.xml +++ b/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -3,37 +3,68 @@ android:height="108dp" android:viewportWidth="357.55405" android:viewportHeight="357.55405"> - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_list_peertube.xml b/app/src/main/res/drawable/ic_list_peertube.xml index 4c2fb8834..1471c52f5 100644 --- a/app/src/main/res/drawable/ic_list_peertube.xml +++ b/app/src/main/res/drawable/ic_list_peertube.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M3,13h2v-2L3,11v2zM3,17h2v-2L3,15v2zM3,9h2L5,7L3,7v2zM7,13h14v-2L7,11v2zM7,17h14v-2L7,15v2zM7,7v2h14L21,7L7,7z" /> diff --git a/app/src/main/res/drawable/ic_list_peertube_activity.xml b/app/src/main/res/drawable/ic_list_peertube_activity.xml index fd7111d5d..6cca0d54a 100644 --- a/app/src/main/res/drawable/ic_list_peertube_activity.xml +++ b/app/src/main/res/drawable/ic_list_peertube_activity.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M3,13h2v-2L3,11v2zM3,17h2v-2L3,15v2zM3,9h2L5,7L3,7v2zM7,13h14v-2L7,11v2zM7,17h14v-2L7,15v2zM7,7v2h14L21,7L7,7z" /> diff --git a/app/src/main/res/drawable/ic_list_timeline.xml b/app/src/main/res/drawable/ic_list_timeline.xml index 4c2fb8834..1471c52f5 100644 --- a/app/src/main/res/drawable/ic_list_timeline.xml +++ b/app/src/main/res/drawable/ic_list_timeline.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M3,13h2v-2L3,11v2zM3,17h2v-2L3,15v2zM3,9h2L5,7L3,7v2zM7,13h14v-2L7,11v2zM7,17h14v-2L7,15v2zM7,7v2h14L21,7L7,7z" /> diff --git a/app/src/main/res/drawable/ic_list_top_menu.xml b/app/src/main/res/drawable/ic_list_top_menu.xml index fd7111d5d..6cca0d54a 100644 --- a/app/src/main/res/drawable/ic_list_top_menu.xml +++ b/app/src/main/res/drawable/ic_list_top_menu.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M3,13h2v-2L3,11v2zM3,17h2v-2L3,15v2zM3,9h2L5,7L3,7v2zM7,13h14v-2L7,11v2zM7,17h14v-2L7,15v2zM7,7v2h14L21,7L7,7z" /> diff --git a/app/src/main/res/drawable/ic_logo_button.xml b/app/src/main/res/drawable/ic_logo_button.xml index c54162ebe..31d073566 100644 --- a/app/src/main/res/drawable/ic_logo_button.xml +++ b/app/src/main/res/drawable/ic_logo_button.xml @@ -1,33 +1,81 @@ - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/ic_make_tab_unvisible.xml b/app/src/main/res/drawable/ic_make_tab_unvisible.xml index 689f3f47c..c71061582 100644 --- a/app/src/main/res/drawable/ic_make_tab_unvisible.xml +++ b/app/src/main/res/drawable/ic_make_tab_unvisible.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,7c2.76,0 5,2.24 5,5 0,0.65 -0.13,1.26 -0.36,1.83l2.92,2.92c1.51,-1.26 2.7,-2.89 3.43,-4.75 -1.73,-4.39 -6,-7.5 -11,-7.5 -1.4,0 -2.74,0.25 -3.98,0.7l2.16,2.16C10.74,7.13 11.35,7 12,7zM2,4.27l2.28,2.28 0.46,0.46C3.08,8.3 1.78,10.02 1,12c1.73,4.39 6,7.5 11,7.5 1.55,0 3.03,-0.3 4.38,-0.84l0.42,0.42L19.73,22 21,20.73 3.27,3 2,4.27zM7.53,9.8l1.55,1.55c-0.05,0.21 -0.08,0.43 -0.08,0.65 0,1.66 1.34,3 3,3 0.22,0 0.44,-0.03 0.65,-0.08l1.55,1.55c-0.67,0.33 -1.41,0.53 -2.2,0.53 -2.76,0 -5,-2.24 -5,-5 0,-0.79 0.2,-1.53 0.53,-2.2zM11.84,9.02l3.15,3.15 0.02,-0.16c0,-1.66 -1.34,-3 -3,-3l-0.17,0.01z" /> diff --git a/app/src/main/res/drawable/ic_make_tab_visible.xml b/app/src/main/res/drawable/ic_make_tab_visible.xml index e02f1d191..64e742969 100644 --- a/app/src/main/res/drawable/ic_make_tab_visible.xml +++ b/app/src/main/res/drawable/ic_make_tab_visible.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12,4.5C7,4.5 2.73,7.61 1,12c1.73,4.39 6,7.5 11,7.5s9.27,-3.11 11,-7.5c-1.73,-4.39 -6,-7.5 -11,-7.5zM12,17c-2.76,0 -5,-2.24 -5,-5s2.24,-5 5,-5 5,2.24 5,5 -2.24,5 -5,5zM12,9c-1.66,0 -3,1.34 -3,3s1.34,3 3,3 3,-1.34 3,-3 -1.34,-3 -3,-3z" /> diff --git a/app/src/main/res/drawable/ic_mention_white.xml b/app/src/main/res/drawable/ic_mention_white.xml index efb7e76a5..30deeb397 100644 --- a/app/src/main/res/drawable/ic_mention_white.xml +++ b/app/src/main/res/drawable/ic_mention_white.xml @@ -1,5 +1,10 @@ - - + + diff --git a/app/src/main/res/drawable/ic_menu_menu.xml b/app/src/main/res/drawable/ic_menu_menu.xml index de103a677..47d7efa6e 100644 --- a/app/src/main/res/drawable/ic_menu_menu.xml +++ b/app/src/main/res/drawable/ic_menu_menu.xml @@ -1,5 +1,10 @@ - - + + diff --git a/app/src/main/res/drawable/ic_mode_comment_white.xml b/app/src/main/res/drawable/ic_mode_comment_white.xml index 480b87a57..2366bcf4b 100644 --- a/app/src/main/res/drawable/ic_mode_comment_white.xml +++ b/app/src/main/res/drawable/ic_mode_comment_white.xml @@ -1,5 +1,10 @@ - - + + diff --git a/app/src/main/res/drawable/ic_more_horiz_black.xml b/app/src/main/res/drawable/ic_more_horiz_black.xml index 21297cbaa..738417014 100644 --- a/app/src/main/res/drawable/ic_more_horiz_black.xml +++ b/app/src/main/res/drawable/ic_more_horiz_black.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M6,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2zM18,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2zM12,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2z" /> diff --git a/app/src/main/res/drawable/ic_new_releases_black.xml b/app/src/main/res/drawable/ic_new_releases_black.xml index 75439c309..94e57c43d 100644 --- a/app/src/main/res/drawable/ic_new_releases_black.xml +++ b/app/src/main/res/drawable/ic_new_releases_black.xml @@ -1,5 +1,10 @@ - - + + diff --git a/app/src/main/res/drawable/ic_notifications_menu.xml b/app/src/main/res/drawable/ic_notifications_menu.xml index 2ad953fe2..5fc97dd9a 100644 --- a/app/src/main/res/drawable/ic_notifications_menu.xml +++ b/app/src/main/res/drawable/ic_notifications_menu.xml @@ -1,5 +1,10 @@ - - + + diff --git a/app/src/main/res/drawable/ic_photo_filter.xml b/app/src/main/res/drawable/ic_photo_filter.xml index 30d702bb3..7689361b8 100644 --- a/app/src/main/res/drawable/ic_photo_filter.xml +++ b/app/src/main/res/drawable/ic_photo_filter.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M19.02,10v9L5,19L5,5h9L14,3L5.02,3c-1.1,0 -2,0.9 -2,2v14c0,1.1 0.9,2 2,2h14c1.1,0 2,-0.9 2,-2v-9h-2zM17,10l0.94,-2.06L20,7l-2.06,-0.94L17,4l-0.94,2.06L14,7l2.06,0.94zM13.25,10.75L12,8l-1.25,2.75L8,12l2.75,1.25L12,16l1.25,-2.75L16,12z" /> diff --git a/app/src/main/res/drawable/ic_pixelfed_comment.xml b/app/src/main/res/drawable/ic_pixelfed_comment.xml index c2da2cee2..052eb9133 100644 --- a/app/src/main/res/drawable/ic_pixelfed_comment.xml +++ b/app/src/main/res/drawable/ic_pixelfed_comment.xml @@ -1,6 +1,12 @@ - - + + android:strokeColor="#000000" + android:strokeLineCap="round" + android:strokeWidth="3" /> diff --git a/app/src/main/res/drawable/ic_pixelfed_share.xml b/app/src/main/res/drawable/ic_pixelfed_share.xml index c5ab44340..72848b653 100644 --- a/app/src/main/res/drawable/ic_pixelfed_share.xml +++ b/app/src/main/res/drawable/ic_pixelfed_share.xml @@ -1,4 +1,9 @@ - - + + diff --git a/app/src/main/res/drawable/ic_redo.xml b/app/src/main/res/drawable/ic_redo.xml index f2f0b1ff3..239699f64 100644 --- a/app/src/main/res/drawable/ic_redo.xml +++ b/app/src/main/res/drawable/ic_redo.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M18.4,10.6C16.55,8.99 14.15,8 11.5,8c-4.65,0 -8.58,3.03 -9.96,7.22L3.9,16c1.05,-3.19 4.05,-5.5 7.6,-5.5 1.95,0 3.73,0.72 5.12,1.88L13,16h9V7l-3.6,3.6z" /> diff --git a/app/src/main/res/drawable/ic_remove_white.xml b/app/src/main/res/drawable/ic_remove_white.xml index f6e9e9416..f9d32fba9 100644 --- a/app/src/main/res/drawable/ic_remove_white.xml +++ b/app/src/main/res/drawable/ic_remove_white.xml @@ -1,5 +1,10 @@ - - + + diff --git a/app/src/main/res/drawable/ic_save_gallery.xml b/app/src/main/res/drawable/ic_save_gallery.xml index 0922c4fa3..31d094a68 100644 --- a/app/src/main/res/drawable/ic_save_gallery.xml +++ b/app/src/main/res/drawable/ic_save_gallery.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M17,3L5,3c-1.11,0 -2,0.9 -2,2v14c0,1.1 0.89,2 2,2h14c1.1,0 2,-0.9 2,-2L21,7l-4,-4zM12,19c-1.66,0 -3,-1.34 -3,-3s1.34,-3 3,-3 3,1.34 3,3 -1.34,3 -3,3zM15,9L5,9L5,5h10v4z" /> diff --git a/app/src/main/res/drawable/ic_security_admin.xml b/app/src/main/res/drawable/ic_security_admin.xml index d66f92794..c9b7c8f0a 100644 --- a/app/src/main/res/drawable/ic_security_admin.xml +++ b/app/src/main/res/drawable/ic_security_admin.xml @@ -1,5 +1,10 @@ - - + + diff --git a/app/src/main/res/drawable/ic_security_admin_menu.xml b/app/src/main/res/drawable/ic_security_admin_menu.xml index f47a5deae..499450038 100644 --- a/app/src/main/res/drawable/ic_security_admin_menu.xml +++ b/app/src/main/res/drawable/ic_security_admin_menu.xml @@ -1,5 +1,10 @@ - - + + diff --git a/app/src/main/res/drawable/ic_show_stats.xml b/app/src/main/res/drawable/ic_show_stats.xml index f62b9850a..df7f089e8 100644 --- a/app/src/main/res/drawable/ic_show_stats.xml +++ b/app/src/main/res/drawable/ic_show_stats.xml @@ -1,5 +1,10 @@ - - + + diff --git a/app/src/main/res/drawable/ic_sticker.xml b/app/src/main/res/drawable/ic_sticker.xml index 230e2185c..c87bb221d 100644 --- a/app/src/main/res/drawable/ic_sticker.xml +++ b/app/src/main/res/drawable/ic_sticker.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M17.63,5.84C17.27,5.33 16.67,5 16,5L5,5.01C3.9,5.01 3,5.9 3,7v10c0,1.1 0.9,1.99 2,1.99L16,19c0.67,0 1.27,-0.33 1.63,-0.84L22,12l-4.37,-6.16z" /> diff --git a/app/src/main/res/drawable/ic_tablet_menu.xml b/app/src/main/res/drawable/ic_tablet_menu.xml index d235bada4..826ff9fe5 100644 --- a/app/src/main/res/drawable/ic_tablet_menu.xml +++ b/app/src/main/res/drawable/ic_tablet_menu.xml @@ -1,5 +1,10 @@ - - + + diff --git a/app/src/main/res/drawable/ic_tag_timeline.xml b/app/src/main/res/drawable/ic_tag_timeline.xml index 1aa8d10ab..0e887d432 100644 --- a/app/src/main/res/drawable/ic_tag_timeline.xml +++ b/app/src/main/res/drawable/ic_tag_timeline.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M17.63,5.84C17.27,5.33 16.67,5 16,5L5,5.01C3.9,5.01 3,5.9 3,7v10c0,1.1 0.9,1.99 2,1.99L16,19c0.67,0 1.27,-0.33 1.63,-0.84L22,12l-4.37,-6.16z" /> diff --git a/app/src/main/res/drawable/ic_text.xml b/app/src/main/res/drawable/ic_text.xml index 7a1c4feec..ce64d10f2 100644 --- a/app/src/main/res/drawable/ic_text.xml +++ b/app/src/main/res/drawable/ic_text.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M2.5,4v3h5v12h3L10.5,7h5L15.5,4h-13zM21.5,9h-9v3h3v7h3v-7h3L21.5,9z" /> diff --git a/app/src/main/res/drawable/ic_timelapse.xml b/app/src/main/res/drawable/ic_timelapse.xml index 6466e4fae..f9fc9eba1 100644 --- a/app/src/main/res/drawable/ic_timelapse.xml +++ b/app/src/main/res/drawable/ic_timelapse.xml @@ -1,5 +1,10 @@ - - + + diff --git a/app/src/main/res/drawable/ic_timeline_menu_s.xml b/app/src/main/res/drawable/ic_timeline_menu_s.xml index b3e257bf2..eef4821c0 100644 --- a/app/src/main/res/drawable/ic_timeline_menu_s.xml +++ b/app/src/main/res/drawable/ic_timeline_menu_s.xml @@ -1,5 +1,10 @@ - - + + diff --git a/app/src/main/res/drawable/ic_translate_white.xml b/app/src/main/res/drawable/ic_translate_white.xml index 61f4a78eb..4c5c302fa 100644 --- a/app/src/main/res/drawable/ic_translate_white.xml +++ b/app/src/main/res/drawable/ic_translate_white.xml @@ -1,5 +1,10 @@ - - + + diff --git a/app/src/main/res/drawable/ic_undo.xml b/app/src/main/res/drawable/ic_undo.xml index 7139439cc..7ad297d93 100644 --- a/app/src/main/res/drawable/ic_undo.xml +++ b/app/src/main/res/drawable/ic_undo.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M12.5,8c-2.65,0 -5.05,0.99 -6.9,2.6L2,7v9h9l-3.62,-3.62c1.39,-1.16 3.16,-1.88 5.12,-1.88 3.54,0 6.55,2.31 7.6,5.5l2.37,-0.78C21.08,11.03 17.15,8 12.5,8z" /> diff --git a/app/src/main/res/drawable/ic_video_peertube.xml b/app/src/main/res/drawable/ic_video_peertube.xml index f808aee58..a616252a6 100644 --- a/app/src/main/res/drawable/ic_video_peertube.xml +++ b/app/src/main/res/drawable/ic_video_peertube.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M4,6L2,6v14c0,1.1 0.9,2 2,2h14v-2L4,20L4,6zM20,2L8,2c-1.1,0 -2,0.9 -2,2v12c0,1.1 0.9,2 2,2h12c1.1,0 2,-0.9 2,-2L22,4c0,-1.1 -0.9,-2 -2,-2zM12,14.5v-9l6,4.5 -6,4.5z" /> diff --git a/app/src/main/res/drawable/ic_video_preview.xml b/app/src/main/res/drawable/ic_video_preview.xml index bb38810de..9273d452e 100644 --- a/app/src/main/res/drawable/ic_video_preview.xml +++ b/app/src/main/res/drawable/ic_video_preview.xml @@ -1,5 +1,12 @@ - - - + + + diff --git a/app/src/main/res/drawable/ic_view_list_poll.xml b/app/src/main/res/drawable/ic_view_list_poll.xml index 82fb90a2b..2c89fde7c 100644 --- a/app/src/main/res/drawable/ic_view_list_poll.xml +++ b/app/src/main/res/drawable/ic_view_list_poll.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M4,14h4v-4L4,10v4zM4,19h4v-4L4,15v4zM4,9h4L8,5L4,5v4zM9,14h12v-4L9,10v4zM9,19h12v-4L9,15v4zM9,5v4h12L21,5L9,5z" /> diff --git a/app/src/main/res/drawable/ic_view_list_poll_notif.xml b/app/src/main/res/drawable/ic_view_list_poll_notif.xml index 78118c161..623aa9fad 100644 --- a/app/src/main/res/drawable/ic_view_list_poll_notif.xml +++ b/app/src/main/res/drawable/ic_view_list_poll_notif.xml @@ -1,9 +1,9 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> + android:pathData="M4,14h4v-4L4,10v4zM4,19h4v-4L4,15v4zM4,9h4L8,5L4,5v4zM9,14h12v-4L9,10v4zM9,19h12v-4L9,15v4zM9,5v4h12L21,5L9,5z" /> diff --git a/app/src/main/res/drawable/ic_visibility_off_menu.xml b/app/src/main/res/drawable/ic_visibility_off_menu.xml index 44c4a85a9..4ac21c06b 100644 --- a/app/src/main/res/drawable/ic_visibility_off_menu.xml +++ b/app/src/main/res/drawable/ic_visibility_off_menu.xml @@ -1,5 +1,10 @@ - - + + diff --git a/app/src/main/res/drawable/ic_zoom_out.xml b/app/src/main/res/drawable/ic_zoom_out.xml index dc55311f3..91274e7e3 100644 --- a/app/src/main/res/drawable/ic_zoom_out.xml +++ b/app/src/main/res/drawable/ic_zoom_out.xml @@ -3,9 +3,9 @@ android:height="24dp" android:viewportWidth="24" android:viewportHeight="24"> - - - + + + diff --git a/app/src/main/res/drawable/imageview_border.xml b/app/src/main/res/drawable/imageview_border.xml index 30e81ab2a..382d1d8df 100644 --- a/app/src/main/res/drawable/imageview_border.xml +++ b/app/src/main/res/drawable/imageview_border.xml @@ -1,7 +1,12 @@ - - + \ No newline at end of file diff --git a/app/src/main/res/drawable/imageview_border_black.xml b/app/src/main/res/drawable/imageview_border_black.xml index d7d8c85b4..77a7133f4 100644 --- a/app/src/main/res/drawable/imageview_border_black.xml +++ b/app/src/main/res/drawable/imageview_border_black.xml @@ -1,7 +1,12 @@ - - + \ No newline at end of file diff --git a/app/src/main/res/drawable/imageview_border_dark.xml b/app/src/main/res/drawable/imageview_border_dark.xml index f9538d26b..f719c8bfc 100644 --- a/app/src/main/res/drawable/imageview_border_dark.xml +++ b/app/src/main/res/drawable/imageview_border_dark.xml @@ -1,7 +1,12 @@ - - + \ No newline at end of file diff --git a/app/src/main/res/drawable/media_message_border.xml b/app/src/main/res/drawable/media_message_border.xml index e23c5738c..78e02e5a2 100644 --- a/app/src/main/res/drawable/media_message_border.xml +++ b/app/src/main/res/drawable/media_message_border.xml @@ -1,17 +1,20 @@ - + - + - + android:bottom="1dp" /> - + \ No newline at end of file diff --git a/app/src/main/res/drawable/menu_item_selector.xml b/app/src/main/res/drawable/menu_item_selector.xml index 9e3876523..b6bb25816 100644 --- a/app/src/main/res/drawable/menu_item_selector.xml +++ b/app/src/main/res/drawable/menu_item_selector.xml @@ -1,9 +1,9 @@ - - - - - - + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/menu_item_selector_black.xml b/app/src/main/res/drawable/menu_item_selector_black.xml index 8886ca0f1..98f16dde7 100644 --- a/app/src/main/res/drawable/menu_item_selector_black.xml +++ b/app/src/main/res/drawable/menu_item_selector_black.xml @@ -1,9 +1,9 @@ - - - - - - + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/menu_item_selector_light.xml b/app/src/main/res/drawable/menu_item_selector_light.xml index 08230f77e..81920e103 100644 --- a/app/src/main/res/drawable/menu_item_selector_light.xml +++ b/app/src/main/res/drawable/menu_item_selector_light.xml @@ -1,9 +1,9 @@ - - - - - - + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/quick_reply_background.xml b/app/src/main/res/drawable/quick_reply_background.xml index 1846bfa12..ed4f9ff61 100644 --- a/app/src/main/res/drawable/quick_reply_background.xml +++ b/app/src/main/res/drawable/quick_reply_background.xml @@ -1,5 +1,5 @@ - - + + \ No newline at end of file diff --git a/app/src/main/res/drawable/quick_reply_background_black.xml b/app/src/main/res/drawable/quick_reply_background_black.xml index 95f7b3e0b..a291f9abd 100644 --- a/app/src/main/res/drawable/quick_reply_background_black.xml +++ b/app/src/main/res/drawable/quick_reply_background_black.xml @@ -1,5 +1,5 @@ - - + + \ No newline at end of file diff --git a/app/src/main/res/drawable/quick_reply_background_light.xml b/app/src/main/res/drawable/quick_reply_background_light.xml index 99e564ce3..4229165a7 100644 --- a/app/src/main/res/drawable/quick_reply_background_light.xml +++ b/app/src/main/res/drawable/quick_reply_background_light.xml @@ -1,5 +1,5 @@ - - + + \ No newline at end of file diff --git a/app/src/main/res/drawable/red_border.xml b/app/src/main/res/drawable/red_border.xml index 4879a1244..bc97c685f 100644 --- a/app/src/main/res/drawable/red_border.xml +++ b/app/src/main/res/drawable/red_border.xml @@ -1,11 +1,13 @@ - + - - - - + + + android:top="1dip" /> \ No newline at end of file diff --git a/app/src/main/res/drawable/rounded_corner_10.xml b/app/src/main/res/drawable/rounded_corner_10.xml index a3be18c0e..1d5ca0768 100644 --- a/app/src/main/res/drawable/rounded_corner_10.xml +++ b/app/src/main/res/drawable/rounded_corner_10.xml @@ -1,5 +1,5 @@ + android:shape="rectangle"> \ No newline at end of file diff --git a/app/src/main/res/drawable/rounded_label_sensitive.xml b/app/src/main/res/drawable/rounded_label_sensitive.xml index 94100870a..74c364724 100644 --- a/app/src/main/res/drawable/rounded_label_sensitive.xml +++ b/app/src/main/res/drawable/rounded_label_sensitive.xml @@ -1,5 +1,5 @@ - + diff --git a/app/src/main/res/drawable/shape_border_bottom_settings.xml b/app/src/main/res/drawable/shape_border_bottom_settings.xml index dad6a5503..b089c7fe9 100644 --- a/app/src/main/res/drawable/shape_border_bottom_settings.xml +++ b/app/src/main/res/drawable/shape_border_bottom_settings.xml @@ -2,12 +2,15 @@ - + - + - + - + - + - + - + \ No newline at end of file diff --git a/app/src/main/res/drawable/unfollow_color.xml b/app/src/main/res/drawable/unfollow_color.xml index c7a67b6bc..a30c51f10 100644 --- a/app/src/main/res/drawable/unfollow_color.xml +++ b/app/src/main/res/drawable/unfollow_color.xml @@ -1,5 +1,4 @@ - - + + \ No newline at end of file diff --git a/app/src/main/res/drawable/verified.xml b/app/src/main/res/drawable/verified.xml index 28afc3cdc..c20e886b1 100644 --- a/app/src/main/res/drawable/verified.xml +++ b/app/src/main/res/drawable/verified.xml @@ -1,6 +1,5 @@ - diff --git a/app/src/main/res/layout-sw600dp/activity_about.xml b/app/src/main/res/layout-sw600dp/activity_about.xml index 4f6510284..e170a8b13 100644 --- a/app/src/main/res/layout-sw600dp/activity_about.xml +++ b/app/src/main/res/layout-sw600dp/activity_about.xml @@ -1,5 +1,4 @@ - - + android:scrollbars="none" /> + +