From 0bdc58d5088240a2ed337f7eca6a7d4a63e974ec Mon Sep 17 00:00:00 2001 From: tom79 Date: Sun, 8 Mar 2020 10:29:06 +0100 Subject: [PATCH] Still cleaning code --- .../android/activities/AdminActivity.java | 3 +- .../android/activities/BaseActivity.java | 2 +- .../android/activities/BaseMainActivity.java | 57 +- .../activities/EditProfileActivity.java | 6 +- .../activities/InstanceHealthActivity.java | 2 +- .../activities/InstanceProfileActivity.java | 11 +- ...eNotificationSettingsAccountsActivity.java | 2 +- .../android/activities/LoginActivity.java | 26 +- .../activities/OwnerNotificationActivity.java | 3 +- .../android/activities/PeertubeActivity.java | 2 +- .../activities/PeertubeUploadActivity.java | 3 +- .../activities/PhotoEditorActivity.java | 4 +- .../activities/PixelfedComposeActivity.java | 16 +- .../android/activities/PlaylistsActivity.java | 2 +- .../activities/ReorderTimelinesActivity.java | 12 +- .../activities/SearchResultActivity.java | 12 +- .../activities/SearchResultTabActivity.java | 3 +- .../android/activities/SettingsActivity.java | 2 +- .../activities/ShowAccountActivity.java | 28 +- .../activities/ShowConversationActivity.java | 1 - .../activities/SlideMediaActivity.java | 12 +- .../android/activities/TootActivity.java | 1767 +++++++---------- .../android/activities/TootInfoActivity.java | 2 +- .../android/activities/WebviewActivity.java | 181 +- .../activities/WebviewConnectActivity.java | 54 +- .../asynctasks/ManageFiltersAsyncTask.java | 1 + .../asynctasks/ManageListsAsyncTask.java | 1 + .../asynctasks/ManagePlaylistsAsyncTask.java | 1 + .../asynctasks/RetrieveFeedsAsyncTask.java | 7 +- .../RetrieveIdentityProofAsyncTask.java | 1 - .../asynctasks/RetrieveMetaDataAsyncTask.java | 2 +- .../RetrieveRemoteDataAsyncTask.java | 2 +- .../asynctasks/RetrieveSearchAsyncTask.java | 4 +- .../asynctasks/RetrieveStoriesAsyncTask.java | 17 +- .../asynctasks/SyncBookmarksAsyncTask.java | 1 + .../UpdateAccountInfoByIDAsyncTask.java | 2 +- .../java/app/fedilab/android/client/API.java | 490 +++-- .../android/client/Entities/Attachment.java | 47 +- .../client/Entities/ManageTimelines.java | 15 +- .../android/client/Entities/Notification.java | 3 +- .../android/client/Entities/Peertube.java | 10 +- .../android/client/Entities/PollOptions.java | 1 + .../android/client/Entities/Status.java | 361 ++-- .../fedilab/android/client/Entities/Tag.java | 38 +- .../client/Entities/TrendsHistory.java | 41 +- .../app/fedilab/android/client/GNUAPI.java | 12 +- .../android/client/HttpsConnection.java | 30 +- .../fedilab/android/client/PeertubeAPI.java | 16 +- .../fedilab/android/client/PixelfedAPI.java | 279 ++- .../android/client/Tls12SocketFactory.java | 1 - .../drawers/AccountSearchDevAdapter.java | 4 +- .../drawers/AccountsFollowRequestAdapter.java | 2 +- .../android/drawers/AccountsListAdapter.java | 2 +- .../android/drawers/AccountsReplyAdapter.java | 3 +- .../android/drawers/CustomEmojiAdapter.java | 52 +- .../drawers/IdentityProofsAdapter.java | 7 +- .../drawers/NotificationsListAdapter.java | 29 +- .../PeertubeNotificationsListAdapter.java | 1 - .../android/drawers/PixelfedListAdapter.java | 2 +- .../drawers/PixelfedStoriesListAdapter.java | 73 +- .../android/drawers/SliderAdapter.java | 1 - .../android/drawers/StatusListAdapter.java | 114 +- .../android/drawers/TrendsAdapter.java | 9 +- .../fragments/ColorSettingsFragment.java | 8 +- .../fragments/ContentSettingsFragment.java | 5 +- .../DisplayNotificationsFragment.java | 2 + .../fragments/DisplayStatusFragment.java | 27 +- .../fragments/DisplayStoriesFragment.java | 24 +- .../fragments/MediaSliderFragment.java | 2 +- .../TabLayoutNotificationsFragment.java | 2 +- .../fragments/TabLayoutScheduleFragment.java | 2 +- .../fragments/TabLayoutTootsFragment.java | 2 +- .../fedilab/android/helper/CrossActions.java | 13 +- .../app/fedilab/android/helper/Helper.java | 60 +- .../helper/LongClickLinkMovementMethod.java | 32 +- .../android/jobs/NotificationsSyncJob.java | 4 +- .../LiveNotificationDelayedService.java | 23 +- .../services/LiveNotificationService.java | 26 +- .../RestartLiveNotificationReceiver.java | 2 +- .../StopDelayedNotificationReceiver.java | 3 +- .../StopLiveNotificationReceiver.java | 4 +- .../StreamingFederatedTimelineService.java | 1 + .../StreamingHomeTimelineService.java | 1 + .../StreamingLocalTimelineService.java | 1 + .../fedilab/android/sqlite/AccountDAO.java | 2 +- .../webview/MastalabWebViewClient.java | 2 +- .../fedilab/android/webview/ProxyHelper.java | 1 - 87 files changed, 1862 insertions(+), 2282 deletions(-) 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 f61ae4e24..8a1afb4ee 100644 --- a/app/src/main/java/app/fedilab/android/activities/AdminActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/AdminActivity.java @@ -313,7 +313,7 @@ public class AdminActivity extends BaseActivity { private class AdminPagerAdapter extends FragmentStatePagerAdapter { AdminPagerAdapter(FragmentManager fm) { - super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT); + super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT); } @NotNull @@ -344,6 +344,7 @@ public class AdminActivity extends BaseActivity { public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { } + @Override public int getCount() { return 2; 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 5cc2f6c4b..5e552741f 100644 --- a/app/src/main/java/app/fedilab/android/activities/BaseActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/BaseActivity.java @@ -65,7 +65,7 @@ public class BaseActivity extends CyaneaAppCompatActivity { .detectLeakedRegistrationObjects() .detectActivityLeaks() .penaltyLog() - // .penaltyDeath() + // .penaltyDeath() .build()); } canShowActionMode = true; 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 cb4e2f53c..625ab036b 100644 --- a/app/src/main/java/app/fedilab/android/activities/BaseMainActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/BaseMainActivity.java @@ -433,13 +433,11 @@ public abstract class BaseMainActivity extends BaseActivity pTabLocal.setCustomView(R.layout.tab_badge); - - - Helper.changeDrawableColor(getApplicationContext(),R.drawable.ic_subscriptions, R.attr.iconColorMenu); - Helper.changeDrawableColor(getApplicationContext(),R.drawable.ic_overview, R.attr.iconColorMenu); - Helper.changeDrawableColor(getApplicationContext(),R.drawable.ic_trending_up, R.attr.iconColorMenu); - Helper.changeDrawableColor(getApplicationContext(),R.drawable.ic_recently_added, R.attr.iconColorMenu); - Helper.changeDrawableColor(getApplicationContext(),R.drawable.ic_home, R.attr.iconColorMenu); + Helper.changeDrawableColor(getApplicationContext(), R.drawable.ic_subscriptions, R.attr.iconColorMenu); + Helper.changeDrawableColor(getApplicationContext(), R.drawable.ic_overview, R.attr.iconColorMenu); + Helper.changeDrawableColor(getApplicationContext(), R.drawable.ic_trending_up, R.attr.iconColorMenu); + Helper.changeDrawableColor(getApplicationContext(), R.drawable.ic_recently_added, R.attr.iconColorMenu); + Helper.changeDrawableColor(getApplicationContext(), R.drawable.ic_home, R.attr.iconColorMenu); @SuppressWarnings("ConstantConditions") @SuppressLint("CutPasteId") @@ -532,9 +530,9 @@ public abstract class BaseMainActivity extends BaseActivity //TabLayout.Tab pfTabDiscover = tabLayout.newTab(); - Helper.changeDrawableColor(getApplicationContext(),R.drawable.ic_notifications, R.attr.iconColorMenu); - Helper.changeDrawableColor(getApplicationContext(),R.drawable.ic_people, R.attr.iconColorMenu); - Helper.changeDrawableColor(getApplicationContext(),R.drawable.ic_home, R.attr.iconColorMenu); + Helper.changeDrawableColor(getApplicationContext(), R.drawable.ic_notifications, R.attr.iconColorMenu); + Helper.changeDrawableColor(getApplicationContext(), R.drawable.ic_people, R.attr.iconColorMenu); + Helper.changeDrawableColor(getApplicationContext(), R.drawable.ic_home, R.attr.iconColorMenu); pfTabHome.setCustomView(R.layout.tab_badge); pfTabLocal.setCustomView(R.layout.tab_badge); @@ -1119,7 +1117,7 @@ public abstract class BaseMainActivity extends BaseActivity MenuFloating.tags = new ArrayList<>(); Helper.updateHeaderAccountInfo(activity, account, headerLayout); //Locked account can see follow request - if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA ) { + if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { if (account.isLocked()) { navigationView.getMenu().findItem(R.id.nav_follow_request).setVisible(true); } else { @@ -1265,14 +1263,15 @@ public abstract class BaseMainActivity extends BaseActivity try { Handler handler = new Handler(); handler.postDelayed(dialogBuilderOptin::show, 1000); - } catch (Exception ignored) {} + } catch (Exception ignored) { + } - }else{ + } else { int lastReleaseNoteRead = sharedpreferences.getInt(Helper.SET_POPUP_RELEASE_NOTES, 0); int versionCode = BuildConfig.VERSION_CODE; - if( lastReleaseNoteRead != versionCode ){ //Need to push release notes - if( social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA ) { + if (lastReleaseNoteRead != versionCode) { //Need to push release notes + if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { new RetrieveRemoteDataAsyncTask(getApplicationContext(), BaseMainActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } try (BufferedReader reader = new BufferedReader( @@ -1660,11 +1659,6 @@ public abstract class BaseMainActivity extends BaseActivity } - - - - - @Override protected void onPause() { super.onPause(); @@ -1714,7 +1708,8 @@ public abstract class BaseMainActivity extends BaseActivity Intent myIntent = new Intent(BaseMainActivity.this, OwnerStatusActivity.class); startActivity(myIntent); return false; - }if (id == R.id.nav_trends) { + } + if (id == R.id.nav_trends) { Intent myIntent = new Intent(BaseMainActivity.this, SearchResultActivity.class); Bundle b = new Bundle(); b.putString("search", "fedilab_trend"); @@ -2037,7 +2032,7 @@ public abstract class BaseMainActivity extends BaseActivity return; List accounts = results.getAccounts(); List statuses = results.getStatuses(); - if( !developerAccount) { + if (!developerAccount) { if (accounts != null && accounts.size() > 0) { Intent intent = new Intent(BaseMainActivity.this, ShowAccountActivity.class); @@ -2052,8 +2047,8 @@ public abstract class BaseMainActivity extends BaseActivity intent.putExtras(b); startActivity(intent); } - }else{ - if( accounts != null && accounts.size() > 0 ) { + } else { + if (accounts != null && accounts.size() > 0) { developers = new ArrayList<>(); developers.addAll(accounts); new RetrieveRelationshipAsyncTask(getApplicationContext(), accounts.get(0).getId(), BaseMainActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); @@ -2063,10 +2058,10 @@ public abstract class BaseMainActivity extends BaseActivity @Override public void onRetrieveRelationship(Relationship relationship, Error error) { - if( dialogReleaseNoteView != null && developers != null && developers.size() > 0){ - if( !relationship.isFollowing()){ + if (dialogReleaseNoteView != null && developers != null && developers.size() > 0) { + if (!relationship.isFollowing()) { TextView dev_follow_title = dialogReleaseNoteView.findViewById(R.id.dev_follow_title); - if( dev_follow_title != null){ + if (dev_follow_title != null) { dev_follow_title.setVisibility(View.VISIBLE); } ExpandableHeightListView lv_developers = dialogReleaseNoteView.findViewById(R.id.lv_developers); @@ -2364,7 +2359,6 @@ public abstract class BaseMainActivity extends BaseActivity } - public enum iconLauncher { BUBBLES, FEDIVERSE, @@ -2381,12 +2375,11 @@ public abstract class BaseMainActivity extends BaseActivity int mNumOfTabs; private PagerAdapter(FragmentManager fm, int NumOfTabs) { - super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT); + super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT); this.mNumOfTabs = NumOfTabs; } - @Override public Parcelable saveState() { return null; @@ -2504,7 +2497,7 @@ public abstract class BaseMainActivity extends BaseActivity bundle.putSerializable("type", DisplayNotificationsFragment.Type.ALL); fragment.setArguments(bundle); return fragment; - }else { + } else { DisplayStoriesFragment fragment = new DisplayStoriesFragment(); bundle.putSerializable("type", RetrieveStoriesAsyncTask.type.ME); fragment.setArguments(bundle); @@ -2520,7 +2513,7 @@ public abstract class BaseMainActivity extends BaseActivity } else { mPageReferenceMap = new HashMap<>(); } - // super.destroyItem(container, position, object); + // super.destroyItem(container, position, object); } @Override 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 84c95cc20..788e285d1 100644 --- a/app/src/main/java/app/fedilab/android/activities/EditProfileActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/EditProfileActivity.java @@ -16,7 +16,6 @@ package app.fedilab.android.activities; import android.Manifest; -import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; @@ -70,7 +69,6 @@ import app.fedilab.android.client.APIResponse; import app.fedilab.android.client.Entities.Account; import app.fedilab.android.client.Entities.Error; import app.fedilab.android.client.Entities.Version; -import app.fedilab.android.client.Glide.GlideApp; import app.fedilab.android.helper.Helper; import app.fedilab.android.interfaces.OnRetrieveAccountInterface; import app.fedilab.android.interfaces.OnUpdateCredentialInterface; @@ -241,7 +239,7 @@ public class EditProfileActivity extends BaseActivity implements OnRetrieveAccou @Override public void afterTextChanged(Editable s) { int maxChar = 160; - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA){ + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { maxChar = 500; } if (s.length() > maxChar) { @@ -354,7 +352,7 @@ public class EditProfileActivity extends BaseActivity implements OnRetrieveAccou } }); - if( !EditProfileActivity.this.isFinishing()) { + if (!EditProfileActivity.this.isFinishing()) { Glide.with(set_profile_picture.getContext()) .load(account.getAvatar()) .into(set_profile_picture); 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 ec6f0ffb8..20cca3a0b 100644 --- a/app/src/main/java/app/fedilab/android/activities/InstanceHealthActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/InstanceHealthActivity.java @@ -113,7 +113,7 @@ public class InstanceHealthActivity extends BaseActivity { private void checkInstance() { - if (instance == null){ + if (instance == null) { LinearLayout main_container = findViewById(R.id.main_container); TextView no_instance = findViewById(R.id.no_instance); instance_container.setVisibility(View.VISIBLE); diff --git a/app/src/main/java/app/fedilab/android/activities/InstanceProfileActivity.java b/app/src/main/java/app/fedilab/android/activities/InstanceProfileActivity.java index 7141ab9e0..63fc11bf8 100644 --- a/app/src/main/java/app/fedilab/android/activities/InstanceProfileActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/InstanceProfileActivity.java @@ -32,6 +32,7 @@ import android.widget.TextView; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; + import com.bumptech.glide.Glide; import java.util.ArrayList; @@ -79,8 +80,8 @@ public class InstanceProfileActivity extends BaseActivity { if (getSupportActionBar() != null) getSupportActionBar().hide(); if (b != null) - instance = b.getString("instance",null); - if( instance == null){ + instance = b.getString("instance", null); + if (instance == null) { finish(); } Button close = findViewById(R.id.close); @@ -117,7 +118,7 @@ public class InstanceProfileActivity extends BaseActivity { try { InstanceNodeInfo instanceNodeInfo = new API(InstanceProfileActivity.this).instanceInfo(instance.trim()); runOnUiThread(() -> { - if( instanceNodeInfo == null){ + if (instanceNodeInfo == null) { finish(); return; } @@ -130,7 +131,7 @@ public class InstanceProfileActivity extends BaseActivity { SpannableString descriptionSpan; - if( instanceNodeInfo.getNodeDescription() != null) { + if (instanceNodeInfo.getNodeDescription() != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) descriptionSpan = new SpannableString(Html.fromHtml(instanceNodeInfo.getNodeDescription(), FROM_HTML_MODE_LEGACY)); else @@ -143,7 +144,7 @@ public class InstanceProfileActivity extends BaseActivity { String softwareStr = instanceNodeInfo.getName() + " - "; software.setText(softwareStr); version.setText(instanceNodeInfo.getVersion()); - if( instanceNodeInfo.getStaffAccount() != null){ + if (instanceNodeInfo.getStaffAccount() != null) { List accounts = new ArrayList<>(); accounts.add(instanceNodeInfo.getStaffAccount()); final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); diff --git a/app/src/main/java/app/fedilab/android/activities/LiveNotificationSettingsAccountsActivity.java b/app/src/main/java/app/fedilab/android/activities/LiveNotificationSettingsAccountsActivity.java index 37b912e59..d845c71b5 100644 --- a/app/src/main/java/app/fedilab/android/activities/LiveNotificationSettingsAccountsActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/LiveNotificationSettingsAccountsActivity.java @@ -63,7 +63,7 @@ public class LiveNotificationSettingsAccountsActivity extends BaseActivity { ArrayList accounts = new ArrayList<>(); SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); List accountStreams = new AccountDAO(getApplicationContext(), db).getAllAccountCrossAction(); - if( accountStreams == null || accountStreams.size() == 0 ){ + if (accountStreams == null || accountStreams.size() == 0) { finish(); return; } 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 cd9a878d2..6c8f48806 100644 --- a/app/src/main/java/app/fedilab/android/activities/LoginActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/LoginActivity.java @@ -304,16 +304,16 @@ public class LoginActivity extends BaseActivity { final String action = "/instances/search"; final HashMap parameters = new HashMap<>(); String query = s.toString().trim(); - if (query.startsWith("http://")){ - query =query.replace("http://", ""); + if (query.startsWith("http://")) { + query = query.replace("http://", ""); } - if (query.startsWith("https://")){ - query =query.replace("https://", ""); + if (query.startsWith("https://")) { + query = query.replace("https://", ""); } parameters.put("q", query); parameters.put("count", String.valueOf(1000)); parameters.put("name", String.valueOf(true)); - if( thread != null && thread.isAlive()){ + if (thread != null && thread.isAlive()) { thread.interrupt(); thread = null; } @@ -322,7 +322,7 @@ public class LoginActivity extends BaseActivity { thread = new Thread(() -> { try { final String response = new HttpsConnection(LoginActivity.this, instance).get("https://instances.social/api/1.0" + action, 30, parameters, Helper.THEKINRAR_SECRET_TOKEN); - if( response == null) { + if (response == null) { return; } runOnUiThread(() -> { @@ -436,11 +436,11 @@ public class LoginActivity extends BaseActivity { private void retrievesClientId() { if (socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.GNU && socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { String instanceFromField = login_instance.getText().toString().trim(); - if (instanceFromField.startsWith("http://")){ - instanceFromField =instanceFromField.replace("http://", ""); + if (instanceFromField.startsWith("http://")) { + instanceFromField = instanceFromField.replace("http://", ""); } - if (instanceFromField.startsWith("https://")){ - instanceFromField =instanceFromField.replace("https://", ""); + if (instanceFromField.startsWith("https://")) { + instanceFromField = instanceFromField.replace("https://", ""); } String host = instanceFromField; try { @@ -563,7 +563,8 @@ public class LoginActivity extends BaseActivity { } try { instance = URLEncoder.encode(host, "utf-8"); - } catch (UnsupportedEncodingException ignored) {} + } catch (UnsupportedEncodingException ignored) { + } String username = login_uid.getText().toString().trim().toLowerCase(); String password = login_passwd.getText().toString(); oauthUrl = "/api/account/verify_credentials.json"; @@ -778,15 +779,18 @@ public class LoginActivity extends BaseActivity { bubbleShowCase.finishSequence(); } } + @Override public void onCloseActionImageClick(@NotNull BubbleShowCase bubbleShowCase) { if (loop) { bubbleShowCase.finishSequence(); } } + @Override public void onBubbleClick(@NotNull BubbleShowCase bubbleShowCase) { } + @Override public void onBackgroundDimClick(@NotNull BubbleShowCase bubbleShowCase) { } 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 5a34758ce..a1fbafe69 100644 --- a/app/src/main/java/app/fedilab/android/activities/OwnerNotificationActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/OwnerNotificationActivity.java @@ -18,7 +18,6 @@ package app.fedilab.android.activities; import android.app.DatePickerDialog; import android.content.BroadcastReceiver; import android.content.Context; -import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; @@ -446,7 +445,7 @@ 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&& apiResponse.getError().getStatusCode() != 501) { + if (apiResponse.getError() != null && apiResponse.getError().getStatusCode() != 404 && apiResponse.getError().getStatusCode() != 501) { Toasty.error(getApplicationContext(), apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); swipeRefreshLayout.setRefreshing(false); swiped = false; 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 804b7e1f8..ce0fbd615 100644 --- a/app/src/main/java/app/fedilab/android/activities/PeertubeActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/PeertubeActivity.java @@ -295,7 +295,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube } }); String user_agent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, null); - if( user_agent != null) { + if (user_agent != null) { webview_video.getSettings().setUserAgentString(user_agent); } webview_video.getSettings().setAllowFileAccess(true); 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 52bf151cc..751aa2bc2 100644 --- a/app/src/main/java/app/fedilab/android/activities/PeertubeUploadActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/PeertubeUploadActivity.java @@ -45,7 +45,6 @@ import androidx.appcompat.app.ActionBar; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; - import net.gotev.uploadservice.MultipartUploadRequest; import net.gotev.uploadservice.ServerResponse; import net.gotev.uploadservice.UploadInfo; @@ -174,7 +173,7 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe } else if (uriString.startsWith("file://")) { filename = myFile.getName(); } - if( filename == null){ + if (filename == null) { filename = new Date().toString(); } set_upload_file_name.setVisibility(View.VISIBLE); 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 f6aa56862..97cdaed93 100644 --- a/app/src/main/java/app/fedilab/android/activities/PhotoEditorActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/PhotoEditorActivity.java @@ -351,7 +351,7 @@ public class PhotoEditorActivity extends BaseActivity implements OnPhotoEditorLi switch (requestCode) { case CAMERA_REQUEST: - if( data != null && data.getExtras() != null) { + if (data != null && data.getExtras() != null) { mPhotoEditor.clearAllViews(); Bitmap photo = (Bitmap) data.getExtras().get("data"); mPhotoEditorView.getSource().setImageBitmap(photo); @@ -359,7 +359,7 @@ public class PhotoEditorActivity extends BaseActivity implements OnPhotoEditorLi } break; case PICK_REQUEST: - if( data != null && data.getData() != null) { + if (data != null && data.getData() != null) { try { mPhotoEditor.clearAllViews(); Uri uri = data.getData(); diff --git a/app/src/main/java/app/fedilab/android/activities/PixelfedComposeActivity.java b/app/src/main/java/app/fedilab/android/activities/PixelfedComposeActivity.java index 212f0d633..862795906 100644 --- a/app/src/main/java/app/fedilab/android/activities/PixelfedComposeActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/PixelfedComposeActivity.java @@ -496,7 +496,7 @@ public class PixelfedComposeActivity extends BaseActivity implements UploadStatu String token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); int maxUploadRetryTimes = sharedpreferences.getInt(Helper.MAX_UPLOAD_IMG_RETRY_TIMES, 3); String url = scheme + "://" + Helper.getLiveInstance(activity) + "/api/v1/media"; - if( pixelfedStory) { + if (pixelfedStory) { url = scheme + "://" + Helper.getLiveInstance(activity) + "/api/stories/v1/add"; } UploadNotificationConfig uploadConfig = new UploadNotificationConfig(); @@ -508,7 +508,7 @@ public class PixelfedComposeActivity extends BaseActivity implements UploadStatu request.addHeader("Authorization", "Bearer " + token); request.setNotificationConfig(uploadConfig); request.addFileToUpload(uri.toString().replace("file://", ""), "file"); - if( !pixelfedStory) { + if (!pixelfedStory) { request.addParameter("filename", fileName).setMaxRetries(maxUploadRetryTimes); } request.startUpload(); @@ -654,7 +654,7 @@ public class PixelfedComposeActivity extends BaseActivity implements UploadStatu toot_sensitive = findViewById(R.id.toot_sensitive); LinearLayout drawer_layout = findViewById(R.id.drawer_layout); ImageButton toot_emoji = findViewById(R.id.toot_emoji); - LinearLayout bottom_bar_tooting = findViewById(R.id.bottom_bar_tooting); + LinearLayout bottom_bar_tooting = findViewById(R.id.bottom_bar_tooting); isScheduled = false; if (sharedpreferences.getBoolean(Helper.SET_DISPLAY_EMOJI, true)) { final EmojiPopup emojiPopup = EmojiPopup.Builder.fromRootView(drawer_layout).build(toot_content); @@ -670,11 +670,11 @@ public class PixelfedComposeActivity extends BaseActivity implements UploadStatu } TextView indication_story = findViewById(R.id.indication_story); pixelfed_story.setOnCheckedChangeListener((buttonView, isChecked) -> { - if( isChecked){ + if (isChecked) { composer_container.setVisibility(View.GONE); indication_story.setVisibility(View.VISIBLE); bottom_bar_tooting.setVisibility(View.GONE); - }else{ + } else { composer_container.setVisibility(View.VISIBLE); indication_story.setVisibility(View.GONE); bottom_bar_tooting.setVisibility(View.VISIBLE); @@ -891,7 +891,7 @@ public class PixelfedComposeActivity extends BaseActivity implements UploadStatu } private void addNewMedia(JSONObject response, ArrayList successfullyUploadedFiles) { - if( !pixelfed_story.isChecked()) { + if (!pixelfed_story.isChecked()) { Attachment attachment; attachment = API.parseAttachmentResponse(response); boolean alreadyAdded = false; @@ -1371,9 +1371,9 @@ public class PixelfedComposeActivity extends BaseActivity implements UploadStatu } SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if( theme == THEME_LIGHT){ + if (theme == THEME_LIGHT) { //Hack for colors in compose menu - for(int i = 0 ; i < menu.size(); i++){ + for (int i = 0; i < menu.size(); i++) { MenuItem item = menu.getItem(i); SpannableString s = new SpannableString(item.getTitle()); s.setSpan(new ForegroundColorSpan(Color.BLACK), 0, s.length(), 0); 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 f225f7c75..1aea4ff29 100644 --- a/app/src/main/java/app/fedilab/android/activities/PlaylistsActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/PlaylistsActivity.java @@ -216,7 +216,7 @@ 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 -")&&!apiResponse.getError().getError().startsWith("501 -")) + if (!apiResponse.getError().getError().startsWith("404 -") && !apiResponse.getError().getError().startsWith("501 -")) Toasty.error(getApplicationContext(), apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); swipeRefreshLayout.setRefreshing(false); swiped = false; 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 f65cddbfb..c1e51c002 100644 --- a/app/src/main/java/app/fedilab/android/activities/ReorderTimelinesActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/ReorderTimelinesActivity.java @@ -161,9 +161,9 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra //Manage download of attachments RadioGroup radioGroup = dialogView.findViewById(R.id.set_attachment_group); radioGroup.setOnCheckedChangeListener((group, checkedId) -> { - if( checkedId == R.id.twitter_accounts){ + if (checkedId == R.id.twitter_accounts) { instance_list.setHint(R.string.list_of_twitter_accounts); - }else { + } else { instance_list.setHint(R.string.instance); } }); @@ -172,7 +172,7 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra @Override 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().replace("@",""); + String instanceName = instance_list.getText().toString().trim().replace("@", ""); new Thread(new Runnable() { @Override public void run() { @@ -201,7 +201,7 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra new InstancesDAO(ReorderTimelinesActivity.this, db).insertInstance(instanceName, "MISSKEY"); } else if (radioGroup.getCheckedRadioButtonId() == R.id.gnu_instance) { new InstancesDAO(ReorderTimelinesActivity.this, db).insertInstance(instanceName, "GNU"); - }else if (radioGroup.getCheckedRadioButtonId() == R.id.twitter_accounts) { + } else if (radioGroup.getCheckedRadioButtonId() == R.id.twitter_accounts) { new InstancesDAO(ReorderTimelinesActivity.this, db).insertInstance(instanceName, "NITTER"); } if (timelines != null && adapter != null) { @@ -263,7 +263,7 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra @Override public void afterTextChanged(Editable s) { - if (radioGroup.getCheckedRadioButtonId() != R.id.twitter_accounts){ + if (radioGroup.getCheckedRadioButtonId() != R.id.twitter_accounts) { 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()) { @@ -336,7 +336,7 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra else isLoadingInstance = false; } - }else { + } else { alertDialog.getButton( AlertDialog.BUTTON_POSITIVE).setEnabled(true); } 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 c6fb9ecd9..639be588d 100644 --- a/app/src/main/java/app/fedilab/android/activities/SearchResultActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/SearchResultActivity.java @@ -94,7 +94,7 @@ public class SearchResultActivity extends BaseActivity implements OnRetrieveSear } else { Toasty.error(getApplicationContext(), getString(R.string.toast_error_search), Toast.LENGTH_LONG).show(); } - if( search.compareTo("fedilab_trend") == 0 ) { + if (search.compareTo("fedilab_trend") == 0) { forTrends = true; } if (getSupportActionBar() != null) @@ -115,15 +115,15 @@ public class SearchResultActivity extends BaseActivity implements OnRetrieveSear finish(); } }); - if( !forTrends) { + if (!forTrends) { toolbar_title.setText(search); - }else{ + } else { toolbar_title.setText(getString(R.string.trending_now)); } } - if( !forTrends) { + if (!forTrends) { setTitle(search); - }else{ + } else { setTitle(R.string.trending_now); } loader.setVisibility(View.VISIBLE); @@ -173,7 +173,7 @@ public class SearchResultActivity extends BaseActivity implements OnRetrieveSear lv_search.setAdapter(searchListAdapter); searchListAdapter.notifyDataSetChanged(); } else { - if (apiResponse.getTrends() == null || apiResponse.getTrends().size() == 0 ) { + if (apiResponse.getTrends() == null || apiResponse.getTrends().size() == 0) { RelativeLayout no_result = findViewById(R.id.no_result); no_result.setVisibility(View.VISIBLE); return; 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 6717e787b..ecccda936 100644 --- a/app/src/main/java/app/fedilab/android/activities/SearchResultTabActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/SearchResultTabActivity.java @@ -190,7 +190,7 @@ public class SearchResultTabActivity extends BaseActivity { private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter { ScreenSlidePagerAdapter(FragmentManager fm) { - super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT); + super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT); } @NotNull @@ -230,6 +230,7 @@ public class SearchResultTabActivity extends BaseActivity { public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { } + @Override public int getCount() { return 4; 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 456b84306..c1e0f276f 100644 --- a/app/src/main/java/app/fedilab/android/activities/SettingsActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/SettingsActivity.java @@ -186,7 +186,7 @@ public class SettingsActivity extends BaseActivity { private static class SettingsPagerAdapter extends FragmentStatePagerAdapter { SettingsPagerAdapter(FragmentManager fm) { - super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT); + super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT); } @NotNull 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 24637fe22..c34d8a979 100644 --- a/app/src/main/java/app/fedilab/android/activities/ShowAccountActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/ShowAccountActivity.java @@ -303,7 +303,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt header_edit_profile.bringToFront(); } //TODO: add other software that supports identity proofs - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { new RetrieveIdentityProofAsyncTask(ShowAccountActivity.this, account.getId(), ShowAccountActivity.this).execute(); } String urlHeader = account.getHeader(); @@ -891,14 +891,14 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt return; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - int[][] states = new int[][] { - new int[] { android.R.attr.state_enabled}, // enabled - new int[] {-android.R.attr.state_enabled}, // disabled - new int[] {-android.R.attr.state_checked}, // unchecked - new int[] { android.R.attr.state_pressed} // pressed + int[][] states = new int[][]{ + new int[]{android.R.attr.state_enabled}, // enabled + new int[]{-android.R.attr.state_enabled}, // disabled + new int[]{-android.R.attr.state_checked}, // unchecked + new int[]{android.R.attr.state_pressed} // pressed }; - int[] colors = new int[] { + int[] colors = new int[]{ ContextCompat.getColor(ShowAccountActivity.this, R.color.mastodonC4), ContextCompat.getColor(ShowAccountActivity.this, R.color.mastodonC4___), ContextCompat.getColor(ShowAccountActivity.this, R.color.mastodonC4), @@ -918,7 +918,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt account_follow.setEnabled(false); account_follow.setContentDescription(getString(R.string.action_disabled)); doAction = action.NOTHING; - }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); @@ -1417,7 +1417,7 @@ 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 -")&&!apiResponse.getError().getError().startsWith("501 -")) + if (!apiResponse.getError().getError().startsWith("404 -") && !apiResponse.getError().getError().startsWith("501 -")) Toasty.error(getApplicationContext(), apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); return; } @@ -1436,11 +1436,11 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt @Override public void onIdentityProof(APIResponse apiResponse) { - if( apiResponse == null) { + if (apiResponse == null) { return; } List identityProofs = apiResponse.getIdentityProofs(); - if( identityProofs != null && identityProofs.size() > 0 ){ + if (identityProofs != null && identityProofs.size() > 0) { ImageView identity_proofs_indicator = findViewById(R.id.identity_proofs_indicator); identity_proofs_indicator.setVisibility(View.VISIBLE); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); @@ -1457,8 +1457,8 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt AlertDialog.Builder builder = new AlertDialog.Builder(ShowAccountActivity.this, style); LayoutInflater inflater = getLayoutInflater(); - View identityProofsView = inflater.inflate(R.layout.popup_identity_proof, new LinearLayout(ShowAccountActivity.this), false); - RecyclerView identityProofsRecycler = identityProofsView.findViewById(R.id.identity_proofs_list); + View identityProofsView = inflater.inflate(R.layout.popup_identity_proof, new LinearLayout(ShowAccountActivity.this), false); + RecyclerView identityProofsRecycler = identityProofsView.findViewById(R.id.identity_proofs_list); LinearLayoutManager mLayoutManager = new LinearLayoutManager(ShowAccountActivity.this); identityProofsRecycler.setLayoutManager(mLayoutManager); IdentityProofsAdapter identityProofsAdapter = new IdentityProofsAdapter(identityProofs); @@ -1487,7 +1487,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter { ScreenSlidePagerAdapter(FragmentManager fm) { - super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT); + super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT); } @NotNull 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 913ca1952..df5f27bbc 100644 --- a/app/src/main/java/app/fedilab/android/activities/ShowConversationActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/ShowConversationActivity.java @@ -29,7 +29,6 @@ import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; -import androidx.appcompat.app.ActionBar; import androidx.appcompat.widget.Toolbar; import androidx.core.content.ContextCompat; import androidx.localbroadcastmanager.content.LocalBroadcastManager; diff --git a/app/src/main/java/app/fedilab/android/activities/SlideMediaActivity.java b/app/src/main/java/app/fedilab/android/activities/SlideMediaActivity.java index da889466c..01743401f 100644 --- a/app/src/main/java/app/fedilab/android/activities/SlideMediaActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/SlideMediaActivity.java @@ -103,7 +103,7 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf startActivity(shareIntent); } catch (Exception ignored) { } - }else{ + } else { Toasty.success(context, context.getString(R.string.save_over), Toasty.LENGTH_LONG).show(); } } @@ -150,7 +150,7 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf media_save.setOnClickListener(view12 -> { int position = mPager.getCurrentItem(); Attachment attachment = attachments.get(position); - if( attachment.getType().compareTo("image") == 0 ){ + if (attachment.getType().compareTo("image") == 0) { if (Build.VERSION.SDK_INT >= 23) { if (ContextCompat.checkSelfPermission(SlideMediaActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(SlideMediaActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(SlideMediaActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, Helper.EXTERNAL_STORAGE_REQUEST_CODE); @@ -160,7 +160,7 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf } else { Helper.manageMove(SlideMediaActivity.this, attachment.getUrl(), false); } - }else { + } else { if (Build.VERSION.SDK_INT >= 23) { if (ContextCompat.checkSelfPermission(SlideMediaActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(SlideMediaActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(SlideMediaActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, Helper.EXTERNAL_STORAGE_REQUEST_CODE); @@ -178,9 +178,9 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf media_share.setOnClickListener(view1 -> { int position = mPager.getCurrentItem(); Attachment attachment = attachments.get(position); - if( attachment.getType().compareTo("image") == 0 ){ + if (attachment.getType().compareTo("image") == 0) { Helper.manageMove(SlideMediaActivity.this, attachment.getUrl(), true); - }else if (attachment.getType().toLowerCase().equals("video") || attachment.getType().toLowerCase().equals("audio") || attachment.getType().toLowerCase().equals("gifv")) { + } else if (attachment.getType().toLowerCase().equals("video") || attachment.getType().toLowerCase().equals("audio") || attachment.getType().toLowerCase().equals("gifv")) { downloadID = Helper.manageDownloadsNoPopup(SlideMediaActivity.this, attachment.getUrl()); } else { if (Build.VERSION.SDK_INT >= 23) { @@ -409,7 +409,7 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter { ScreenSlidePagerAdapter(FragmentManager fm) { - super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT); + super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT); } @NotNull 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 f8aabcce0..5462fe947 100644 --- a/app/src/main/java/app/fedilab/android/activities/TootActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/TootActivity.java @@ -16,6 +16,7 @@ package app.fedilab.android.activities; import android.Manifest; +import android.annotation.SuppressLint; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ClipData; @@ -52,14 +53,11 @@ import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; -import android.view.ViewTreeObserver; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; -import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; -import android.widget.CompoundButton; import android.widget.DatePicker; import android.widget.EditText; import android.widget.GridView; @@ -98,7 +96,6 @@ import com.github.irshulx.Editor; import com.github.irshulx.EditorListener; import com.github.irshulx.models.EditorTextStyle; import com.github.stom79.localepicker.CountryPicker; -import com.github.stom79.localepicker.CountryPickerListener; import com.github.stom79.mytransl.MyTransL; import com.github.stom79.mytransl.client.HttpsConnectionException; import com.github.stom79.mytransl.translate.Translate; @@ -302,7 +299,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, public void onReceive(Context context, Intent intent) { JSONObject response = null; - ArrayList successfullyUploadedFiles = null; + ArrayList successfullyUploadedFiles; try { response = new JSONObject(Objects.requireNonNull(intent.getStringExtra("response"))); } catch (JSONException e) { @@ -372,22 +369,18 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, Handler mainHandler = new Handler(Looper.getMainLooper()); - Runnable myRunnable = new Runnable() { - @Override - public void run() { - newContent[0] = newContent[0] + hugs.toString(); - toot_content.setText(newContent[0]); - toot_content.setSelection(toot_content.getText().length()); - // toot_content.addTextChangedListener(finalTextw); - autocomplete = false; - toot_space_left.setText(String.valueOf(countLength(social, toot_content, toot_cw_content))); - } + Runnable myRunnable = () -> { + newContent[0] = newContent[0] + hugs.toString(); + toot_content.setText(newContent[0]); + toot_content.setSelection(toot_content.getText().length()); + autocomplete = false; + toot_space_left.setText(String.valueOf(countLength(social, toot_content, toot_cw_content))); }; mainHandler.post(myRunnable); } 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]+)?"; + 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()) { @@ -422,14 +415,11 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, Handler mainHandler = new Handler(Looper.getMainLooper()); - Runnable myRunnable = new Runnable() { - @Override - public void run() { - toot_content.setText(newContent[0]); - toot_content.setSelection(toot_content.getText().length()); - autocomplete = false; - toot_space_left.setText(String.valueOf(countLength(social, toot_content, toot_cw_content))); - } + Runnable myRunnable = () -> { + toot_content.setText(newContent[0]); + toot_content.setSelection(toot_content.getText().length()); + autocomplete = false; + toot_space_left.setText(String.valueOf(countLength(social, toot_content, toot_cw_content))); }; mainHandler.post(myRunnable); } @@ -659,8 +649,6 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, String contentView = ""; //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); - if (tootReply.getAccount() != null && tootReply.getAccount().getAcct() != null && !tootReply.getAccount().getId().equals(userIdReply)) { contentView = String.format("@%s", tootReply.getAccount().getAcct()); mentionedAccountsAdded.add(tootReply.getAccount().getAcct()); @@ -692,7 +680,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, String cwContent = toot_cw_content.getText().toString(); String contentCount = content; if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { - contentCount = contentCount.replaceAll("(?i)(^|[^/\\w])@(([a-z0-9_]+)@[a-z0-9\\.\\-]+[a-z0-9]+)", "$1@$3"); + contentCount = contentCount.replaceAll("(?i)(^|[^/\\w])@(([a-z0-9_]+)@[a-z0-9.-]+[a-z0-9]+)", "$1@$3"); Matcher matcherALink = Patterns.WEB_URL.matcher(contentCount); while (matcherALink.find()) { final String url = matcherALink.group(1); @@ -829,11 +817,8 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, if (sharedpreferences.getBoolean(Helper.SET_DISPLAY_EMOJI, true)) { final EmojiPopup emojiPopup = EmojiPopup.Builder.fromRootView(drawer_layout).build(toot_content); - toot_emoji.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - emojiPopup.toggle(); // Toggles visibility of the Popup. - } + toot_emoji.setOnClickListener(v -> { + emojiPopup.toggle(); // Toggles visibility of the Popup. }); } else { toot_emoji.setVisibility(View.GONE); @@ -939,21 +924,18 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, }); } - drawer_layout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { - @Override - public void onGlobalLayout() { - int heightDiff = drawer_layout.getRootView().getHeight() - drawer_layout.getHeight(); - if (heightDiff > Helper.convertDpToPixel(200, getApplicationContext())) { - ViewGroup.LayoutParams params = toot_picture_container.getLayoutParams(); - params.height = (int) Helper.convertDpToPixel(50, getApplicationContext()); - params.width = (int) Helper.convertDpToPixel(50, getApplicationContext()); - toot_picture_container.setLayoutParams(params); - } else { - ViewGroup.LayoutParams params = toot_picture_container.getLayoutParams(); - params.height = (int) Helper.convertDpToPixel(100, getApplicationContext()); - params.width = (int) Helper.convertDpToPixel(100, getApplicationContext()); - toot_picture_container.setLayoutParams(params); - } + drawer_layout.getViewTreeObserver().addOnGlobalLayoutListener(() -> { + int heightDiff = drawer_layout.getRootView().getHeight() - drawer_layout.getHeight(); + if (heightDiff > Helper.convertDpToPixel(200, getApplicationContext())) { + ViewGroup.LayoutParams params = toot_picture_container.getLayoutParams(); + params.height = (int) Helper.convertDpToPixel(50, getApplicationContext()); + params.width = (int) Helper.convertDpToPixel(50, getApplicationContext()); + toot_picture_container.setLayoutParams(params); + } else { + ViewGroup.LayoutParams params = toot_picture_container.getLayoutParams(); + params.height = (int) Helper.convertDpToPixel(100, getApplicationContext()); + params.width = (int) Helper.convertDpToPixel(100, getApplicationContext()); + toot_picture_container.setLayoutParams(params); } }); @@ -974,7 +956,6 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } tootMention = b.getString("tootMention", null); urlMention = b.getString("urlMention", null); - String fileMention = b.getString("fileMention", null); sharedContent = b.getString("sharedContent", null); sharedContentIni = b.getString("sharedContent", null); sharedSubject = b.getString("sharedSubject", null); @@ -1154,109 +1135,85 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } } - toot_sensitive.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - isSensitive = isChecked; - } - }); + toot_sensitive.setOnCheckedChangeListener((buttonView, isChecked) -> isSensitive = isChecked); toot_space_left.setText(String.valueOf(countLength(social, toot_content, toot_cw_content))); - toot_cw.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (toot_cw_content.getVisibility() == View.GONE) { - toot_cw_content.setVisibility(View.VISIBLE); - toot_cw_content.requestFocus(); - } else { - toot_cw_content.setVisibility(View.GONE); - toot_cw_content.setText(""); - toot_content.requestFocus(); - } + toot_cw.setOnClickListener(v -> { + if (toot_cw_content.getVisibility() == View.GONE) { + toot_cw_content.setVisibility(View.VISIBLE); + toot_cw_content.requestFocus(); + } else { + toot_cw_content.setVisibility(View.GONE); + toot_cw_content.setText(""); + toot_content.requestFocus(); } }); - toot_visibility.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - tootVisibilityDialog(); - } - }); + toot_visibility.setOnClickListener(v -> tootVisibilityDialog()); - toot_it.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (!displayWYSIWYG()) { - sendToot(null, null); - } else { - sendToot(null, "text/html"); - } + toot_it.setOnClickListener(v -> { + if (!displayWYSIWYG()) { + sendToot(null, null); + } else { + sendToot(null, "text/html"); } }); if (social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA && !displayWYSIWYG()) - toot_it.setOnLongClickListener(new View.OnLongClickListener() { - @Override - public boolean onLongClick(View v) { - PopupMenu popup = new PopupMenu(TootActivity.this, toot_it); - popup.getMenuInflater() - .inflate(R.menu.main_content_type, popup.getMenu()); - popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { - public boolean onMenuItemClick(MenuItem item) { - switch (item.getItemId()) { - case R.id.action_plain_text: - contentType = "text/plain"; - break; - case R.id.action_html: - contentType = "text/html"; - break; - case R.id.action_markdown: - contentType = "text/markdown"; - break; - case R.id.action_bbcode: - contentType = "text/bbcode"; - break; - } - popup.dismiss(); - sendToot(null, contentType); - return false; - } - }); - popup.show(); + toot_it.setOnLongClickListener(v -> { + PopupMenu popup = new PopupMenu(TootActivity.this, toot_it); + popup.getMenuInflater() + .inflate(R.menu.main_content_type, popup.getMenu()); + popup.setOnMenuItemClickListener(item -> { + switch (item.getItemId()) { + case R.id.action_plain_text: + contentType = "text/plain"; + break; + case R.id.action_html: + contentType = "text/html"; + break; + case R.id.action_markdown: + contentType = "text/markdown"; + break; + case R.id.action_bbcode: + contentType = "text/bbcode"; + break; + } + popup.dismiss(); + sendToot(null, contentType); return false; - } + }); + popup.show(); + return false; }); - toot_picture.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - - if (ContextCompat.checkSelfPermission(TootActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != - PackageManager.PERMISSION_GRANTED) { - ActivityCompat.requestPermissions(TootActivity.this, - new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, - MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE); - return; - } - Intent intent; - intent = new Intent(Intent.ACTION_GET_CONTENT); - intent.addCategory(Intent.CATEGORY_OPENABLE); - 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"}; - intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes); - startActivityForResult(intent, PICK_IMAGE); - } else { - intent.setType("image/* video/* audio/mpeg audio/opus audio/flac audio/wav audio/ogg"); - intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); - Intent pickIntent = new Intent(Intent.ACTION_PICK, 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}); - startActivityForResult(chooserIntent, PICK_IMAGE); - } + toot_picture.setOnClickListener(v -> { + if (ContextCompat.checkSelfPermission(TootActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != + PackageManager.PERMISSION_GRANTED) { + ActivityCompat.requestPermissions(TootActivity.this, + new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, + MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE); + return; } + Intent intent; + intent = new Intent(Intent.ACTION_GET_CONTENT); + intent.addCategory(Intent.CATEGORY_OPENABLE); + 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"}; + intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes); + startActivityForResult(intent, PICK_IMAGE); + } else { + intent.setType("image/* video/* audio/mpeg audio/opus audio/flac audio/wav audio/ogg"); + intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); + Intent pickIntent = new Intent(Intent.ACTION_PICK, 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}); + startActivityForResult(chooserIntent, PICK_IMAGE); + } + }); @@ -1287,12 +1244,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, restoreToot(restored); } - poll_action.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - displayPollPopup(); - } - }); + poll_action.setOnClickListener(v -> displayPollPopup()); toot_space_left.setText(String.valueOf(countLength(social, toot_content, toot_cw_content))); @@ -1312,7 +1264,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, private void addNewMedia(JSONObject response, ArrayList successfullyUploadedFiles) { Attachment attachment; //response = new JSONObject(serverResponse.getBodyAsString()); - if( response == null ){ + if (response == null) { Toasty.error(TootActivity.this, getString(R.string.toast_error), Toasty.LENGTH_SHORT).show(); return; } @@ -1336,6 +1288,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } File audioFile = new File(getCacheDir() + "/fedilab_recorded_audio.wav"); + //noinspection ResultOfMethodCallIgnored audioFile.delete(); if (!alreadyAdded) { toot_picture_container.setVisibility(View.VISIBLE); @@ -1371,7 +1324,6 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } else { String finalUrl = url; - String uuid = attachment.getId(); Glide.with(imageView.getContext()) .asBitmap() .load(url) @@ -1415,24 +1367,16 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } imageView.setTag(attachment.getId()); toot_picture_container.addView(imageView, attachments.size(), imParams); - imageView.setOnLongClickListener(new View.OnLongClickListener() { - @Override - public boolean onLongClick(View view) { - showRemove(imageView.getId()); - return false; - } + imageView.setOnLongClickListener(view -> { + showRemove(imageView.getId()); + return false; }); String instanceVersion = sharedpreferences.getString(Helper.INSTANCE_VERSION + userId + instance, null); if (instanceVersion != null) { Version currentVersion = new Version(instanceVersion); Version minVersion = new Version("2.0"); - if (currentVersion.compareTo(minVersion) == 1 || currentVersion.equals(minVersion)) { - imageView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - showAddDescription(attachment); - } - }); + if (currentVersion.compareTo(minVersion) > 0 || currentVersion.equals(minVersion)) { + imageView.setOnClickListener(view -> showAddDescription(attachment)); } } attachments.add(attachment); @@ -1692,6 +1636,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } + @SuppressLint("ClickableViewAccessibility") @Override public boolean onOptionsItemSelected(@NotNull MenuItem item) { final SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); @@ -1724,16 +1669,10 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, input.setText(Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY)); else input.setText(Html.fromHtml(content)); - alert.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int whichButton) { - dialog.dismiss(); - } - }); - 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); - dialog.dismiss(); - } + alert.setPositiveButton(R.string.close, (dialog, whichButton) -> dialog.dismiss()); + alert.setNegativeButton(R.string.accounts, (dialog, whichButton) -> { + new RetrieveAccountsForReplyAsyncTask(getApplicationContext(), tootReply.getReblog() != null ? tootReply.getReblog() : tootReply, TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + dialog.dismiss(); }); alert.show(); return true; @@ -1759,145 +1698,130 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, return true; } } - picker.setListener(new CountryPickerListener() { - @Override - public void onSelectCountry(String name, String locale, int flagDrawableResID) { - picker.dismiss(); - AlertDialog.Builder transAlert = new AlertDialog.Builder(TootActivity.this, style); - transAlert.setTitle(R.string.translate_toot); + picker.setListener((name, locale, flagDrawableResID) -> { + picker.dismiss(); + 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); - 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.apply(); - TextView yandex_translate = popup_trans.findViewById(R.id.yandex_translate); - yandex_translate.setOnClickListener(new View.OnClickListener() { + 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.apply(); + TextView yandex_translate = popup_trans.findViewById(R.id.yandex_translate); + yandex_translate.setOnClickListener(v -> { + Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://translate.yandex.com/")); + startActivity(browserIntent); + }); + MyTransL myTransL = MyTransL.getInstance(MyTransL.translatorEngine.YANDEX); + myTransL.setYandexAPIKey(Helper.YANDEX_KEY); + myTransL.setObfuscation(true); + myTransL.setTimeout(60); + 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 onClick(View v) { - Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://translate.yandex.com/")); - startActivity(browserIntent); - } - }); - MyTransL myTransL = MyTransL.getInstance(MyTransL.translatorEngine.YANDEX); - myTransL.setYandexAPIKey(Helper.YANDEX_KEY); - myTransL.setObfuscation(true); - myTransL.setTimeout(60); - 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) - return; - 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) - trans_progress_cw.setVisibility(View.GONE); - LinearLayout trans_container = popup_trans.findViewById(R.id.trans_container); - if (trans_container != null) { - TextView cw_trans = popup_trans.findViewById(R.id.cw_trans); - 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(); + public void onSuccess(Translate translate) { + try { + if (translate.getTranslatedContent() == null) + return; + 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) + trans_progress_cw.setVisibility(View.GONE); + LinearLayout trans_container = popup_trans.findViewById(R.id.trans_container); + if (trans_container != null) { + TextView cw_trans = popup_trans.findViewById(R.id.cw_trans); + if (cw_trans != null) { + cw_trans.setVisibility(View.VISIBLE); + cw_trans.setText(translate.getTranslatedContent()); } - 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); + } else { + Toasty.error(getApplicationContext(), getString(R.string.toast_error_translate), Toast.LENGTH_LONG).show(); } - } catch (IllegalArgumentException e) { - 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) + dialogTrans.getButton(DialogInterface.BUTTON_NEGATIVE).setEnabled(true); } - + } catch (IllegalArgumentException e) { + Toasty.error(getApplicationContext(), getString(R.string.toast_error_translate), Toast.LENGTH_LONG).show(); } - @Override - public void onFail(HttpsConnectionException e) { - 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) - 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) - return; - 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) - trans_progress_toot.setVisibility(View.GONE); - LinearLayout trans_container = popup_trans.findViewById(R.id.trans_container); - if (trans_container != null) { - TextView toot_trans = popup_trans.findViewById(R.id.toot_trans); - 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(); - } - 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(); - } - } - - @Override - public void onFail(HttpsConnectionException e) { - e.printStackTrace(); - } - }); - - transAlert.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int whichButton) { - dialog.dismiss(); } - }); - transAlert.setNegativeButton(R.string.validate, new DialogInterface.OnClickListener() { - 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) { - toot_content.setText(toot_trans.getText().toString()); - toot_content.setSelection(toot_content.getText().length()); - } - if (cw_trans != null) - toot_cw_content.setText(cw_trans.getText().toString()); - dialog.dismiss(); - } - }); - dialogTrans = transAlert.create(); - transAlert.show(); - dialogTrans.setOnShowListener(new DialogInterface.OnShowListener() { @Override - public void onShow(DialogInterface dialog) { - Button negativeButton = ((AlertDialog) dialog) - .getButton(AlertDialog.BUTTON_NEGATIVE); - if (negativeButton != null) - negativeButton.setEnabled(false); + public void onFail(HttpsConnectionException e) { + 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) + 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) + return; + 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) + trans_progress_toot.setVisibility(View.GONE); + LinearLayout trans_container = popup_trans.findViewById(R.id.trans_container); + if (trans_container != null) { + TextView toot_trans = popup_trans.findViewById(R.id.toot_trans); + 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(); + } + 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(); + } + } + + @Override + public void onFail(HttpsConnectionException e) { + e.printStackTrace(); + } + }); + + transAlert.setPositiveButton(R.string.close, (dialog, whichButton) -> dialog.dismiss()); + transAlert.setNegativeButton(R.string.validate, (dialog, 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) { + toot_content.setText(toot_trans.getText().toString()); + toot_content.setSelection(toot_content.getText().length()); + } + if (cw_trans != null) + toot_cw_content.setText(cw_trans.getText().toString()); + dialog.dismiss(); + }); + dialogTrans = transAlert.create(); + transAlert.show(); + + dialogTrans.setOnShowListener(dialog -> { + Button negativeButton = ((AlertDialog) dialog) + .getButton(AlertDialog.BUTTON_NEGATIVE); + if (negativeButton != null) + negativeButton.setEnabled(false); + }); + }); picker.show(getSupportFragmentManager(), "COUNTRY_PICKER"); return true; case R.id.action_emoji: - if( emojis != null){ + if (emojis != null) { emojis.clear(); emojis = null; } @@ -1906,22 +1830,15 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, int paddingPixel = 15; float density = getResources().getDisplayMetrics().density; int paddingDp = (int) (paddingPixel * density); - builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - } - }); + builder.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()); builder.setTitle(R.string.insert_emoji); if (emojis != null && emojis.size() > 0) { GridView gridView = new GridView(TootActivity.this); gridView.setAdapter(new CustomEmojiAdapter(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() + ": "); - alertDialogEmoji.dismiss(); - } + gridView.setOnItemClickListener((parent, view, position, id) -> { + toot_content.getText().insert(toot_content.getSelectionStart(), " :" + emojis.get(position).getShortcode() + ": "); + alertDialogEmoji.dismiss(); }); gridView.setPadding(paddingDp, paddingDp, paddingDp, paddingDp); builder.setView(gridView); @@ -1973,27 +1890,21 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } } }); - search_account.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - final int DRAWABLE_RIGHT = 2; - 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); - } + search_account.setOnTouchListener((v, event) -> { + final int DRAWABLE_RIGHT = 2; + 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); } - - return false; } + + return false; }); builderSingle.setView(dialogView); - builderSingle.setNegativeButton(R.string.validate, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - toot_content.setSelection(toot_content.getText().length()); - } + builderSingle.setNegativeButton(R.string.validate, (dialog, which) -> { + dialog.dismiss(); + toot_content.setSelection(toot_content.getText().length()); }); builderSingle.show(); @@ -2042,44 +1953,26 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, ids[i] = draft.getId(); i++; } - builderSingle.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - } - }); - builderSingle.setPositiveButton(R.string.delete_all, new DialogInterface.OnClickListener() { - @Override - public void onClick(final DialogInterface dialog, int which) { - AlertDialog.Builder builder = new AlertDialog.Builder(TootActivity.this, style); - builder.setTitle(R.string.delete_all); - builder.setIcon(android.R.drawable.ic_dialog_alert) - .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogConfirm, int which) { - new StatusStoredDAO(getApplicationContext(), db).removeAllDrafts(); - dialogConfirm.dismiss(); - dialog.dismiss(); - } - }) - .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogConfirm, int which) { - dialogConfirm.dismiss(); - } - }) - .show(); + builderSingle.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()); + builderSingle.setPositiveButton(R.string.delete_all, (dialog, which) -> { + AlertDialog.Builder builder1 = new AlertDialog.Builder(TootActivity.this, style); + builder1.setTitle(R.string.delete_all); + builder1.setIcon(android.R.drawable.ic_dialog_alert) + .setPositiveButton(R.string.yes, (dialogConfirm, which1) -> { + new StatusStoredDAO(getApplicationContext(), db).removeAllDrafts(); + dialogConfirm.dismiss(); + dialog.dismiss(); + }) + .setNegativeButton(R.string.no, (dialogConfirm, which12) -> dialogConfirm.dismiss()) + .show(); - } - }); - builderSingle.setAdapter(draftsListAdapter, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - int id = ids[which]; - restoreToot(id); - dialog.dismiss(); - } }); + builderSingle.setAdapter(draftsListAdapter, + (dialog, which) -> { + int id = ids[which]; + restoreToot(id); + dialog.dismiss(); + }); builderSingle.show(); } catch (Exception e) { Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show(); @@ -2093,7 +1986,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(TootActivity.this, style); inflater = this.getLayoutInflater(); - dialogView = inflater.inflate(R.layout.datetime_picker, null); + dialogView = inflater.inflate(R.layout.datetime_picker, new LinearLayout(getApplicationContext()), false); dialogBuilder.setView(dialogView); final AlertDialog alertDialog = dialogBuilder.create(); @@ -2107,86 +2000,64 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, final ImageButton date_time_set = dialogView.findViewById(R.id.date_time_set); //Buttons management - date_time_cancel.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - alertDialog.dismiss(); - } + date_time_cancel.setOnClickListener(v -> alertDialog.dismiss()); + date_time_next.setOnClickListener(v -> { + datePicker.setVisibility(View.GONE); + timePicker.setVisibility(View.VISIBLE); + date_time_previous.setVisibility(View.VISIBLE); + date_time_next.setVisibility(View.GONE); + date_time_set.setVisibility(View.VISIBLE); }); - date_time_next.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - datePicker.setVisibility(View.GONE); - timePicker.setVisibility(View.VISIBLE); - date_time_previous.setVisibility(View.VISIBLE); - date_time_next.setVisibility(View.GONE); - date_time_set.setVisibility(View.VISIBLE); - } + date_time_previous.setOnClickListener(v -> { + datePicker.setVisibility(View.VISIBLE); + timePicker.setVisibility(View.GONE); + date_time_previous.setVisibility(View.GONE); + date_time_next.setVisibility(View.VISIBLE); + date_time_set.setVisibility(View.GONE); }); - date_time_previous.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - datePicker.setVisibility(View.VISIBLE); - timePicker.setVisibility(View.GONE); - date_time_previous.setVisibility(View.GONE); - date_time_next.setVisibility(View.VISIBLE); - date_time_set.setVisibility(View.GONE); + date_time_set.setOnClickListener(v -> { + int hour, minute; + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + hour = timePicker.getHour(); + minute = timePicker.getMinute(); + } else { + hour = timePicker.getCurrentHour(); + minute = timePicker.getCurrentMinute(); } - }); - date_time_set.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - int hour, minute; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - hour = timePicker.getHour(); - minute = timePicker.getMinute(); - } else { - //noinspection deprecation - hour = timePicker.getCurrentHour(); - //noinspection deprecation - minute = timePicker.getCurrentMinute(); - } - Calendar calendar = new GregorianCalendar(datePicker.getYear(), - datePicker.getMonth(), - datePicker.getDayOfMonth(), - hour, - minute); - final long[] time = {calendar.getTimeInMillis()}; + Calendar calendar = new GregorianCalendar(datePicker.getYear(), + datePicker.getMonth(), + datePicker.getDayOfMonth(), + hour, + minute); + final long[] time = {calendar.getTimeInMillis()}; - if ((time[0] - new Date().getTime()) < 60000) { - Toasty.warning(getApplicationContext(), getString(R.string.toot_scheduled_date), Toast.LENGTH_LONG).show(); - } else { - SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); - String instanceVersion = sharedpreferences.getString(Helper.INSTANCE_VERSION + userId + instance, null); - Version currentVersion = new Version(instanceVersion); - Version minVersion = new Version("2.7"); - if (currentVersion.compareTo(minVersion) == 1 || currentVersion.equals(minVersion)) { - AlertDialog.Builder builderSingle = new AlertDialog.Builder(TootActivity.this, style); - builderSingle.setTitle(getString(R.string.choose_schedule)); - builderSingle.setNegativeButton(R.string.device_schedule, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - deviceSchedule(time[0]); - dialog.dismiss(); - } - }); - builderSingle.setPositiveButton(R.string.server_schedule, new DialogInterface.OnClickListener() { - @Override - public void onClick(final DialogInterface dialog, int which) { - int offset = TimeZone.getDefault().getRawOffset(); - calendar.add(Calendar.MILLISECOND, -offset); - final String date = Helper.dateToString(new Date(calendar.getTimeInMillis())); - serverSchedule(date); - } - }); - builderSingle.show(); - - } else { + if ((time[0] - new Date().getTime()) < 60000) { + Toasty.warning(getApplicationContext(), getString(R.string.toot_scheduled_date), Toast.LENGTH_LONG).show(); + } else { + SharedPreferences sharedpreferences1 = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); + String instanceVersion = sharedpreferences1.getString(Helper.INSTANCE_VERSION + userId + instance, null); + Version currentVersion = new Version(instanceVersion); + Version minVersion = new Version("2.7"); + if (currentVersion.compareTo(minVersion) > 0 || currentVersion.equals(minVersion)) { + AlertDialog.Builder builderSingle1 = new AlertDialog.Builder(TootActivity.this, style); + builderSingle1.setTitle(getString(R.string.choose_schedule)); + builderSingle1.setNegativeButton(R.string.device_schedule, (dialog, which) -> { deviceSchedule(time[0]); - } + dialog.dismiss(); + }); + builderSingle1.setPositiveButton(R.string.server_schedule, (dialog, which) -> { + int offset = TimeZone.getDefault().getRawOffset(); + calendar.add(Calendar.MILLISECOND, -offset); + final String date = Helper.dateToString(new Date(calendar.getTimeInMillis())); + serverSchedule(date); + }); + builderSingle1.show(); - alertDialog.dismiss(); + } else { + deviceSchedule(time[0]); } + + alertDialog.dismiss(); } }); alertDialog.show(); @@ -2208,11 +2079,6 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, toot_it.setEnabled(true); return; } - /*if( poll != null && visibility.equals("direct")){ - Toasty.error(getApplicationContext(),getString(R.string.poll_not_private),Toast.LENGTH_LONG).show(); - toot_it.setEnabled(true); - 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); @@ -2248,39 +2114,32 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, textView.setText(""); final SwitchCompat report_mention = preview.findViewById(R.id.report_mention); int finalSplit_toot_size = split_toot_size; - report_mention.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - splitToot = Helper.splitToots(toot_content.getText().toString().trim(), finalSplit_toot_size, isChecked); - textView.setText(""); - int inc = 0; - for (String prev : splitToot) { - if (inc < splitToot.size() - 1) { - textView.setText(textView.getText() + prev + "\n----------\n"); - } + report_mention.setOnCheckedChangeListener((buttonView, isChecked) -> { + splitToot = Helper.splitToots(toot_content.getText().toString().trim(), finalSplit_toot_size, isChecked); + textView.setText(""); + int inc = 0; + for (String prev : splitToot) { + if (inc < splitToot.size() - 1) { + String contentStr = textView.getText() + prev + "\n----------\n"; + textView.setText(contentStr); } } }); int inc = 0; for (String prev : splitToot) { if (inc < splitToot.size() - 1) { - textView.setText(textView.getText() + prev + "\n----------\n"); + String textStr = textView.getText() + prev + "\n----------\n"; + textView.setText(textStr); } } - builderInner.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - toot_it.setEnabled(true); - dialog.dismiss(); - } + builderInner.setNegativeButton(R.string.cancel, (dialog, which) -> { + toot_it.setEnabled(true); + dialog.dismiss(); }); - builderInner.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - createAndSendToot(tootContent, content_type, timestamp); - dialog.dismiss(); - } + builderInner.setPositiveButton(R.string.validate, (dialog, which) -> { + createAndSendToot(tootContent, content_type, timestamp); + dialog.dismiss(); }); AlertDialog alertDialog = builderInner.create(); alertDialog.show(); @@ -2426,9 +2285,9 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, itemContacts.setVisible(false); } int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - if( theme == THEME_LIGHT){ + if (theme == THEME_LIGHT) { //Hack for colors in compose menu - for(int i = 0 ; i < menu.size(); i++){ + for (int i = 0; i < menu.size(); i++) { MenuItem item = menu.getItem(i); SpannableString s = new SpannableString(item.getTitle()); s.setSpan(new ForegroundColorSpan(Color.BLACK), 0, s.length(), 0); @@ -2496,28 +2355,20 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } }); - builderInner.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - } - }); + builderInner.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()); 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); - attachment.setDescription(input.getText().toString()); - addBorder(); - dialog.dismiss(); - } + builderInner.setPositiveButton(R.string.validate, (dialog, which) -> { + new UpdateDescriptionAttachmentAsyncTask(getApplicationContext(), attachment.getId(), input.getText().toString(), account, TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + attachment.setDescription(input.getText().toString()); + addBorder(); + dialog.dismiss(); }); AlertDialog alertDialog = builderInner.create(); - alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); + Objects.requireNonNull(alertDialog.getWindow()).setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); alertDialog.show(); input.requestFocus(); } @@ -2532,43 +2383,35 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, 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) { - dialog.dismiss(); - } - }); - dialog.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - View namebar = findViewById(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) { - //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(), "")); - toot_space_left.setText(String.valueOf(countLength(social, toot_content, toot_cw_content))); - //Moves the cursor - if (selectionBefore >= 0 && selectionBefore < toot_content.length()) - toot_content.setSelection(selectionBefore); - } - ((ViewGroup) namebar.getParent()).removeView(namebar); - break; + dialog.setNegativeButton(R.string.cancel, (dialog1, which) -> dialog1.dismiss()); + dialog.setPositiveButton(R.string.yes, (dialog12, which) -> { + View namebar = findViewById(viewId); + for (Attachment attachment : attachments) { + if (Integer.parseInt(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) { + //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(), "")); + toot_space_left.setText(String.valueOf(countLength(social, toot_content, toot_cw_content))); + //Moves the cursor + if (selectionBefore >= 0 && selectionBefore < toot_content.length()) + toot_content.setSelection(selectionBefore); } + ((ViewGroup) namebar.getParent()).removeView(namebar); + break; } - dialog.dismiss(); - if (attachments.size() == 0) { - toot_sensitive.setVisibility(View.GONE); - isSensitive = false; - toot_sensitive.setChecked(false); - picture_scrollview.setVisibility(View.GONE); - } - toot_picture.setEnabled(true); } + dialog12.dismiss(); + if (attachments.size() == 0) { + toot_sensitive.setVisibility(View.GONE); + isSensitive = false; + toot_sensitive.setChecked(false); + picture_scrollview.setVisibility(View.GONE); + } + toot_picture.setEnabled(true); }); dialog.show(); @@ -2580,36 +2423,28 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, dialog.setTitle(R.string.toot_visibility_tilte); final String[] stringArray = getResources().getStringArray(R.array.toot_visibility); final ArrayAdapter arrayAdapter = new ArrayAdapter<>(TootActivity.this, android.R.layout.simple_list_item_1, stringArray); - dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int position) { - dialog.dismiss(); + dialog.setNegativeButton(R.string.cancel, (dialog1, position) -> dialog1.dismiss()); + dialog.setAdapter(arrayAdapter, (dialog12, position) -> { + switch (position) { + case 0: + visibility = "public"; + toot_visibility.setImageResource(R.drawable.ic_public_toot); + break; + case 1: + visibility = "unlisted"; + toot_visibility.setImageResource(R.drawable.ic_lock_open_toot); + break; + case 2: + visibility = "private"; + toot_visibility.setImageResource(R.drawable.ic_lock_outline_toot); + break; + case 3: + visibility = "direct"; + toot_visibility.setImageResource(R.drawable.ic_mail_outline_toot); + break; } - }); - dialog.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int position) { - switch (position) { - case 0: - visibility = "public"; - toot_visibility.setImageResource(R.drawable.ic_public_toot); - break; - case 1: - visibility = "unlisted"; - toot_visibility.setImageResource(R.drawable.ic_lock_open_toot); - break; - case 2: - visibility = "private"; - toot_visibility.setImageResource(R.drawable.ic_lock_outline_toot); - break; - case 3: - visibility = "direct"; - toot_visibility.setImageResource(R.drawable.ic_mail_outline_toot); - break; - } - dialog.dismiss(); - } + dialog12.dismiss(); }); dialog.show(); } @@ -2643,24 +2478,18 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } else { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(TootActivity.this, style); dialogBuilder.setMessage(R.string.save_draft); - dialogBuilder.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int id) { - if (accountReply == null) { - storeToot(true, false); - } else { - storeToot(false, false); - } - dialog.dismiss(); - finish(); + dialogBuilder.setPositiveButton(R.string.save, (dialog, id) -> { + if (accountReply == null) { + storeToot(true, false); + } else { + storeToot(false, false); } + dialog.dismiss(); + finish(); }); - dialogBuilder.setNegativeButton(R.string.discard, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int id) { - dialog.dismiss(); - finish(); - } + dialogBuilder.setNegativeButton(R.string.discard, (dialog, id) -> { + dialog.dismiss(); + finish(); }); AlertDialog alertDialog = dialogBuilder.create(); alertDialog.setCancelable(false); @@ -2799,37 +2628,34 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, 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) { - Account account = accounts.get(position); - String deltaSearch = ""; - int searchLength = searchDeep; - if (currentCursorPosition < searchDeep) { //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); - } - - if (!search.equals("")) - deltaSearch = deltaSearch.replace("@" + search, ""); - String newContent = oldContent.substring(0, currentCursorPosition - searchLength); - newContent += deltaSearch; - newContent += "@" + account.getAcct() + " "; - int newPosition = newContent.length(); - if (currentCursorPosition < oldContent.length()) - newContent += oldContent.substring(currentCursorPosition); - toot_content.setText(newContent); - toot_space_left.setText(String.valueOf(countLength(social, toot_content, toot_cw_content))); - toot_content.setSelection(newPosition); - AccountsSearchAdapter accountsListAdapter = new AccountsSearchAdapter(TootActivity.this, new ArrayList<>()); - toot_content.setThreshold(1); - toot_content.setAdapter(accountsListAdapter); + toot_content.setOnItemClickListener((parent, view, position, id) -> { + Account account = accounts.get(position); + String deltaSearch = ""; + int searchLength = searchDeep; + if (currentCursorPosition < searchDeep) { //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); + } + + if (!search.equals("")) + deltaSearch = deltaSearch.replace("@" + search, ""); + String newContent = oldContent.substring(0, currentCursorPosition - searchLength); + newContent += deltaSearch; + newContent += "@" + account.getAcct() + " "; + int newPosition = newContent.length(); + if (currentCursorPosition < oldContent.length()) + newContent += oldContent.substring(currentCursorPosition); + toot_content.setText(newContent); + toot_space_left.setText(String.valueOf(countLength(social, toot_content, toot_cw_content))); + toot_content.setSelection(newPosition); + AccountsSearchAdapter accountsListAdapter1 = new AccountsSearchAdapter(TootActivity.this, new ArrayList<>()); + toot_content.setThreshold(1); + toot_content.setAdapter(accountsListAdapter1); }); } } @@ -2853,38 +2679,35 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, String[] searchA = oldContent.substring(0, currentCursorPosition).split("@"); if (searchA.length > 0) { final String search = searchA[searchA.length - 1]; - suggestionsRV.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() { - @Override - public void onItemClick(final View view, final int position) { - final Suggestion suggestion = suggestionsAdapter.getItem(position); + suggestionsRV.addOnItemTouchListener(new RecyclerItemClickListener(this, (view, position) -> { + final Suggestion suggestion = suggestionsAdapter.getItem(position); - String deltaSearch = ""; - int searchLength = searchDeep; - if (currentCursorPosition < searchDeep) { //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); - } - - if (!search.equals("")) - deltaSearch = deltaSearch.replace("@" + search, ""); - String newContent = oldContent.substring(0, currentCursorPosition - searchLength); - newContent += deltaSearch; - newContent += "@" + suggestion.getContent() + " "; - int newPosition = newContent.length(); - if (currentCursorPosition < oldContent.length()) - newContent += oldContent.substring(currentCursorPosition); - wysiwygEditText.setText(newContent); - toot_space_left.setText(String.valueOf(countLength(wysiwyg, toot_cw_content))); - wysiwygEditText.setSelection(newPosition); - suggestionsRV.setVisibility(View.GONE); - + String deltaSearch = ""; + int searchLength = searchDeep; + if (currentCursorPosition < searchDeep) { //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); + } + + if (!search.equals("")) + deltaSearch = deltaSearch.replace("@" + search, ""); + String newContent = oldContent.substring(0, currentCursorPosition - searchLength); + newContent += deltaSearch; + newContent += "@" + suggestion.getContent() + " "; + int newPosition = newContent.length(); + if (currentCursorPosition < oldContent.length()) + newContent += oldContent.substring(currentCursorPosition); + wysiwygEditText.setText(newContent); + toot_space_left.setText(String.valueOf(countLength(wysiwyg, toot_cw_content))); + wysiwygEditText.setSelection(newPosition); + suggestionsRV.setVisibility(View.GONE); + })); } } @@ -2935,38 +2758,35 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, 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 = searchDeep; - if (currentCursorPosition < searchDeep) { //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); - } - - 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); - 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); - + toot_content.setOnItemClickListener((parent, view, position, id) -> { + String shortcode = emojis.get(position).getShortcode(); + String deltaSearch = ""; + int searchLength = searchDeep; + if (currentCursorPosition < searchDeep) { //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); + } + + 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); + toot_content.setText(newContent); + toot_space_left.setText(String.valueOf(countLength(social, toot_content, toot_cw_content))); + toot_content.setSelection(newPosition); + EmojisSearchAdapter emojisSearchAdapter1 = new EmojisSearchAdapter(TootActivity.this, new ArrayList<>()); + toot_content.setThreshold(1); + toot_content.setAdapter(emojisSearchAdapter1); + }); } } else { @@ -2989,38 +2809,35 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, String[] searchA = oldContent.substring(0, currentCursorPosition).split(":"); if (searchA.length > 0) { final String search = searchA[searchA.length - 1]; - suggestionsRV.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() { - @Override - public void onItemClick(final View view, final int position) { - final Suggestion suggestion = suggestionsAdapter.getItem(position); + suggestionsRV.addOnItemTouchListener(new RecyclerItemClickListener(this, (view, position) -> { + final Suggestion suggestion = suggestionsAdapter.getItem(position); - String deltaSearch = ""; - int searchLength = searchDeep; - if (currentCursorPosition < searchDeep) { //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); - } - - if (!search.equals("")) - deltaSearch = deltaSearch.replace(":" + search, ""); - String newContent = oldContent.substring(0, currentCursorPosition - searchLength); - newContent += deltaSearch; - newContent += ":" + suggestion.getContent() + ": "; - int newPosition = newContent.length(); - if (currentCursorPosition < oldContent.length()) - newContent += oldContent.substring(currentCursorPosition); - wysiwygEditText.setText(newContent); - toot_space_left.setText(String.valueOf(countLength(wysiwyg, toot_cw_content))); - wysiwygEditText.setSelection(newPosition); - suggestionsRV.setVisibility(View.GONE); - + String deltaSearch = ""; + int searchLength = searchDeep; + if (currentCursorPosition < searchDeep) { //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); + } + + if (!search.equals("")) + deltaSearch = deltaSearch.replace(":" + search, ""); + String newContent = oldContent.substring(0, currentCursorPosition - searchLength); + newContent += deltaSearch; + newContent += ":" + suggestion.getContent() + ": "; + int newPosition = newContent.length(); + if (currentCursorPosition < oldContent.length()) + newContent += oldContent.substring(currentCursorPosition); + wysiwygEditText.setText(newContent); + toot_space_left.setText(String.valueOf(countLength(wysiwyg, toot_cw_content))); + wysiwygEditText.setSelection(newPosition); + suggestionsRV.setVisibility(View.GONE); + })); } } @@ -3028,28 +2845,6 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } } - 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) { - imageWidth = bitmap.getWidth(); - imageHeight = bitmap.getHeight(); - } - if (inUri != null) { - File imageFile = new File(inUri.getPath()); - size = imageFile.length(); - } - if (imageWidth != -1 && imageHeight != -1 && size != -1) { - - } - } catch (IOException e) { - e.printStackTrace(); - } - } - @Override public void onRetrieveSearch(APIResponse apiResponse) { @@ -3075,40 +2870,37 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, if (searchA.length < 1) return; 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()) - return; - String tag = tags.get(position); - String deltaSearch = ""; - int searchLength = searchDeep; - if (currentCursorPosition < searchDeep) { //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); - } - - 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); - toot_content.setText(newContent); - toot_space_left.setText(String.valueOf(countLength(social, toot_content, toot_cw_content))); - toot_content.setSelection(newPosition); - TagsSearchAdapter tagsSearchAdapter = new TagsSearchAdapter(TootActivity.this, new ArrayList<>()); - toot_content.setThreshold(1); - toot_content.setAdapter(tagsSearchAdapter); - + toot_content.setOnItemClickListener((parent, view, position, id) -> { + if (position >= tags.size()) + return; + String tag = tags.get(position); + String deltaSearch = ""; + int searchLength = searchDeep; + if (currentCursorPosition < searchDeep) { //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); + } + + 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); + toot_content.setText(newContent); + toot_space_left.setText(String.valueOf(countLength(social, toot_content, toot_cw_content))); + toot_content.setSelection(newPosition); + TagsSearchAdapter tagsSearchAdapter1 = new TagsSearchAdapter(TootActivity.this, new ArrayList<>()); + toot_content.setThreshold(1); + toot_content.setAdapter(tagsSearchAdapter1); + }); } else { int currentCursorPosition = wysiwygEditText.getSelectionStart(); @@ -3130,38 +2922,35 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, String[] searchA = oldContent.substring(0, currentCursorPosition).split("#"); if (searchA.length > 0) { final String search = searchA[searchA.length - 1]; - suggestionsRV.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() { - @Override - public void onItemClick(final View view, final int position) { - final Suggestion suggestion = suggestionsAdapter.getItem(position); + suggestionsRV.addOnItemTouchListener(new RecyclerItemClickListener(this, (view, position) -> { + final Suggestion suggestion = suggestionsAdapter.getItem(position); - String deltaSearch = ""; - int searchLength = searchDeep; - if (currentCursorPosition < searchDeep) { //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); - } - - if (!search.equals("")) - deltaSearch = deltaSearch.replace("#" + search, ""); - String newContent = oldContent.substring(0, currentCursorPosition - searchLength); - newContent += deltaSearch; - newContent += "#" + suggestion.getContent() + " "; - int newPosition = newContent.length(); - if (currentCursorPosition < oldContent.length()) - newContent += oldContent.substring(currentCursorPosition); - wysiwygEditText.setText(newContent); - toot_space_left.setText(String.valueOf(countLength(wysiwyg, toot_cw_content))); - wysiwygEditText.setSelection(newPosition); - suggestionsRV.setVisibility(View.GONE); - + String deltaSearch = ""; + int searchLength = searchDeep; + if (currentCursorPosition < searchDeep) { //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); + } + + if (!search.equals("")) + deltaSearch = deltaSearch.replace("#" + search, ""); + String newContent = oldContent.substring(0, currentCursorPosition - searchLength); + newContent += deltaSearch; + newContent += "#" + suggestion.getContent() + " "; + int newPosition = newContent.length(); + if (currentCursorPosition < oldContent.length()) + newContent += oldContent.substring(currentCursorPosition); + wysiwygEditText.setText(newContent); + toot_space_left.setText(String.valueOf(countLength(wysiwyg, toot_cw_content))); + wysiwygEditText.setSelection(newPosition); + suggestionsRV.setVisibility(View.GONE); + })); } } @@ -3195,13 +2984,13 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, toRemove.clear(); } String content = status.getContent(); - Pattern mentionLink = Pattern.compile("(<\\s?a\\s?href=\"https?:\\/\\/([\\da-z\\.-]+\\.[a-z\\.]{2,10})\\/(@[\\/\\w._-]*)\"\\s?[^.]*<\\s?\\/\\s?a\\s?>)"); + Pattern mentionLink = Pattern.compile("(<\\s?a\\s?href=\"https?://([\\da-z.-]+\\.[a-z.]{2,10})/(@[/\\w._-]*)\"\\s?[^.]*<\\s?/\\s?a\\s?>)"); Matcher matcher = mentionLink.matcher(content); if (matcher.find()) { content = matcher.replaceAll("$3@$2"); } - Pattern mentionLinkPleroma = Pattern.compile("(<\\s?a\\s?href=\"https?:\\/\\/([\\da-z\\.-]+\\.[a-z\\.]{2,10})\\/users/([\\/\\w._-]*)\"\\s?[^.]*<\\s?\\/\\s?a\\s?>)"); + Pattern mentionLinkPleroma = Pattern.compile("(<\\s?a\\s?href=\"https?://([\\da-z.-]+\\.[a-z.]{2,10})/users/([/\\w._-]*)\"\\s?[^.]*<\\s?/\\s?a\\s?>)"); Matcher matcherPleroma = mentionLinkPleroma.matcher(content); if (matcherPleroma.find()) { content = matcherPleroma.replaceAll("@$3@$2"); @@ -3211,7 +3000,6 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, 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) { @@ -3251,31 +3039,20 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } }); imageView.setTag(attachment.getId()); - imageView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); - String instanceVersion = sharedpreferences.getString(Helper.INSTANCE_VERSION + userId + instance, null); - if (instanceVersion != null) { - Version currentVersion = new Version(instanceVersion); - Version minVersion = new Version("2.0"); - if (currentVersion.compareTo(minVersion) == 1 || currentVersion.equals(minVersion)) { - imageView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - showAddDescription(attachment); - } - }); - } + imageView.setOnClickListener(view -> { + SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); + String instanceVersion = sharedpreferences.getString(Helper.INSTANCE_VERSION + userId + instance, null); + if (instanceVersion != null) { + Version currentVersion = new Version(instanceVersion); + Version minVersion = new Version("2.0"); + if (currentVersion.compareTo(minVersion) > 0 || currentVersion.equals(minVersion)) { + imageView.setOnClickListener(view1 -> showAddDescription(attachment)); } } }); - imageView.setOnLongClickListener(new View.OnLongClickListener() { - @Override - public boolean onLongClick(View view) { - showRemove(imageView.getId()); - return false; - } + imageView.setOnLongClickListener(view -> { + showRemove(imageView.getId()); + return false; }); addBorder(); if (attachments.size() < max_media_count) @@ -3298,16 +3075,8 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, if (!displayWYSIWYG()) { toot_content.setText(content); } else { - if (content != null) { - content = content.replaceAll("]*><\\/p>", ""); - } + content = content.replaceAll("]*>

", ""); wysiwyg.render(content); - try { - - } 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()) { @@ -3382,7 +3151,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, toRemove.clear(); } String content = status.getContent(); - Pattern mentionLink = Pattern.compile("(<\\s?a\\s?href=\"https?:\\/\\/([\\da-z\\.-]+\\.[a-z\\.]{2,10})\\/(@[\\/\\w._-]*)\"\\s?[^.]*<\\s?\\/\\s?a\\s?>)"); + Pattern mentionLink = Pattern.compile("(<\\s?a\\s?href=\"https?://([\\da-z.-]+\\.[a-z.]{2,10})/(@[/\\w._-]*)\"\\s?[^.]*<\\s?/\\s?a\\s?>)"); Matcher matcher = mentionLink.matcher(content); if (matcher.find()) { content = matcher.replaceAll("$3@$2"); @@ -3391,7 +3160,6 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, 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) { @@ -3422,31 +3190,20 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } }); imageView.setTag(attachment.getId()); - imageView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); - String instanceVersion = sharedpreferences.getString(Helper.INSTANCE_VERSION + userId + instance, null); - if (instanceVersion != null) { - Version currentVersion = new Version(instanceVersion); - Version minVersion = new Version("2.0"); - if (currentVersion.compareTo(minVersion) == 1 || currentVersion.equals(minVersion)) { - imageView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - showAddDescription(attachment); - } - }); - } + imageView.setOnClickListener(view -> { + SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); + String instanceVersion = sharedpreferences.getString(Helper.INSTANCE_VERSION + userId + instance, null); + if (instanceVersion != null) { + Version currentVersion = new Version(instanceVersion); + Version minVersion = new Version("2.0"); + if (currentVersion.compareTo(minVersion) > 0 || currentVersion.equals(minVersion)) { + imageView.setOnClickListener(view1 -> showAddDescription(attachment)); } } }); - imageView.setOnLongClickListener(new View.OnLongClickListener() { - @Override - public boolean onLongClick(View view) { - showRemove(imageView.getId()); - return false; - } + imageView.setOnLongClickListener(view -> { + showRemove(imageView.getId()); + return false; }); addBorder(); if (attachments.size() < max_media_count) @@ -3603,9 +3360,11 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, boolean forwardTags = sharedpreferences.getBoolean(Helper.SET_FORWARD_TAGS_IN_REPLY, false); if (tootReply != null && forwardTags && tootReply.getTags() != null && tootReply.getTags().size() > 0) { int currentCursorPosition = toot_content.getSelectionStart(); - toot_content.setText(toot_content.getText() + "\n"); + String contentStr = toot_content.getText() + "\n"; + toot_content.setText(contentStr); for (Tag tag : tootReply.getTags()) { - toot_content.setText(toot_content.getText() + " #" + tag.getName()); + String tempContentStr = toot_content.getText() + " #" + tag.getName(); + toot_content.setText(tempContentStr); } toot_content.setSelection(currentCursorPosition); toot_space_left.setText(String.valueOf(countLength(social, toot_content, toot_cw_content))); @@ -3644,41 +3403,35 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, int finalMax_entry = max_entry; int finalMax_length = max_length; - add.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - 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_items_container.addView(poll_item); - } - pollCountItem++; - if (pollCountItem >= finalMax_entry) { - add.setVisibility(View.GONE); - } else { - add.setVisibility(View.VISIBLE); - } - remove.setVisibility(View.VISIBLE); + add.setOnClickListener(v -> { + if (pollCountItem < finalMax_entry) { + EditText poll_item = new EditText(TootActivity.this); + InputFilter[] fArray1 = new InputFilter[1]; + fArray1[0] = new InputFilter.LengthFilter(finalMax_length); + poll_item.setFilters(fArray1); + poll_item.setHint(getString(R.string.poll_choice_s, (pollCountItem + 1))); + poll_items_container.addView(poll_item); } - }); - remove.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (pollCountItem > 2) { - int childCount = poll_items_container.getChildCount(); - poll_items_container.removeViewAt(childCount - 1); - } - pollCountItem--; - if (pollCountItem <= 2) { - remove.setVisibility(View.GONE); - } else { - remove.setVisibility(View.VISIBLE); - } + pollCountItem++; + if (pollCountItem >= finalMax_entry) { + add.setVisibility(View.GONE); + } else { add.setVisibility(View.VISIBLE); } + remove.setVisibility(View.VISIBLE); + }); + remove.setOnClickListener(v -> { + if (pollCountItem > 2) { + int childCount = poll_items_container.getChildCount(); + poll_items_container.removeViewAt(childCount - 1); + } + pollCountItem--; + if (pollCountItem <= 2) { + remove.setVisibility(View.GONE); + } else { + remove.setVisibility(View.VISIBLE); + } + add.setVisibility(View.VISIBLE); }); ArrayAdapter pollduration = ArrayAdapter.createFromResource(TootActivity.this, @@ -3750,109 +3503,99 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, } - alertPoll.setNegativeButton(R.string.delete, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int whichButton) { - if (poll != null) - poll = null; - poll_action.setVisibility(View.GONE); - toot_picture.setVisibility(View.VISIBLE); - if (attachments != null && attachments.size() > 0) - picture_scrollview.setVisibility(View.VISIBLE); - dialog.dismiss(); - } + alertPoll.setNegativeButton(R.string.delete, (dialog, whichButton) -> { + if (poll != null) + poll = null; + poll_action.setVisibility(View.GONE); + toot_picture.setVisibility(View.VISIBLE); + if (attachments != null && attachments.size() > 0) + picture_scrollview.setVisibility(View.VISIBLE); + dialog.dismiss(); }); alertPoll.setPositiveButton(R.string.validate, null); final AlertDialog alertPollDiaslog = alertPoll.create(); - alertPollDiaslog.setOnShowListener(new DialogInterface.OnShowListener() { + alertPollDiaslog.setOnShowListener(dialog -> { - @Override - public void onShow(DialogInterface dialog) { + Button b = alertPollDiaslog.getButton(AlertDialog.BUTTON_POSITIVE); + b.setOnClickListener(view1 -> { + int poll_duration_pos = poll_duration.getSelectedItemPosition(); - Button b = alertPollDiaslog.getButton(AlertDialog.BUTTON_POSITIVE); - b.setOnClickListener(new View.OnClickListener() { + int poll_choice_pos = poll_choice.getSelectedItemPosition(); + String choice1 = choice_1.getText().toString().trim(); + String choice2 = choice_2.getText().toString().trim(); - @Override - public void onClick(View view) { - int poll_duration_pos = poll_duration.getSelectedItemPosition(); + if (choice1.isEmpty() && choice2.isEmpty()) { + Toasty.error(getApplicationContext(), getString(R.string.poll_invalid_choices), Toast.LENGTH_SHORT).show(); + } else { + poll = new Poll(); + poll.setMultiple(poll_choice_pos != 0); + int expire; + switch (poll_duration_pos) { + case 0: + expire = 300; + break; + case 1: + expire = 1800; + break; + case 2: + expire = 3600; + break; + case 3: + expire = 21600; + break; + case 4: + expire = 86400; + break; + case 5: + expire = 259200; + break; + case 6: + expire = 604800; + break; + default: + expire = 864000; + } + poll.setExpires_in(expire); - int poll_choice_pos = poll_choice.getSelectedItemPosition(); - String choice1 = choice_1.getText().toString().trim(); - String choice2 = choice_2.getText().toString().trim(); + List pollOptions = new ArrayList<>(); + PollOptions pollOption1 = new PollOptions(); + pollOption1.setTitle(choice1); + pollOptions.add(pollOption1); - if (choice1.isEmpty() && choice2.isEmpty()) { - Toasty.error(getApplicationContext(), getString(R.string.poll_invalid_choices), Toast.LENGTH_SHORT).show(); - } else { - poll = new Poll(); - poll.setMultiple(poll_choice_pos != 0); - int expire = 0; - switch (poll_duration_pos) { - case 0: - expire = 300; - break; - case 1: - expire = 1800; - break; - case 2: - expire = 3600; - break; - case 3: - expire = 21600; - break; - case 4: - expire = 86400; - break; - case 5: - expire = 259200; - break; - case 6: - expire = 604800; - break; - default: - expire = 864000; - } - poll.setExpires_in(expire); + PollOptions pollOption2 = new PollOptions(); + pollOption2.setTitle(choice2); + pollOptions.add(pollOption2); - List pollOptions = new ArrayList<>(); - PollOptions pollOption1 = new PollOptions(); - pollOption1.setTitle(choice1); - pollOptions.add(pollOption1); - - PollOptions pollOption2 = new PollOptions(); - pollOption2.setTitle(choice2); - pollOptions.add(pollOption2); - - int childCount = poll_items_container.getChildCount(); - if (childCount > 2) { - for (int i = 2; i < childCount; i++) { - PollOptions pollItem = new PollOptions(); - 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())) { - options.add(po.getTitle().trim()); - } else { - doubleTitle = true; - } - } - if (!doubleTitle) { - poll.setOptionsList(pollOptions); - dialog.dismiss(); - } else { - Toasty.error(getApplicationContext(), getString(R.string.poll_duplicated_entry), Toast.LENGTH_SHORT).show(); - } - } - poll_action.setVisibility(View.VISIBLE); - if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { - toot_picture.setVisibility(View.GONE); - picture_scrollview.setVisibility(View.GONE); + int childCount = poll_items_container.getChildCount(); + if (childCount > 2) { + for (int i = 2; i < childCount; i++) { + PollOptions pollItem = new PollOptions(); + 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())) { + options.add(po.getTitle().trim()); + } else { + doubleTitle = true; + } + } + if (!doubleTitle) { + poll.setOptionsList(pollOptions); + dialog.dismiss(); + } else { + Toasty.error(getApplicationContext(), getString(R.string.poll_duplicated_entry), Toast.LENGTH_SHORT).show(); + } + } + poll_action.setVisibility(View.VISIBLE); + if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { + toot_picture.setVisibility(View.GONE); + picture_scrollview.setVisibility(View.GONE); + } + }); }); alertPollDiaslog.show(); @@ -3917,12 +3660,9 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, final AlertDialog.Builder builderSingle = new AlertDialog.Builder(TootActivity.this, style); AccountsReplyAdapter accountsReplyAdapter = new AccountsReplyAdapter(new WeakReference<>(TootActivity.this), accounts, checkedValues); builderSingle.setTitle(getString(R.string.select_accounts)).setAdapter(accountsReplyAdapter, null); - builderSingle.setNegativeButton(R.string.validate, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - toot_content.setSelection(toot_content.getText().length()); - } + builderSingle.setNegativeButton(R.string.validate, (dialog, which) -> { + dialog.dismiss(); + toot_content.setSelection(toot_content.getText().length()); }); builderSingle.show(); } @@ -4012,128 +3752,55 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, private void renderEditor() { - findViewById(R.id.action_h1).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - wysiwyg.updateTextStyle(EditorTextStyle.H1); - } - }); + findViewById(R.id.action_h1).setOnClickListener(v -> wysiwyg.updateTextStyle(EditorTextStyle.H1)); - findViewById(R.id.action_h2).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - wysiwyg.updateTextStyle(EditorTextStyle.H2); - } - }); + findViewById(R.id.action_h2).setOnClickListener(v -> wysiwyg.updateTextStyle(EditorTextStyle.H2)); - findViewById(R.id.action_h3).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - wysiwyg.updateTextStyle(EditorTextStyle.H3); - } - }); + findViewById(R.id.action_h3).setOnClickListener(v -> wysiwyg.updateTextStyle(EditorTextStyle.H3)); - findViewById(R.id.action_bold).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - wysiwyg.updateTextStyle(EditorTextStyle.BOLD); - } - }); + findViewById(R.id.action_bold).setOnClickListener(v -> wysiwyg.updateTextStyle(EditorTextStyle.BOLD)); - findViewById(R.id.action_Italic).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - wysiwyg.updateTextStyle(EditorTextStyle.ITALIC); - } - }); + findViewById(R.id.action_Italic).setOnClickListener(v -> wysiwyg.updateTextStyle(EditorTextStyle.ITALIC)); - findViewById(R.id.action_indent).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - wysiwyg.updateTextStyle(EditorTextStyle.INDENT); - } - }); + findViewById(R.id.action_indent).setOnClickListener(v -> wysiwyg.updateTextStyle(EditorTextStyle.INDENT)); - findViewById(R.id.action_outdent).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - wysiwyg.updateTextStyle(EditorTextStyle.OUTDENT); - } - }); + findViewById(R.id.action_outdent).setOnClickListener(v -> wysiwyg.updateTextStyle(EditorTextStyle.OUTDENT)); - findViewById(R.id.action_bulleted).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - wysiwyg.insertList(false); - } - }); + findViewById(R.id.action_bulleted).setOnClickListener(v -> wysiwyg.insertList(false)); - findViewById(R.id.action_color).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - new ColorPickerPopup.Builder(getApplicationContext()) - .enableAlpha(false) - .okTitle(getString(R.string.validate)) - .cancelTitle(getString(R.string.cancel)) - .showIndicator(true) - .showValue(true) - .build() - .show(findViewById(android.R.id.content), new ColorPickerPopup.ColorPickerObserver() { - @Override - public void onColorPicked(int color) { - wysiwyg.updateTextColor(colorHex(color)); - } + findViewById(R.id.action_color).setOnClickListener(v -> new ColorPickerPopup.Builder(getApplicationContext()) + .enableAlpha(false) + .okTitle(getString(R.string.validate)) + .cancelTitle(getString(R.string.cancel)) + .showIndicator(true) + .showValue(true) + .build() + .show(findViewById(android.R.id.content), new ColorPickerPopup.ColorPickerObserver() { + @Override + public void onColorPicked(int color) { + wysiwyg.updateTextColor(colorHex(color)); + } - }); - } - }); + })); //Remove colours findViewById(R.id.action_color).setVisibility(View.GONE); - findViewById(R.id.action_unordered_numbered).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - wysiwyg.insertList(true); - } - }); + findViewById(R.id.action_unordered_numbered).setOnClickListener(v -> wysiwyg.insertList(true)); - findViewById(R.id.action_hr).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - wysiwyg.insertDivider(); - } - }); + findViewById(R.id.action_hr).setOnClickListener(v -> wysiwyg.insertDivider()); - findViewById(R.id.action_insert_image).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - wysiwyg.openImagePicker(); - } - }); + findViewById(R.id.action_insert_image).setOnClickListener(v -> wysiwyg.openImagePicker()); - findViewById(R.id.action_insert_link).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - wysiwyg.insertLink(); - } - }); + findViewById(R.id.action_insert_link).setOnClickListener(v -> wysiwyg.insertLink()); - findViewById(R.id.action_erase).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - wysiwyg.clearAllContents(); - } - }); + findViewById(R.id.action_erase).setOnClickListener(v -> wysiwyg.clearAllContents()); //Remove eraser findViewById(R.id.action_erase).setVisibility(View.GONE); - findViewById(R.id.action_blockquote).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - wysiwyg.updateTextStyle(EditorTextStyle.BLOCKQUOTE); - wysiwyg.updateTextColor("#000000"); - } + findViewById(R.id.action_blockquote).setOnClickListener(v -> { + wysiwyg.updateTextStyle(EditorTextStyle.BLOCKQUOTE); + wysiwyg.updateTextColor("#000000"); }); wysiwyg.render(); @@ -4190,10 +3857,10 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, @Override protected void onPostExecute(Void result) { - if( activityWeakReference.get().findViewById(R.id.compression_loader) != null) { + if (activityWeakReference.get().findViewById(R.id.compression_loader) != null) { activityWeakReference.get().findViewById(R.id.compression_loader).setVisibility(View.GONE); } - if( activityWeakReference.get().findViewById(R.id.picture_scrollview) != null){ + if (activityWeakReference.get().findViewById(R.id.picture_scrollview) != null) { activityWeakReference.get().findViewById(R.id.picture_scrollview).setVisibility(View.VISIBLE); } if (!error) { @@ -4206,13 +3873,13 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate, toot_picture = this.activityWeakReference.get().findViewById(R.id.toot_picture); toot_it = this.activityWeakReference.get().findViewById(R.id.toot_it); toot_picture_container = this.activityWeakReference.get().findViewById(R.id.toot_picture_container); - if( toot_picture_container != null){ + if (toot_picture_container != null) { toot_picture_container.setVisibility(View.VISIBLE); } - if( toot_picture != null){ + if (toot_picture != null) { toot_picture.setEnabled(false); } - if( toot_it != null){ + if (toot_it != null) { toot_it.setEnabled(false); } if (filename == null) { 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 72b0d0fa9..2adf0b1a2 100644 --- a/app/src/main/java/app/fedilab/android/activities/TootInfoActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/TootInfoActivity.java @@ -136,7 +136,7 @@ public class TootInfoActivity extends BaseActivity { private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter { ScreenSlidePagerAdapter(FragmentManager fm) { - super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT); + super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT); } @NotNull 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 af499934c..9541f5b23 100644 --- a/app/src/main/java/app/fedilab/android/activities/WebviewActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/WebviewActivity.java @@ -16,8 +16,8 @@ package app.fedilab.android.activities; import android.Manifest; +import android.annotation.SuppressLint; import android.content.Context; -import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; @@ -34,7 +34,6 @@ import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; -import android.webkit.DownloadListener; import android.widget.ArrayAdapter; import android.widget.FrameLayout; import android.widget.Toast; @@ -43,6 +42,8 @@ import androidx.appcompat.app.AlertDialog; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; +import org.jetbrains.annotations.NotNull; + import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; @@ -57,7 +58,6 @@ import app.fedilab.android.sqlite.Sqlite; import app.fedilab.android.webview.CustomWebview; import app.fedilab.android.webview.MastalabWebChromeClient; import app.fedilab.android.webview.MastalabWebViewClient; -import app.fedilab.android.webview.ProxyHelper; import es.dmoral.toasty.Toasty; @@ -76,6 +76,7 @@ public class WebviewActivity extends BaseActivity { private Menu defaultMenu; private MastalabWebViewClient mastalabWebViewClient; + @SuppressLint("SetJavaScriptEnabled") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -85,9 +86,6 @@ public class WebviewActivity extends BaseActivity { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme_Fedilab); break; - case Helper.THEME_DARK: - setTheme(R.style.AppThemeDark); - break; case Helper.THEME_BLACK: setTheme(R.style.AppThemeBlack); break; @@ -115,68 +113,53 @@ public class WebviewActivity extends BaseActivity { webView.getSettings().setJavaScriptEnabled(true); - MastalabWebChromeClient mastalabWebChromeClient = new MastalabWebChromeClient(WebviewActivity.this, webView, webview_container, videoLayout); - mastalabWebChromeClient.setOnToggledFullscreen(new MastalabWebChromeClient.ToggledFullscreenCallback() { - @Override - public void toggledFullscreen(boolean fullscreen) { + mastalabWebChromeClient.setOnToggledFullscreen(fullscreen -> { - if (fullscreen) { - videoLayout.setVisibility(View.VISIBLE); - WindowManager.LayoutParams attrs = getWindow().getAttributes(); - attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN; - attrs.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; - getWindow().setAttributes(attrs); - getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE); - } else { - WindowManager.LayoutParams attrs = getWindow().getAttributes(); - attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN; - attrs.flags &= ~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; - getWindow().setAttributes(attrs); - getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE); - videoLayout.setVisibility(View.GONE); - } + if (fullscreen) { + videoLayout.setVisibility(View.VISIBLE); + WindowManager.LayoutParams attrs = getWindow().getAttributes(); + attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN; + attrs.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; + getWindow().setAttributes(attrs); + getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE); + } else { + WindowManager.LayoutParams attrs = getWindow().getAttributes(); + attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN; + attrs.flags &= ~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; + getWindow().setAttributes(attrs); + getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE); + videoLayout.setVisibility(View.GONE); } }); webView.setWebChromeClient(mastalabWebChromeClient); mastalabWebViewClient = new MastalabWebViewClient(WebviewActivity.this); webView.setWebViewClient(mastalabWebViewClient); - webView.setDownloadListener(new DownloadListener() { - @Override - public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { + webView.setDownloadListener((url, userAgent, contentDisposition, mimetype, contentLength) -> { - 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); - } + 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 { + Helper.manageDownloads(WebviewActivity.this, url); } }); if (!url.toLowerCase().startsWith("http://") && !url.toLowerCase().startsWith("https://")) url = "http://" + url; 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) - trackingDomains = new ArrayList<>(); - // Get a handler that can be used to post to the main thread - Handler mainHandler = new Handler(getMainLooper()); - Runnable myRunnable = new Runnable() { - @Override - public void run() { - webView.loadUrl(url); - } - }; - mainHandler.post(myRunnable); + AsyncTask.execute(() -> { + SQLiteDatabase db = Sqlite.getInstance(WebviewActivity.this, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); + trackingDomains = new DomainBlockDAO(WebviewActivity.this, db).getAll(); + if (trackingDomains == null) + trackingDomains = new ArrayList<>(); + // Get a handler that can be used to post to the main thread + Handler mainHandler = new Handler(getMainLooper()); + Runnable myRunnable = () -> webView.loadUrl(url); + mainHandler.post(myRunnable); - } }); } else webView.loadUrl(url); @@ -213,7 +196,7 @@ public class WebviewActivity extends BaseActivity { } @Override - public boolean onCreateOptionsMenu(Menu menu) { + public boolean onCreateOptionsMenu(@NotNull Menu menu) { getMenuInflater().inflate(R.menu.main_webview, menu); defaultMenu = menu; if (peertubeLink) { @@ -253,20 +236,12 @@ public class WebviewActivity extends BaseActivity { AlertDialog.Builder builder = new AlertDialog.Builder(WebviewActivity.this, style); builder.setTitle(R.string.list_of_blocked_domains); - builder.setNegativeButton(R.string.close, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - } - }); + builder.setNegativeButton(R.string.close, (dialog, which) -> dialog.dismiss()); - builder.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - String strName = arrayAdapter.getItem(which); - assert strName != null; - Toasty.info(getApplicationContext(), strName, Toast.LENGTH_LONG).show(); - } + builder.setAdapter(arrayAdapter, (dialog, which) -> { + String strName = arrayAdapter.getItem(which); + assert strName != null; + Toasty.info(getApplicationContext(), strName, Toast.LENGTH_LONG).show(); }); builder.show(); @@ -281,40 +256,7 @@ public class WebviewActivity extends BaseActivity { return true; case R.id.action_comment: Toasty.info(getApplicationContext(), getString(R.string.retrieve_remote_status), Toast.LENGTH_LONG).show(); - new AsyncTask() { - - private List remoteStatuses; - private WeakReference contextReference = new WeakReference<>(WebviewActivity.this); - - @Override - protected Void doInBackground(Void... voids) { - - if (url != null) { - APIResponse search = new API(contextReference.get()).search(peertubeLinkToFetch); - if (search != null && search.getResults() != null) { - remoteStatuses = search.getResults().getStatuses(); - } - } - return null; - } - - @Override - 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(); - return; - } - if (remoteStatuses.get(0).getReblog() != null) { - b.putParcelable("tootReply", remoteStatuses.get(0).getReblog()); - } 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); + new connnectAsync(new WeakReference<>(WebviewActivity.this), url, peertubeLinkToFetch).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); return true; default: return super.onOptionsItemSelected(item); @@ -354,4 +296,45 @@ public class WebviewActivity extends BaseActivity { if (webView != null) webView.destroy(); } + + static class connnectAsync extends AsyncTask> { + private WeakReference contextReference; + private String url; + private String peertubeLinkToFetch; + + connnectAsync(WeakReference contextReference, String url, String peertubeLinkToFetch) { + this.contextReference = contextReference; + this.url = url; + this.peertubeLinkToFetch = peertubeLinkToFetch; + } + + @Override + protected List doInBackground(Void... voids) { + List remoteStatuses = null; + if (url != null) { + APIResponse search = new API(contextReference.get()).search(peertubeLinkToFetch); + if (search != null && search.getResults() != null) { + remoteStatuses = search.getResults().getStatuses(); + } + } + return remoteStatuses; + } + + @Override + protected void onPostExecute(List remoteStatuses) { + Intent intent = new Intent(contextReference.get(), TootActivity.class); + Bundle b = new Bundle(); + if (remoteStatuses == null || remoteStatuses.size() == 0) { + Toasty.error(contextReference.get(), contextReference.get().getString(R.string.toast_error), Toast.LENGTH_LONG).show(); + return; + } + if (remoteStatuses.get(0).getReblog() != null) { + b.putParcelable("tootReply", remoteStatuses.get(0).getReblog()); + } else { + b.putParcelable("tootReply", remoteStatuses.get(0)); + } + intent.putExtras(b); //Put your id to your next Intent + contextReference.get().startActivity(intent); + } + } } 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 20c476394..5b5bb12ea 100644 --- a/app/src/main/java/app/fedilab/android/activities/WebviewConnectActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/WebviewConnectActivity.java @@ -16,6 +16,7 @@ package app.fedilab.android.activities; +import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; @@ -51,7 +52,6 @@ import app.fedilab.android.asynctasks.UpdateAccountInfoAsyncTask; import app.fedilab.android.client.HttpsConnection; import app.fedilab.android.helper.Helper; import app.fedilab.android.webview.CustomWebview; -import app.fedilab.android.webview.ProxyHelper; import es.dmoral.toasty.Toasty; /** @@ -67,7 +67,6 @@ public class WebviewConnectActivity extends BaseActivity { private String instance; private UpdateAccountInfoAsyncTask.SOCIAL social; - @SuppressWarnings("deprecation") public static void clearCookies(Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { @@ -84,6 +83,7 @@ public class WebviewConnectActivity extends BaseActivity { } } + @SuppressLint("SetJavaScriptEnabled") public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); @@ -92,9 +92,6 @@ public class WebviewConnectActivity extends BaseActivity { case Helper.THEME_LIGHT: setTheme(R.style.AppTheme_Fedilab); break; - case Helper.THEME_DARK: - setTheme(R.style.AppThemeDark); - break; case Helper.THEME_BLACK: setTheme(R.style.AppThemeBlack); break; @@ -122,19 +119,14 @@ public class WebviewConnectActivity extends BaseActivity { actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close); TextView toolbar_title = actionBar.getCustomView().findViewById(R.id.toolbar_title); - toolbar_close.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - finish(); - } - }); + toolbar_close.setOnClickListener(v -> finish()); toolbar_title.setText(R.string.add_account); } webView = findViewById(R.id.webviewConnect); clearCookies(getApplicationContext()); webView.getSettings().setJavaScriptEnabled(true); String user_agent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, null); - if( user_agent != null) { + if (user_agent != null) { webView.getSettings().setUserAgentString(user_agent); } if (android.os.Build.VERSION.SDK_INT >= 21) { @@ -160,7 +152,6 @@ public class WebviewConnectActivity extends BaseActivity { webView.setWebViewClient(new WebViewClient() { - @SuppressWarnings("deprecation") @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { super.shouldOverrideUrlLoading(view, url); @@ -181,28 +172,25 @@ public class WebviewConnectActivity extends BaseActivity { parameters.put(Helper.REDIRECT_URI, Helper.REDIRECT_CONTENT_WEB); parameters.put("grant_type", "authorization_code"); parameters.put("code", code); - new Thread(new Runnable() { - @Override - public void run() { + new Thread(() -> { + try { + final String response = new HttpsConnection(WebviewConnectActivity.this, instance).post(Helper.instanceWithProtocol(getApplicationContext(), instance) + action, 30, parameters, null); + JSONObject resobj; try { - final String response = new HttpsConnection(WebviewConnectActivity.this, instance).post(Helper.instanceWithProtocol(getApplicationContext(), instance) + action, 30, parameters, null); - JSONObject resobj; - try { - resobj = new JSONObject(response); - String token = resobj.get("access_token").toString(); - String refresh_token = null; - 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(); - editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, token); - 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) { + resobj = new JSONObject(response); + String token = resobj.get("access_token").toString(); + String refresh_token = null; + if (resobj.has("refresh_token")) + refresh_token = resobj.get("refresh_token").toString(); + SharedPreferences sharedpreferences1 = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + SharedPreferences.Editor editor = sharedpreferences1.edit(); + editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, token); + 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(); return true; 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 803eb1bd8..3d5dfa099 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/ManageFiltersAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/ManageFiltersAsyncTask.java @@ -38,6 +38,7 @@ public class ManageFiltersAsyncTask extends AsyncTask { private action apiAction; private WeakReference contextReference; private Filters filter; + public ManageFiltersAsyncTask(Context context, action apiAction, Filters filter, OnFilterActionInterface onFilterActionInterface) { contextReference = new WeakReference<>(context); this.listener = onFilterActionInterface; 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 7aa85117b..e60e86481 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/ManageListsAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/ManageListsAsyncTask.java @@ -43,6 +43,7 @@ public class ManageListsAsyncTask extends AsyncTask { private String max_id, since_id; private int limit; private String search; + public ManageListsAsyncTask(Context context, action apiAction, String[] accountsId, String targetedId, String listId, String title, OnListActionInterface onListActionInterface) { contextReference = new WeakReference<>(context); this.listener = onListActionInterface; 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 2658694a9..a09fcda14 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/ManagePlaylistsAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/ManagePlaylistsAsyncTask.java @@ -46,6 +46,7 @@ public class ManagePlaylistsAsyncTask extends AsyncTask { private String max_id; private Playlist playlist; private String videoId; + public ManagePlaylistsAsyncTask(Context context, action apiAction, Playlist playlist, String videoId, String max_id, OnPlaylistActionInterface onPlaylistActionInterface) { contextReference = new WeakReference<>(context); this.listener = onPlaylistActionInterface; 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 4ce798c55..67574f964 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveFeedsAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveFeedsAsyncTask.java @@ -32,7 +32,6 @@ import app.fedilab.android.client.Entities.Results; import app.fedilab.android.client.Entities.RetrieveFeedsParam; import app.fedilab.android.client.GNUAPI; import app.fedilab.android.client.PeertubeAPI; -import app.fedilab.android.fragments.DisplayStatusFragment; import app.fedilab.android.helper.FilterToots; import app.fedilab.android.interfaces.OnRetrieveFeedsInterface; import app.fedilab.android.sqlite.InstancesDAO; @@ -63,7 +62,6 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { private WeakReference contextReference; private FilterToots filterToots; private String instanceName, remoteInstance, name; - private boolean cached = false; private int timelineId; private String currentfilter; private String social; @@ -95,7 +93,6 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { } - public RetrieveFeedsAsyncTask(Context context, Type action, String instanceName, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface) { this.contextReference = new WeakReference<>(context); this.action = action; @@ -176,8 +173,6 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { } - - @Override protected Void doInBackground(Void... params) { API api = new API(this.contextReference.get()); @@ -257,7 +252,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { 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")) { apiResponse = api.getGNUTimeline(instanceName, max_id); diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveIdentityProofAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveIdentityProofAsyncTask.java index cacb7f568..983d2df83 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveIdentityProofAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveIdentityProofAsyncTask.java @@ -21,7 +21,6 @@ import java.lang.ref.WeakReference; import app.fedilab.android.client.API; import app.fedilab.android.client.APIResponse; - import app.fedilab.android.interfaces.OnRetrieveIdentityProofInterface; diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveMetaDataAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveMetaDataAsyncTask.java index 6b1db8298..da0305f64 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveMetaDataAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveMetaDataAsyncTask.java @@ -95,7 +95,7 @@ public class RetrieveMetaDataAsyncTask extends AsyncTask { Pattern descriptionPattern = Pattern.compile("meta[ a-zA-Z=\"'-]+property=[\"']og:description[\"']\\s+content=[\"']([^>]*)[\"']"); Pattern imagePattern = Pattern.compile("meta[ a-zA-Z=\"'-]+property=[\"']og:image[\"']\\s+content=[\"']([^>]*)[\"']"); try { - if( !potentialUrl.startsWith("http")){ + if (!potentialUrl.startsWith("http")) { potentialUrl = "https://" + potentialUrl; } URLConnection conn = new URL(potentialUrl).openConnection(); diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveRemoteDataAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveRemoteDataAsyncTask.java index 834a42644..4f39eb846 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveRemoteDataAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveRemoteDataAsyncTask.java @@ -42,13 +42,13 @@ public class RetrieveRemoteDataAsyncTask extends AsyncTask { private boolean developerAccount = false; - public RetrieveRemoteDataAsyncTask(Context context, OnRetrieveRemoteAccountInterface onRetrieveRemoteAccountInterface) { this.url = "https://toot.fedilab.app/@fedilab"; developerAccount = true; this.listener = onRetrieveRemoteAccountInterface; this.contextReference = new WeakReference<>(context); } + public RetrieveRemoteDataAsyncTask(Context context, String username, String instance, OnRetrieveRemoteAccountInterface onRetrieveRemoteAccountInterface) { this.url = Helper.instanceWithProtocol(context, instance) + "/@" + username; this.listener = onRetrieveRemoteAccountInterface; 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 5e518490f..c64699b64 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveSearchAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveSearchAsyncTask.java @@ -72,9 +72,9 @@ public class RetrieveSearchAsyncTask extends AsyncTask { @Override protected Void doInBackground(Void... params) { - if( query.compareTo("fedilab_trend") == 0 ) { + if (query.compareTo("fedilab_trend") == 0) { apiResponse = new API(this.contextReference.get()).getTrends(); - }else if (this.type == null) { + } else if (this.type == null) { if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { API api = new API(this.contextReference.get()); String[] split = query.trim().split("@"); diff --git a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveStoriesAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveStoriesAsyncTask.java index e574cf72c..14871e545 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/RetrieveStoriesAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/RetrieveStoriesAsyncTask.java @@ -16,7 +16,9 @@ package app.fedilab.android.asynctasks; import android.content.Context; import android.os.AsyncTask; + import java.lang.ref.WeakReference; + import app.fedilab.android.client.APIResponse; import app.fedilab.android.client.PixelfedAPI; import app.fedilab.android.interfaces.OnRetrieveStoriesInterface; @@ -36,11 +38,6 @@ public class RetrieveStoriesAsyncTask extends AsyncTask { private WeakReference contextReference; private type typeOfStory; - public enum type{ - ME, - FRIENDS - } - public RetrieveStoriesAsyncTask(Context context, String max_id, type typeOfStory, OnRetrieveStoriesInterface onRetrieveStoriesInterface) { this.contextReference = new WeakReference<>(context); this.max_id = max_id; @@ -48,13 +45,12 @@ public class RetrieveStoriesAsyncTask extends AsyncTask { this.typeOfStory = typeOfStory; } - @Override protected Void doInBackground(Void... params) { PixelfedAPI pixelfedAPI = new PixelfedAPI(this.contextReference.get()); - if( typeOfStory == type.FRIENDS) { + if (typeOfStory == type.FRIENDS) { apiResponse = pixelfedAPI.getFriendStories(max_id); - }else if (typeOfStory == type.ME){ + } else if (typeOfStory == type.ME) { apiResponse = pixelfedAPI.getMyStories(); } return null; @@ -65,4 +61,9 @@ public class RetrieveStoriesAsyncTask extends AsyncTask { listener.onRetrieveStories(apiResponse); } + public enum type { + ME, + FRIENDS + } + } diff --git a/app/src/main/java/app/fedilab/android/asynctasks/SyncBookmarksAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/SyncBookmarksAsyncTask.java index 27fcb5084..ce237e0f3 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/SyncBookmarksAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/SyncBookmarksAsyncTask.java @@ -40,6 +40,7 @@ public class SyncBookmarksAsyncTask extends AsyncTask { private OnSyncBookmarksInterface listener; private WeakReference contextReference; private sync type; + public SyncBookmarksAsyncTask(Context context, sync type, OnSyncBookmarksInterface onSyncBookmarksInterface) { this.contextReference = new WeakReference<>(context); this.type = type; 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 e575fdf5b..7c3a74618 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/UpdateAccountInfoByIDAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/UpdateAccountInfoByIDAsyncTask.java @@ -86,7 +86,7 @@ public class UpdateAccountInfoByIDAsyncTask extends AsyncTask if (response != null && response.getEmojis() != null && response.getEmojis().size() > 0) { new CustomEmojiDAO(contextReference.get(), db).removeAll(); for (Emojis emojis : response.getEmojis()) { - if( emojis.isVisible_in_picker()) { + if (emojis.isVisible_in_picker()) { new CustomEmojiDAO(contextReference.get(), db).insertEmoji(emojis); } } 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 878843f08..e3d7367fd 100644 --- a/app/src/main/java/app/fedilab/android/client/API.java +++ b/app/src/main/java/app/fedilab/android/client/API.java @@ -20,7 +20,6 @@ import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; - import androidx.localbroadcastmanager.content.LocalBroadcastManager; import com.google.gson.JsonArray; @@ -360,7 +359,7 @@ public class API { } ArrayList resolutions = new ArrayList<>(); - if( resobj.has("streamingPlaylists") && resobj.getJSONArray("streamingPlaylists").length() > 0){ + if (resobj.has("streamingPlaylists") && resobj.getJSONArray("streamingPlaylists").length() > 0) { JSONArray files = resobj.getJSONArray("streamingPlaylists").getJSONObject(0).getJSONArray("files"); for (int j = 0; j < files.length(); j++) { @@ -369,7 +368,7 @@ public class API { } peertube.setResolution(resolutions); peertube.setStreamService(true); - }else { + } else { JSONArray files = resobj.getJSONArray("files"); for (int j = 0; j < files.length(); j++) { @@ -546,9 +545,9 @@ public class API { poll.setExpired(resobj.getBoolean("expired")); poll.setMultiple(resobj.getBoolean("multiple")); poll.setVotes_count(resobj.getInt("votes_count")); - if( resobj.has("voters_count")){ + if (resobj.has("voters_count")) { poll.setVoters_count(resobj.getInt("voters_count")); - }else{ + } else { poll.setVoters_count(resobj.getInt("votes_count")); } poll.setVoted(resobj.getBoolean("voted")); @@ -579,14 +578,14 @@ public class API { Status status = new Status(); try { status.setId(resobj.get("id").toString()); - if( resobj.has("uri")) { + if (resobj.has("uri")) { status.setUri(resobj.get("uri").toString()); - }else { + } else { status.setUri(resobj.get("id").toString()); } - if( resobj.has("created_at")) { + if (resobj.has("created_at")) { status.setCreated_at(Helper.mstStringToDate(context, resobj.get("created_at").toString())); - }else{ + } else { status.setCreated_at(new Date()); } status.setIn_reply_to_id(resobj.get("in_reply_to_id").toString()); @@ -606,7 +605,7 @@ public class API { status.setUrl(resobj.get("url").toString()); ArrayList attachments = new ArrayList<>(); //Retrieves attachments - if( resobj.has("media_attachments")) { + if (resobj.has("media_attachments")) { JSONArray arrayAttachement = resobj.getJSONArray("media_attachments"); if (arrayAttachement != null) { @@ -743,9 +742,9 @@ public class API { poll.setExpired(resobj.getJSONObject("poll").getBoolean("expired")); poll.setMultiple(resobj.getJSONObject("poll").getBoolean("multiple")); poll.setVotes_count(resobj.getJSONObject("poll").getInt("votes_count")); - if( resobj.getJSONObject("poll").has("voters_count") && !resobj.getJSONObject("poll").isNull("voters_count")){ + if (resobj.getJSONObject("poll").has("voters_count") && !resobj.getJSONObject("poll").isNull("voters_count")) { poll.setVoters_count(resobj.getJSONObject("poll").getInt("voters_count")); - }else{ + } else { poll.setVoters_count(resobj.getJSONObject("poll").getInt("votes_count")); } poll.setVoted(resobj.getJSONObject("poll").getBoolean("voted")); @@ -795,159 +794,6 @@ public class API { return status; } - - /** - * Parse xml response for Nitter - * - * @param xml String - * @return List - */ - - private List parseNitter(String xml) { - final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - String nitterHost = sharedpreferences.getString(Helper.SET_NITTER_HOST, Helper.DEFAULT_NITTER_HOST).toLowerCase(); - - List statuses = new ArrayList<>(); - try { - XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); - factory.setNamespaceAware(true); - XmlPullParser xpp = factory.newPullParser(); - - xpp.setInput( new StringReader( xml ) ); - int eventType = xpp.getEventType(); - Account account = null; - Status status = null; - HashMap mappedProfile = new HashMap<>(); - while (eventType != XmlPullParser.END_DOCUMENT) { - - if(eventType == XmlPullParser.START_TAG) { - if( xpp.getName().compareTo("item") == 0 ){ - status = new Status(); - status.setReplies_count(0); - status.setFavourites_count(0); - status.setReblogs_count(0); - status.setFavourited(false); - status.setReblogged(false); - status.setEmojiFound(true); - status.setPollEmojiFound(true); - status.setEmojiTranslateFound(true); - status.setMedia_attachments(new ArrayList<>()); - account = new Account(); - }else if( xpp.getName().compareTo("creator") == 0 ){ - eventType = xpp.next(); - if(eventType == XmlPullParser.TEXT) { - if( account != null ){ - account.setAcct(xpp.getText().replace("@","")+"@" + nitterHost); - account.setDisplay_name(xpp.getText().replace("@","")); - account.setUsername(xpp.getText().replace("@","")); - account.setId("https://" + nitterHost + "/" + xpp.getText()); - account.setUuid("https://" + nitterHost + "/" + xpp.getText()); - account.setUrl("https://" + nitterHost + "/" + xpp.getText()); - if( !mappedProfile.containsKey(xpp.getText()) ){ - HttpsConnection httpsConnection = new HttpsConnection(context, nitterHost); - try { - String response = httpsConnection.get("https://" + nitterHost + "/" + xpp.getText() + "/rss", 10, null, null); - XmlPullParserFactory factory2 = XmlPullParserFactory.newInstance(); - factory2.setNamespaceAware(true); - XmlPullParser xpp2 = factory2.newPullParser(); - - xpp2.setInput( new StringReader( response ) ); - int eventType2 = xpp2.getEventType(); - while (eventType2 != XmlPullParser.END_DOCUMENT) { - if (eventType2 == XmlPullParser.START_TAG) { - if (xpp2.getName().compareTo("url") == 0) { - eventType2 = xpp2.next(); - if(eventType2 == XmlPullParser.TEXT ) { - mappedProfile.put(xpp.getText(), xpp2.getText()); - } - break; - } - } - eventType2 = xpp2.next(); - } - } catch (NoSuchAlgorithmException | KeyManagementException | HttpsConnection.HttpsConnectionException e) { - e.printStackTrace(); - } - } - account.setAvatar(mappedProfile.get(xpp.getText())); - } - } - } else if( xpp.getName().compareTo("pubDate") == 0 ){ - eventType = xpp.next(); - if(eventType == XmlPullParser.TEXT && status != null) { - if( xpp.getText() != null ) { - try { - DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); - Date date = formatter.parse(xpp.getText()); - status.setCreated_at(date); - } catch (ParseException e) { - status.setCreated_at(new Date()); - } - } - } - }else if( xpp.getName().compareTo("description") == 0 ){ - eventType = xpp.next(); - if(eventType == XmlPullParser.TEXT && status != null) { - if( xpp.getText() != null ) { - String description = xpp.getText(); - Pattern imgPattern = Pattern.compile("]*src=\"([^\"]+)\"[^>]*>"); - Matcher matcher = imgPattern.matcher(description); - List imgs = new ArrayList<>(); - int i = 1; - ArrayList attachments = new ArrayList<>(); - while (matcher.find()) { - description = description.replaceAll(Pattern.quote(matcher.group()), ""); - imgs.add("[media_" + i + "]|" + matcher.group(1)); - Attachment attachment = new Attachment(); - attachment.setType("image"); - attachment.setDescription(""); - attachment.setUrl(matcher.group(1)); - attachment.setPreview_url(matcher.group(1)); - attachment.setId(matcher.group(1)); - attachments.add(attachment); - } - status.setMedia_attachments(attachments); - status.setContent(context, description); - } - } - }else if( xpp.getName().compareTo("guid") == 0 ){ - eventType = xpp.next(); - if(eventType == XmlPullParser.TEXT && status != null) { - if( xpp.getText() != null ) { - status.setUri(xpp.getText()); - Pattern idPattern = Pattern.compile("([0-9])+"); - Matcher matcher = idPattern.matcher(xpp.getText()); - while (matcher.find()) { - status.setId(matcher.group(0)); - } - } - } - }else if( xpp.getName().compareTo("link") == 0 ){ - eventType = xpp.next(); - if(eventType == XmlPullParser.TEXT && status != null) { - if( xpp.getText() != null ) { - status.setUrl(xpp.getText()); - } - } - } - } else if(eventType == XmlPullParser.END_TAG) { - if( xpp.getName().compareTo("item") == 0 ){ - if (status != null) { - status.setAccount(account); - statuses.add(status); - } - account = null; - status = null; - } - } - eventType = xpp.next(); - } - } catch (XmlPullParserException | IOException e) { - e.printStackTrace(); - } - return statuses; - } - /** * Parse json response for several notes (Misskey) * @@ -1394,19 +1240,19 @@ public class API { } else { account.setCreated_at(new Date()); } - if( !resobj.isNull("followers_count")) { + if (!resobj.isNull("followers_count")) { account.setFollowers_count(Integer.valueOf(resobj.get("followers_count").toString())); - }else{ + } else { account.setFollowers_count(0); } - if( !resobj.isNull("following_count")) { + if (!resobj.isNull("following_count")) { account.setFollowing_count(Integer.valueOf(resobj.get("following_count").toString())); - }else{ + } else { account.setFollowing_count(0); } - if( !resobj.isNull("statuses_count")) { + if (!resobj.isNull("statuses_count")) { account.setStatuses_count(Integer.valueOf(resobj.get("statuses_count").toString())); - }else{ + } else { account.setStatuses_count(0); } account.setNote(resobj.get("note").toString()); @@ -1501,41 +1347,6 @@ public class API { return account; } - private List parseIdentityProof(Context context, JSONArray jsonArray) { - List identityProofs = new ArrayList<>(); - try { - int i = 0; - while (i < jsonArray.length()) { - - JSONObject resobj = jsonArray.getJSONObject(i); - IdentityProof identityProof = parseIdentityProof(context, resobj); - i++; - if (identityProof != null) { - identityProofs.add(identityProof); - } - } - - } catch (JSONException e) { - e.printStackTrace(); - } - return identityProofs; - } - - private IdentityProof parseIdentityProof(Context context, JSONObject jsonObject) { - IdentityProof identityProof = new IdentityProof(); - try { - identityProof.setProfile_url(jsonObject.getString("profile_url")); - identityProof.setProof_url(jsonObject.getString("proof_url")); - identityProof.setProvider(jsonObject.getString("provider")); - identityProof.setProvider_username(jsonObject.getString("provider_username")); - identityProof.setUpdated_at(Helper.mstStringToDate(context, jsonObject.getString("updated_at"))); - - } catch (JSONException | ParseException e) { - e.printStackTrace(); - } - return identityProof; - } - /** * Parse json response an unique account * @@ -1719,6 +1530,193 @@ public class API { return notification; } + /** + * Parse xml response for Nitter + * + * @param xml String + * @return List + */ + + private List parseNitter(String xml) { + final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + String nitterHost = sharedpreferences.getString(Helper.SET_NITTER_HOST, Helper.DEFAULT_NITTER_HOST).toLowerCase(); + + List statuses = new ArrayList<>(); + try { + XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); + factory.setNamespaceAware(true); + XmlPullParser xpp = factory.newPullParser(); + + xpp.setInput(new StringReader(xml)); + int eventType = xpp.getEventType(); + Account account = null; + Status status = null; + HashMap mappedProfile = new HashMap<>(); + while (eventType != XmlPullParser.END_DOCUMENT) { + + if (eventType == XmlPullParser.START_TAG) { + if (xpp.getName().compareTo("item") == 0) { + status = new Status(); + status.setReplies_count(0); + status.setFavourites_count(0); + status.setReblogs_count(0); + status.setFavourited(false); + status.setReblogged(false); + status.setEmojiFound(true); + status.setPollEmojiFound(true); + status.setEmojiTranslateFound(true); + status.setMedia_attachments(new ArrayList<>()); + account = new Account(); + } else if (xpp.getName().compareTo("creator") == 0) { + eventType = xpp.next(); + if (eventType == XmlPullParser.TEXT) { + if (account != null) { + account.setAcct(xpp.getText().replace("@", "") + "@" + nitterHost); + account.setDisplay_name(xpp.getText().replace("@", "")); + account.setUsername(xpp.getText().replace("@", "")); + account.setId("https://" + nitterHost + "/" + xpp.getText()); + account.setUuid("https://" + nitterHost + "/" + xpp.getText()); + account.setUrl("https://" + nitterHost + "/" + xpp.getText()); + if (!mappedProfile.containsKey(xpp.getText())) { + HttpsConnection httpsConnection = new HttpsConnection(context, nitterHost); + try { + String response = httpsConnection.get("https://" + nitterHost + "/" + xpp.getText() + "/rss", 10, null, null); + XmlPullParserFactory factory2 = XmlPullParserFactory.newInstance(); + factory2.setNamespaceAware(true); + XmlPullParser xpp2 = factory2.newPullParser(); + + xpp2.setInput(new StringReader(response)); + int eventType2 = xpp2.getEventType(); + while (eventType2 != XmlPullParser.END_DOCUMENT) { + if (eventType2 == XmlPullParser.START_TAG) { + if (xpp2.getName().compareTo("url") == 0) { + eventType2 = xpp2.next(); + if (eventType2 == XmlPullParser.TEXT) { + mappedProfile.put(xpp.getText(), xpp2.getText()); + } + break; + } + } + eventType2 = xpp2.next(); + } + } catch (NoSuchAlgorithmException | KeyManagementException | HttpsConnection.HttpsConnectionException e) { + e.printStackTrace(); + } + } + account.setAvatar(mappedProfile.get(xpp.getText())); + } + } + } else if (xpp.getName().compareTo("pubDate") == 0) { + eventType = xpp.next(); + if (eventType == XmlPullParser.TEXT && status != null) { + if (xpp.getText() != null) { + try { + DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); + Date date = formatter.parse(xpp.getText()); + status.setCreated_at(date); + } catch (ParseException e) { + status.setCreated_at(new Date()); + } + } + } + } else if (xpp.getName().compareTo("description") == 0) { + eventType = xpp.next(); + if (eventType == XmlPullParser.TEXT && status != null) { + if (xpp.getText() != null) { + String description = xpp.getText(); + Pattern imgPattern = Pattern.compile("]*src=\"([^\"]+)\"[^>]*>"); + Matcher matcher = imgPattern.matcher(description); + List imgs = new ArrayList<>(); + int i = 1; + ArrayList attachments = new ArrayList<>(); + while (matcher.find()) { + description = description.replaceAll(Pattern.quote(matcher.group()), ""); + imgs.add("[media_" + i + "]|" + matcher.group(1)); + Attachment attachment = new Attachment(); + attachment.setType("image"); + attachment.setDescription(""); + attachment.setUrl(matcher.group(1)); + attachment.setPreview_url(matcher.group(1)); + attachment.setId(matcher.group(1)); + attachments.add(attachment); + } + status.setMedia_attachments(attachments); + status.setContent(context, description); + } + } + } else if (xpp.getName().compareTo("guid") == 0) { + eventType = xpp.next(); + if (eventType == XmlPullParser.TEXT && status != null) { + if (xpp.getText() != null) { + status.setUri(xpp.getText()); + Pattern idPattern = Pattern.compile("([0-9])+"); + Matcher matcher = idPattern.matcher(xpp.getText()); + while (matcher.find()) { + status.setId(matcher.group(0)); + } + } + } + } else if (xpp.getName().compareTo("link") == 0) { + eventType = xpp.next(); + if (eventType == XmlPullParser.TEXT && status != null) { + if (xpp.getText() != null) { + status.setUrl(xpp.getText()); + } + } + } + } else if (eventType == XmlPullParser.END_TAG) { + if (xpp.getName().compareTo("item") == 0) { + if (status != null) { + status.setAccount(account); + statuses.add(status); + } + account = null; + status = null; + } + } + eventType = xpp.next(); + } + } catch (XmlPullParserException | IOException e) { + e.printStackTrace(); + } + return statuses; + } + + private List parseIdentityProof(Context context, JSONArray jsonArray) { + List identityProofs = new ArrayList<>(); + try { + int i = 0; + while (i < jsonArray.length()) { + + JSONObject resobj = jsonArray.getJSONObject(i); + IdentityProof identityProof = parseIdentityProof(context, resobj); + i++; + if (identityProof != null) { + identityProofs.add(identityProof); + } + } + + } catch (JSONException e) { + e.printStackTrace(); + } + return identityProofs; + } + + private IdentityProof parseIdentityProof(Context context, JSONObject jsonObject) { + IdentityProof identityProof = new IdentityProof(); + try { + identityProof.setProfile_url(jsonObject.getString("profile_url")); + identityProof.setProof_url(jsonObject.getString("proof_url")); + identityProof.setProvider(jsonObject.getString("provider")); + identityProof.setProvider_username(jsonObject.getString("provider_username")); + identityProof.setUpdated_at(Helper.mstStringToDate(context, jsonObject.getString("updated_at"))); + + } catch (JSONException | ParseException e) { + e.printStackTrace(); + } + return identityProof; + } + /** * Execute admin get actions * @@ -2080,11 +2078,11 @@ public class API { String response; InstanceNodeInfo instanceNodeInfo = new InstanceNodeInfo(); - if( domain.startsWith("http://")){ - domain = domain.replace("http://",""); + if (domain.startsWith("http://")) { + domain = domain.replace("http://", ""); } - if( domain.startsWith("https://")){ - domain = domain.replace("https://",""); + if (domain.startsWith("https://")) { + domain = domain.replace("https://", ""); } try { response = new HttpsConnection(context, domain).get("https://" + domain + "/.well-known/nodeinfo", 30, null, null); @@ -2129,7 +2127,7 @@ public class API { } catch (NoSuchAlgorithmException | JSONException | KeyManagementException e1) { e1.printStackTrace(); } catch (HttpsConnection.HttpsConnectionException e1) { - if (e1.getStatusCode() == 404 || e1.getStatusCode() == 501 ) { + if (e1.getStatusCode() == 404 || e1.getStatusCode() == 501) { instanceNodeInfo.setName("GNU"); instanceNodeInfo.setVersion("unknown"); instanceNodeInfo.setOpenRegistrations(true); @@ -2153,7 +2151,7 @@ public class API { } catch (NoSuchAlgorithmException | JSONException | KeyManagementException e1) { e1.printStackTrace(); } catch (HttpsConnection.HttpsConnectionException e1) { - if (e1.getStatusCode() == 404|| e1.getStatusCode() == 501) { + if (e1.getStatusCode() == 404 || e1.getStatusCode() == 501) { instanceNodeInfo.setName("GNU"); instanceNodeInfo.setVersion("unknown"); instanceNodeInfo.setOpenRegistrations(true); @@ -2170,8 +2168,6 @@ public class API { } - - public InstanceNodeInfo instanceInfo(String domain) { String response; @@ -2202,7 +2198,7 @@ public class API { instanceNodeInfo.setName(name); instanceNodeInfo.setVersion(jsonObject.getString("version")); instanceNodeInfo.setOpenRegistrations(resobj.getBoolean("openRegistrations")); - if (name.trim().toUpperCase().compareTo("MASTODON") == 0 || name.trim().toUpperCase().compareTo("PLEROMA") == 0 || name.trim().toUpperCase().compareTo("PIXELFED") == 0){ + if (name.trim().toUpperCase().compareTo("MASTODON") == 0 || name.trim().toUpperCase().compareTo("PLEROMA") == 0 || name.trim().toUpperCase().compareTo("PIXELFED") == 0) { APIResponse apiResponse = getInstance(domain); Instance instanceNode = apiResponse.getInstance(); instanceNodeInfo.setNodeDescription(instanceNode.getDescription()); @@ -2214,27 +2210,27 @@ public class API { instanceNodeInfo.setThumbnail(instanceNode.getThumbnail()); instanceNodeInfo.setVersion(instanceNode.getVersion()); } - if( resobj.has("metadata")){ + if (resobj.has("metadata")) { JSONObject metadata = resobj.getJSONObject("metadata"); - if( metadata.has("staffAccounts")){ + if (metadata.has("staffAccounts")) { instanceNodeInfo.setStaffAccountStr(metadata.getString("staffAccounts")); } - if( metadata.has("nodeName")){ + if (metadata.has("nodeName")) { instanceNodeInfo.setNodeName(metadata.getString("nodeName")); } } - if( resobj.has("usage")){ + if (resobj.has("usage")) { JSONObject usage = resobj.getJSONObject("usage"); - if( usage.has("users") && usage.getJSONObject("users").has("total")){ + if (usage.has("users") && usage.getJSONObject("users").has("total")) { instanceNodeInfo.setNumberOfUsers(usage.getJSONObject("users").getInt("total")); } - if( usage.has("localPosts") ){ + if (usage.has("localPosts")) { instanceNodeInfo.setNumberOfPosts(usage.getInt("localPosts")); } } - if( instanceNodeInfo.getStaffAccountStr() != null && instanceNodeInfo.getStaffAccount() == null){ + if (instanceNodeInfo.getStaffAccountStr() != null && instanceNodeInfo.getStaffAccount() == null) { APIResponse search = searchAccounts(instanceNodeInfo.getStaffAccountStr(), 1); - if( search != null && search.getAccounts() != null && search.getAccounts().size() > 0 ){ + if (search != null && search.getAccounts() != null && search.getAccounts().size() > 0) { instanceNodeInfo.setStaffAccount(search.getAccounts().get(0)); } } @@ -2244,7 +2240,7 @@ public class API { } } catch (IOException | JSONException | NoSuchAlgorithmException | KeyManagementException e) { e.printStackTrace(); - } catch (HttpsConnection.HttpsConnectionException e){ + } catch (HttpsConnection.HttpsConnectionException e) { APIResponse apiResponse = getInstance(domain); instanceNodeInfo = new InstanceNodeInfo(); instanceNodeInfo.setName("MASTODON"); @@ -2267,7 +2263,7 @@ public class API { */ public APIResponse getInstance(String instance) { try { - String response = new HttpsConnection(context, this.instance).get("https://"+instance+"/api/v1/instance", 30, null, prefKeyOauthTokenT); + String response = new HttpsConnection(context, this.instance).get("https://" + instance + "/api/v1/instance", 30, null, prefKeyOauthTokenT); Instance instanceEntity = parseInstance(new JSONObject(response)); apiResponse.setInstance(instanceEntity); } catch (HttpsConnection.HttpsConnectionException e) { @@ -2577,7 +2573,7 @@ public class API { List relationships; Relationship relationship = null; HashMap params = new HashMap<>(); - if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) params.put("id[]", accountId); else params.put("id", accountId); @@ -3153,11 +3149,11 @@ public class API { } else { statuses = parseStatuses(context, new JSONArray(response)); } - } catch (UnknownHostException e){ - if (since_id == null){ + } catch (UnknownHostException e) { + if (since_id == null) { getHomeTimelineCache(max_id); } - } catch(HttpsConnection.HttpsConnectionException e) { + } catch (HttpsConnection.HttpsConnectionException e) { setError(e.getStatusCode(), e); } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { e.printStackTrace(); @@ -3169,9 +3165,9 @@ public class API { } /** - *Get identy proof for an account *synchronously* + * Get identy proof for an account *synchronously* * - * @param userId user_id String + * @param userId user_id String * @return APIResponse */ public APIResponse getIdentityProof(String userId) { @@ -3181,8 +3177,8 @@ public class API { String response = httpsConnection.get(getAbsoluteUrl(String.format("/accounts/%s/identity_proofs", userId)), 10, null, prefKeyOauthTokenT); identityProofs = parseIdentityProof(context, new JSONArray(response)); - } catch (UnknownHostException e){ - } catch(HttpsConnection.HttpsConnectionException e) { + } catch (UnknownHostException e) { + } catch (HttpsConnection.HttpsConnectionException e) { setError(e.getStatusCode(), e); } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { e.printStackTrace(); @@ -3194,7 +3190,6 @@ public class API { } - /** * Retrieves public GNU timeline for the account *synchronously* * @@ -3344,12 +3339,12 @@ public class API { try { HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); String response = httpsConnection.get("https://" + instance + "/api/v1/videos", 10, params, null); - if( response == null) { + if (response == null) { apiResponse.setPeertubes(peertubes); return apiResponse; } JSONObject jsonObject = new JSONObject(response); - if( jsonObject.has("data")) { + if (jsonObject.has("data")) { JSONArray jsonArray = new JSONObject(response).getJSONArray("data"); peertubes = parsePeertube(instance, jsonArray); } @@ -3494,7 +3489,7 @@ public class API { final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String nitterHost = sharedpreferences.getString(Helper.SET_NITTER_HOST, Helper.DEFAULT_NITTER_HOST).toLowerCase(); String[] usernames = instance.split(" "); - if( usernames.length == 0 ){ + if (usernames.length == 0) { Error error = new Error(); error.setError(context.getString(R.string.toast_error)); error.setStatusCode(404); @@ -3502,12 +3497,12 @@ public class API { return apiResponse; } StringBuilder urlparams = new StringBuilder(); - for(String param: usernames){ + for (String param : usernames) { urlparams.append(param.trim()).append(","); } String url = "https://" + nitterHost + "/" + urlparams + "/rss"; - if( max_id != null ){ + if (max_id != null) { url += "?max_position=" + max_id; } try { @@ -5921,9 +5916,9 @@ public class API { trend.setName(resobj.getString("name")); trend.setUrl(resobj.getString("url")); List historyList = new ArrayList<>(); - if( resobj.has("history")) { + if (resobj.has("history")) { JSONArray histories = resobj.getJSONArray("history"); - for(int i = 0 ; i < histories.length() ; i++ ) { + for (int i = 0; i < histories.length(); i++) { JSONObject hystory = histories.getJSONObject(i); TrendsHistory trendsHistory = new TrendsHistory(); trendsHistory.setDays(hystory.getLong("day")); @@ -5939,7 +5934,6 @@ public class API { } - /** * Parse json response for several conversations * @@ -6048,22 +6042,22 @@ public class API { poll_limits.put("max_expiration", polllimits.getInt("max_expiration")); instance.setPoll_limits(poll_limits); } - if( resobj.has("thumbnail")){ + if (resobj.has("thumbnail")) { instance.setThumbnail(resobj.getString("thumbnail")); } - if( resobj.has("stats")){ + if (resobj.has("stats")) { JSONObject stats = resobj.getJSONObject("stats"); - if( stats.has("user_count")) { + if (stats.has("user_count")) { instance.setUserCount(stats.getInt("user_count")); } - if( stats.has("status_count")) { + if (stats.has("status_count")) { instance.setStatusCount(stats.getInt("status_count")); } - if( stats.has("domain_count")) { + if (stats.has("domain_count")) { instance.setDomainCount(stats.getInt("domain_count")); } } - if( resobj.has("contact_account")){ + if (resobj.has("contact_account")) { instance.setContactAccount(parseAccountResponse(context, resobj.getJSONObject("contact_account"))); } } catch (JSONException e) { 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 3aa6f080f..9e3d23396 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 @@ -24,6 +24,17 @@ import android.os.Parcelable; public class Attachment implements Parcelable { + public static final Creator CREATOR = new Creator() { + @Override + public Attachment createFromParcel(Parcel source) { + return new Attachment(source); + } + + @Override + public Attachment[] newArray(int size) { + return new Attachment[size]; + } + }; private String id; private String type; private String url; @@ -38,6 +49,18 @@ public class Attachment implements Parcelable { } + protected Attachment(Parcel in) { + this.id = in.readString(); + this.type = in.readString(); + this.url = in.readString(); + this.remote_url = in.readString(); + this.preview_url = in.readString(); + this.meta = in.readString(); + this.text_url = in.readString(); + this.description = in.readString(); + this.local_path = in.readString(); + } + public String getId() { return id; } @@ -127,28 +150,4 @@ public class Attachment implements Parcelable { dest.writeString(this.description); dest.writeString(this.local_path); } - - protected Attachment(Parcel in) { - this.id = in.readString(); - this.type = in.readString(); - this.url = in.readString(); - this.remote_url = in.readString(); - this.preview_url = in.readString(); - this.meta = in.readString(); - this.text_url = in.readString(); - this.description = in.readString(); - this.local_path = in.readString(); - } - - public static final Creator CREATOR = new Creator() { - @Override - public Attachment createFromParcel(Parcel source) { - return new Attachment(source); - } - - @Override - public Attachment[] newArray(int size) { - return new Attachment[size]; - } - }; } 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 fb5bebc8f..fda8728e5 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 @@ -60,7 +60,6 @@ import app.fedilab.android.sqlite.TimelinesDAO; import es.dmoral.toasty.Toasty; import static app.fedilab.android.activities.BaseMainActivity.mPageReferenceMap; -import static app.fedilab.android.activities.BaseMainActivity.regex_home; import static app.fedilab.android.sqlite.Sqlite.DB_NAME; @@ -282,13 +281,13 @@ public class ManageTimelines { icon = tb.getCustomView().findViewById(R.id.tab_icon); } - Helper.changeDrawableColor(context,R.drawable.ic_home, R.attr.iconColorMenu); - Helper.changeDrawableColor(context,R.drawable.ic_notifications, R.attr.iconColorMenu); - Helper.changeDrawableColor(context,R.drawable.ic_direct_messages, R.attr.iconColorMenu); - Helper.changeDrawableColor(context,R.drawable.ic_people, R.attr.iconColorMenu); - Helper.changeDrawableColor(context,R.drawable.ic_public, R.attr.iconColorMenu); - Helper.changeDrawableColor(context,R.drawable.ic_color_lens, R.attr.iconColorMenu); - Helper.changeDrawableColor(context,R.drawable.ic_video_peertube, R.attr.iconColorMenu); + Helper.changeDrawableColor(context, R.drawable.ic_home, R.attr.iconColorMenu); + Helper.changeDrawableColor(context, R.drawable.ic_notifications, R.attr.iconColorMenu); + Helper.changeDrawableColor(context, R.drawable.ic_direct_messages, R.attr.iconColorMenu); + Helper.changeDrawableColor(context, R.drawable.ic_people, R.attr.iconColorMenu); + Helper.changeDrawableColor(context, R.drawable.ic_public, R.attr.iconColorMenu); + Helper.changeDrawableColor(context, R.drawable.ic_color_lens, R.attr.iconColorMenu); + Helper.changeDrawableColor(context, R.drawable.ic_video_peertube, R.attr.iconColorMenu); if (icon != null) { switch (tl.getType()) { case HOME: 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 281f84fa5..af36bde2d 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 @@ -246,7 +246,8 @@ public class Notification implements Parcelable { contentSpan.setSpan( imageSpan, startPosition, endPosition, Spannable.SPAN_INCLUSIVE_EXCLUSIVE); - }catch (Exception ignored){} + } catch (Exception ignored) { + } } } } 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 1d81565ec..26ac125ff 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 @@ -21,8 +21,6 @@ import java.util.Date; import java.util.HashMap; import java.util.List; -import app.fedilab.android.helper.Helper; - /** * Created by Thomas on 29/09/2018. * Manage how to videos @@ -183,9 +181,9 @@ public class Peertube { resolution = this.getResolution().get(0); if (resolution == null) return null; - if( streamService) { + if (streamService) { return "https://" + this.host + "/static/streaming-playlists/hls/" + getUuid() + "/" + getUuid() + "-" + resolution + "-fragmented.mp4"; - }else{ + } else { return "https://" + this.host + "/static/webseed/" + getUuid() + "-" + resolution + ".mp4"; } @@ -215,9 +213,9 @@ public class Peertube { resolution = this.getResolution().get(0); if (resolution == null) return null; - if( streamService) { + if (streamService) { return "https://" + this.host + "/download/streaming-playlists/hls/videos/" + getUuid() + "/" + getUuid() + "-" + resolution + "-fragmented.mp4"; - }else{ + } else { return "https://" + this.host + "/download/videos/" + getUuid() + "-" + resolution + ".mp4"; } diff --git a/app/src/main/java/app/fedilab/android/client/Entities/PollOptions.java b/app/src/main/java/app/fedilab/android/client/Entities/PollOptions.java index 0df16b415..1f03e5904 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/PollOptions.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/PollOptions.java @@ -38,6 +38,7 @@ public class PollOptions implements Parcelable { public PollOptions() { } + protected PollOptions(Parcel in) { this.title = in.readString(); this.votes_count = in.readInt(); 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 8cffb9f73..3b1bce3b4 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 @@ -65,8 +65,6 @@ import com.github.penfeizhou.animation.apng.decode.APNGParser; import com.github.penfeizhou.animation.gif.GifDrawable; import com.github.penfeizhou.animation.gif.decode.GifParser; -import net.gotev.uploadservice.http.HttpConnection; - import java.io.File; import java.net.URI; import java.net.URISyntaxException; @@ -81,7 +79,6 @@ import java.util.regex.Pattern; import app.fedilab.android.R; import app.fedilab.android.activities.BaseActivity; -import app.fedilab.android.activities.BaseMainActivity; import app.fedilab.android.activities.GroupActivity; import app.fedilab.android.activities.HashTagActivity; import app.fedilab.android.activities.MainActivity; @@ -90,24 +87,19 @@ import app.fedilab.android.activities.ShowAccountActivity; import app.fedilab.android.asynctasks.RetrieveFeedsAsyncTask; import app.fedilab.android.asynctasks.UpdateAccountInfoAsyncTask; import app.fedilab.android.client.HttpsConnection; -import app.fedilab.android.fragments.TabLayoutNotificationsFragment; import app.fedilab.android.helper.CrossActions; import app.fedilab.android.helper.CustomQuoteSpan; import app.fedilab.android.helper.Helper; -import app.fedilab.android.helper.LongClickLinkMovementMethod; import app.fedilab.android.helper.LongClickableSpan; import app.fedilab.android.helper.ThemeHelper; import app.fedilab.android.interfaces.OnRetrieveEmojiInterface; import app.fedilab.android.interfaces.OnRetrieveImageInterface; -import app.fedilab.android.sqlite.StatusStoredDAO; import es.dmoral.toasty.Toasty; import static android.content.Context.MODE_PRIVATE; -import static app.fedilab.android.activities.BaseMainActivity.mPageReferenceMap; import static app.fedilab.android.drawers.StatusListAdapter.COMPACT_STATUS; import static app.fedilab.android.drawers.StatusListAdapter.CONSOLE_STATUS; import static app.fedilab.android.drawers.StatusListAdapter.DISPLAYED_STATUS; -import static app.fedilab.android.helper.Helper.THEME_BLACK; import static app.fedilab.android.helper.Helper.drawableToBitmap; /** @@ -463,7 +455,7 @@ public class Status implements Parcelable { uri = new URI(url); instance = uri.getHost(); } catch (URISyntaxException e) { - if( url.contains("|")) { + if (url.contains("|")) { try { uri = new URI(url.split("\\|")[0]); instance = uri.getHost(); @@ -482,7 +474,7 @@ public class Status implements Parcelable { account.setInstance(instance); account.setUrl(url); String accountId = null; - if( mentions != null) { + if (mentions != null) { for (Mention mention : mentions) { String[] accountMentionAcct = mention.getAcct().split("@"); //Different isntance @@ -632,187 +624,186 @@ public class Status implements Parcelable { if (endPosition <= spannableStringT.toString().length() && endPosition >= startPosition) { - spannableStringT.setSpan(new LongClickableSpan() { - @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.toLowerCase().startsWith("http://") && !url.toLowerCase().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.toLowerCase().startsWith("http://") && !url.toLowerCase().startsWith("https://")) - finalUrl = "http://" + url; - Helper.openBrowser(context, finalUrl); + @Override + public void onLongClick(@NonNull View textView) { + PopupMenu popup = new PopupMenu(context, textView); + popup.getMenuInflater() + .inflate(R.menu.links_popup, popup.getMenu()); + 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; + } + popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { + public boolean onMenuItemClick(MenuItem item) { + switch (item.getItemId()) { + case R.id.action_show_link: + int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); + + AlertDialog.Builder builder = new AlertDialog.Builder(context, style); + builder.setMessage(url); + builder.setTitle(context.getString(R.string.display_full_link)); + builder.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + } + }) + .show(); + break; + case R.id.action_share_link: + Intent sendIntent = new Intent(Intent.ACTION_SEND); + sendIntent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.shared_via)); + sendIntent.putExtra(Intent.EXTRA_TEXT, url); + sendIntent.setType("text/plain"); + context.startActivity(Intent.createChooser(sendIntent, context.getString(R.string.share_with))); + break; + + case R.id.action_open_other_app: + 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(); + } + break; + case R.id.action_copy_link: + ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); + ClipData clip = ClipData.newPlainText(Helper.CLIP_BOARD, url); + if (clipboard != null) { + clipboard.setPrimaryClip(clip); + Toasty.info(context, context.getString(R.string.clipboard_url), Toast.LENGTH_LONG).show(); + } + break; + case R.id.action_unshorten: + Thread thread = new Thread() { + @Override + public void run() { + String response = new HttpsConnection(context, null).checkUrl(url); + + Handler mainHandler = new Handler(context.getMainLooper()); + + Runnable myRunnable = new Runnable() { + @Override + public void run() { + AlertDialog.Builder builder = new AlertDialog.Builder(context, style); + if (response != null) { + builder.setMessage(context.getString(R.string.redirect_detected, url, response)); + builder.setNegativeButton(R.string.copy_link, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); + ClipData clip = ClipData.newPlainText(Helper.CLIP_BOARD, response); + if (clipboard != null) { + clipboard.setPrimaryClip(clip); + Toasty.info(context, context.getString(R.string.clipboard_url), Toast.LENGTH_LONG).show(); + } + dialog.dismiss(); + } + }); + builder.setNeutralButton(R.string.share_link, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + Intent sendIntent = new Intent(Intent.ACTION_SEND); + sendIntent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.shared_via)); + sendIntent.putExtra(Intent.EXTRA_TEXT, url); + sendIntent.setType("text/plain"); + context.startActivity(Intent.createChooser(sendIntent, context.getString(R.string.share_with))); + dialog.dismiss(); + } + }); + } else { + builder.setMessage(R.string.no_redirect); + } + builder.setTitle(context.getString(R.string.check_redirect)); + builder.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + } + }) + .show(); + + } + }; + mainHandler.post(myRunnable); + + } + }; + thread.start(); + break; + } + return true; + } + }); + popup.setOnDismissListener(new PopupMenu.OnDismissListener() { + @Override + public void onDismiss(PopupMenu menu) { + BaseActivity.canShowActionMode = true; + } + }); + popup.show(); + textView.clearFocus(); + BaseActivity.canShowActionMode = false; } - } - } - @Override - public void onLongClick(@NonNull View textView) { - PopupMenu popup = new PopupMenu(context, textView); - popup.getMenuInflater() - .inflate(R.menu.links_popup, popup.getMenu()); - 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; - } - popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { - public boolean onMenuItemClick(MenuItem item) { - switch (item.getItemId()) { - case R.id.action_show_link: - int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); - - AlertDialog.Builder builder = new AlertDialog.Builder(context, style); - builder.setMessage(url); - builder.setTitle(context.getString(R.string.display_full_link)); - builder.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - } - }) - .show(); - break; - case R.id.action_share_link: - Intent sendIntent = new Intent(Intent.ACTION_SEND); - sendIntent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.shared_via)); - sendIntent.putExtra(Intent.EXTRA_TEXT, url); - sendIntent.setType("text/plain"); - context.startActivity(Intent.createChooser(sendIntent, context.getString(R.string.share_with))); - break; - - case R.id.action_open_other_app: - 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(); - } - break; - case R.id.action_copy_link: - ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); - ClipData clip = ClipData.newPlainText(Helper.CLIP_BOARD, url); - if (clipboard != null) { - clipboard.setPrimaryClip(clip); - Toasty.info(context, context.getString(R.string.clipboard_url), Toast.LENGTH_LONG).show(); - } - break; - case R.id.action_unshorten: - Thread thread = new Thread() { - @Override - public void run() { - String response = new HttpsConnection(context, null).checkUrl(url); - - Handler mainHandler = new Handler(context.getMainLooper()); - - Runnable myRunnable = new Runnable() { - @Override - public void run() { - AlertDialog.Builder builder = new AlertDialog.Builder(context, style); - if( response != null ) { - builder.setMessage(context.getString(R.string.redirect_detected,url,response)); - builder.setNegativeButton(R.string.copy_link, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); - ClipData clip = ClipData.newPlainText(Helper.CLIP_BOARD, response); - if (clipboard != null) { - clipboard.setPrimaryClip(clip); - Toasty.info(context, context.getString(R.string.clipboard_url), Toast.LENGTH_LONG).show(); - } - dialog.dismiss(); - } - }); - builder.setNeutralButton(R.string.share_link, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - Intent sendIntent = new Intent(Intent.ACTION_SEND); - sendIntent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.shared_via)); - sendIntent.putExtra(Intent.EXTRA_TEXT, url); - sendIntent.setType("text/plain"); - context.startActivity(Intent.createChooser(sendIntent, context.getString(R.string.share_with))); - dialog.dismiss(); - } - }); - }else{ - builder.setMessage(R.string.no_redirect); - } - builder.setTitle(context.getString(R.string.check_redirect)); - builder.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - } - }) - .show(); - - } - }; - mainHandler.post(myRunnable); - - } - }; - thread.start(); - break; - } - return true; - } - }); - popup.setOnDismissListener(new PopupMenu.OnDismissListener() { - @Override - public void onDismiss(PopupMenu menu) { - BaseActivity.canShowActionMode = true; - } - }); - popup.show(); - textView.clearFocus(); - BaseActivity.canShowActionMode = false; - } - - - @Override - public void updateDrawState(@NonNull TextPaint ds) { - super.updateDrawState(ds); - ds.setUnderlineText(false); - ds.setColor(link_color); - } - }, - startPosition, endPosition, - Spanned.SPAN_INCLUSIVE_EXCLUSIVE); + @Override + public void updateDrawState(@NonNull TextPaint ds) { + super.updateDrawState(ds); + ds.setUnderlineText(false); + ds.setColor(link_color); + } + }, + startPosition, endPosition, + Spanned.SPAN_INCLUSIVE_EXCLUSIVE); } @@ -1069,7 +1060,7 @@ public class Status implements Parcelable { resource.setBounds(0, 0, (int) Helper.convertDpToPixel(20, context), (int) Helper.convertDpToPixel(20, context)); resource.setVisible(true, true); imageSpan = new ImageSpan(resource); - }catch (Exception e) { + } catch (Exception e) { Bitmap bitmap = drawableToBitmap(resource.getCurrent()); imageSpan = new ImageSpan(context, Bitmap.createScaledBitmap(bitmap, (int) Helper.convertDpToPixel(20, context), 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 69d34e4ff..148a002ab 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,12 +27,31 @@ import java.util.List; public class Tag implements Parcelable { + public static final Creator CREATOR = new Creator() { + @Override + public Tag createFromParcel(Parcel source) { + return new Tag(source); + } + + @Override + public Tag[] newArray(int size) { + return new Tag[size]; + } + }; private String name; private String url; private List trendsHistory; + public Tag() { } + protected Tag(Parcel in) { + this.name = in.readString(); + this.url = in.readString(); + this.trendsHistory = new ArrayList(); + in.readList(this.trendsHistory, TrendsHistory.class.getClassLoader()); + } + public List getTrendsHistory() { return trendsHistory; } @@ -68,23 +87,4 @@ public class Tag implements Parcelable { dest.writeString(this.url); dest.writeList(this.trendsHistory); } - - protected Tag(Parcel in) { - this.name = in.readString(); - this.url = in.readString(); - this.trendsHistory = new ArrayList(); - in.readList(this.trendsHistory, TrendsHistory.class.getClassLoader()); - } - - public static final Creator CREATOR = new Creator() { - @Override - public Tag createFromParcel(Parcel source) { - return new Tag(source); - } - - @Override - public Tag[] newArray(int size) { - return new Tag[size]; - } - }; } diff --git a/app/src/main/java/app/fedilab/android/client/Entities/TrendsHistory.java b/app/src/main/java/app/fedilab/android/client/Entities/TrendsHistory.java index f6d63131e..647e6be20 100644 --- a/app/src/main/java/app/fedilab/android/client/Entities/TrendsHistory.java +++ b/app/src/main/java/app/fedilab/android/client/Entities/TrendsHistory.java @@ -25,10 +25,30 @@ import android.os.Parcelable; public class TrendsHistory implements Parcelable { + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + @Override + public TrendsHistory createFromParcel(Parcel source) { + return new TrendsHistory(source); + } + + @Override + public TrendsHistory[] newArray(int size) { + return new TrendsHistory[size]; + } + }; private long days; private int uses; private int accounts; + public TrendsHistory() { + } + + protected TrendsHistory(Parcel in) { + this.days = in.readLong(); + this.uses = in.readInt(); + this.accounts = in.readInt(); + } + public long getDays() { return days; } @@ -64,25 +84,4 @@ public class TrendsHistory implements Parcelable { dest.writeInt(this.uses); dest.writeInt(this.accounts); } - - public TrendsHistory() { - } - - protected TrendsHistory(Parcel in) { - this.days = in.readLong(); - this.uses = in.readInt(); - this.accounts = in.readInt(); - } - - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - @Override - public TrendsHistory createFromParcel(Parcel source) { - return new TrendsHistory(source); - } - - @Override - public TrendsHistory[] newArray(int size) { - return new TrendsHistory[size]; - } - }; } 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 c602a48e8..6f7116655 100644 --- a/app/src/main/java/app/fedilab/android/client/GNUAPI.java +++ b/app/src/main/java/app/fedilab/android/client/GNUAPI.java @@ -268,7 +268,7 @@ public class GNUAPI { } //Retrieves mentions List mentions = new ArrayList<>(); - Helper.largeLog( resobj.toString()); + Helper.largeLog(resobj.toString()); if (resobj.has("attentions")) { JSONArray arrayMention = resobj.getJSONArray("attentions"); if (arrayMention != null) { @@ -397,17 +397,17 @@ public class GNUAPI { Account account = new Account(); try { - if( resobj.has("id_str")){ + if (resobj.has("id_str")) { account.setId(resobj.getString("id_str")); - }else{ + } else { account.setId(resobj.get("id").toString()); } if (resobj.has("ostatus_uri")) { account.setUuid(resobj.get("ostatus_uri").toString()); - }else { - if( resobj.has("id_str")){ + } else { + if (resobj.has("id_str")) { account.setUuid(resobj.getString("id_str")); - }else{ + } else { account.setUuid(resobj.get("id").toString()); } } 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 26ea54857..509fce219 100644 --- a/app/src/main/java/app/fedilab/android/client/HttpsConnection.java +++ b/app/src/main/java/app/fedilab/android/client/HttpsConnection.java @@ -21,7 +21,6 @@ import android.os.Build; import android.text.Html; import android.text.SpannableString; - import com.google.gson.JsonObject; import net.gotev.uploadservice.MultipartUploadRequest; @@ -141,10 +140,11 @@ public class HttpsConnection { /** * Get calls + * * @param urlConnection String url - * @param timeout int timeout - * @param paramaters HashMap paramaters - * @param token String token + * @param timeout int timeout + * @param paramaters HashMap paramaters + * @param token String token * @return String * @throws IOException * @throws NoSuchAlgorithmException @@ -165,7 +165,7 @@ public class HttpsConnection { } StringBuilder postData = new StringBuilder(); URL url; - if( params.size() > 0 ) { + if (params.size() > 0) { for (Map.Entry param : params.entrySet()) { if (postData.length() != 0) postData.append('&'); postData.append(param.getKey()); @@ -173,7 +173,7 @@ public class HttpsConnection { postData.append(param.getValue()); } url = new URL(urlConnection + "?" + postData); - }else{ + } else { url = new URL(urlConnection); } @@ -228,10 +228,11 @@ public class HttpsConnection { /** * Will check if the current url is redirecting + * * @param urlConnection String the url to check * @return String null|string url redirection */ - public String checkUrl(String urlConnection){ + public String checkUrl(String urlConnection) { URL url; String redirect = null; try { @@ -244,7 +245,7 @@ public class HttpsConnection { httpsURLConnection.setInstanceFollowRedirects(false); httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory(this.instance)); httpsURLConnection.setRequestMethod("HEAD"); - if( httpsURLConnection.getResponseCode() == 301) { + if (httpsURLConnection.getResponseCode() == 301) { Map> map = httpsURLConnection.getHeaderFields(); for (Map.Entry> entry : map.entrySet()) { if (entry.toString().toLowerCase().startsWith("location")) { @@ -256,11 +257,11 @@ public class HttpsConnection { } } httpsURLConnection.getInputStream().close(); - if (redirect != null && redirect.compareTo(urlConnection)!=0){ + if (redirect != null && redirect.compareTo(urlConnection) != 0) { URL redirectURL = new URL(redirect); String host = redirectURL.getHost(); String protocol = redirectURL.getProtocol(); - if( protocol == null || host == null){ + if (protocol == null || host == null) { redirect = null; } } @@ -833,7 +834,8 @@ public class HttpsConnection { return httpsURLConnection.getInputStream(); } httpsURLConnection.getInputStream().close(); - } catch (IOException | NoSuchAlgorithmException | KeyManagementException ignored) {} + } catch (IOException | NoSuchAlgorithmException | KeyManagementException ignored) { + } if (httpsURLConnection != null) try { httpsURLConnection.getInputStream().close(); @@ -1372,7 +1374,7 @@ public class HttpsConnection { return max_id; } - private void getOKHttpHeader(Map> headers){ + private void getOKHttpHeader(Map> headers) { for (Map.Entry> entry : headers.entrySet()) { if (entry.toString().startsWith("Link") || entry.toString().startsWith("link")) { Pattern patternMaxId = Pattern.compile("max_id=([0-9a-zA-Z]{1,}).*"); @@ -1388,7 +1390,7 @@ public class HttpsConnection { } } - }else if (entry.toString().startsWith("Min-Id") || entry.toString().startsWith("min-id")) { + } else if (entry.toString().startsWith("Min-Id") || entry.toString().startsWith("min-id")) { Pattern patternMaxId = Pattern.compile("min-id=\\[([0-9a-zA-Z]{1,}).*\\]"); Matcher matcherMaxId = patternMaxId.matcher(entry.toString()); if (matcherMaxId.find()) { @@ -1421,7 +1423,7 @@ public class HttpsConnection { } } - }else if (entry.toString().startsWith("Min-Id") || entry.toString().startsWith("min-id")) { + } else if (entry.toString().startsWith("Min-Id") || entry.toString().startsWith("min-id")) { Pattern patternMaxId = Pattern.compile("min-id=\\[([0-9a-zA-Z]{1,}).*\\]"); Matcher matcherMaxId = patternMaxId.matcher(entry.toString()); if (matcherMaxId.find()) { 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 3d1e5fb0f..7681b6842 100644 --- a/app/src/main/java/app/fedilab/android/client/PeertubeAPI.java +++ b/app/src/main/java/app/fedilab/android/client/PeertubeAPI.java @@ -344,7 +344,7 @@ public class PeertubeAPI { e.printStackTrace(); } ArrayList resolutions = new ArrayList<>(); - if( resobj.has("streamingPlaylists") && resobj.getJSONArray("streamingPlaylists").length() > 0){ + if (resobj.has("streamingPlaylists") && resobj.getJSONArray("streamingPlaylists").length() > 0) { JSONArray files = resobj.getJSONArray("streamingPlaylists").getJSONObject(0).getJSONArray("files"); for (int j = 0; j < files.length(); j++) { @@ -353,7 +353,7 @@ public class PeertubeAPI { } peertube.setResolution(resolutions); peertube.setStreamService(true); - }else { + } else { JSONArray files = resobj.getJSONArray("files"); for (int j = 0; j < files.length(); j++) { JSONObject attObj = files.getJSONObject(j); @@ -413,11 +413,14 @@ 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) {} + } catch (Exception ignored) { + } try { playlist.setUpdatedAt(Helper.stringToDate(context, resobj.getString("updatedAt"))); - } catch (Exception ignored) {} - } catch (Exception ignored) {} + } catch (Exception ignored) { + } + } catch (Exception ignored) { + } return playlist; } @@ -692,7 +695,7 @@ public class PeertubeAPI { e1.printStackTrace(); setError(e.getStatusCode(), e); } - }else{ + } else { setError(e.getStatusCode(), e); } e.printStackTrace(); @@ -1142,7 +1145,6 @@ public class PeertubeAPI { } - /** * Retrieves home timeline for the account *synchronously* * diff --git a/app/src/main/java/app/fedilab/android/client/PixelfedAPI.java b/app/src/main/java/app/fedilab/android/client/PixelfedAPI.java index 7dc6a2171..cd9811ab9 100644 --- a/app/src/main/java/app/fedilab/android/client/PixelfedAPI.java +++ b/app/src/main/java/app/fedilab/android/client/PixelfedAPI.java @@ -28,7 +28,6 @@ import app.fedilab.android.client.Entities.Attachment; import app.fedilab.android.client.Entities.Error; import app.fedilab.android.client.Entities.PixelFedStory; import app.fedilab.android.client.Entities.PixelFedStoryItem; -import app.fedilab.android.client.Entities.PollOptions; import app.fedilab.android.client.Entities.Status; import app.fedilab.android.helper.Helper; import app.fedilab.android.sqlite.AccountDAO; @@ -77,147 +76,6 @@ public class PixelfedAPI { APIError = null; } - - /** - * Retrieves Pixelfed Own Stories *synchronously* - * - * @return APIResponse - */ - public APIResponse getMyStories() { - pixelFedStories = new ArrayList<>(); - PixelFedStory pixelFedStory; - try { - HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - String response = httpsConnection.get(getAbsoluteUrl("/me"), 10, null, prefKeyOauthTokenT); - apiResponse.setSince_id(httpsConnection.getSince_id()); - apiResponse.setMax_id(httpsConnection.getMax_id()); - pixelFedStory = parseStory(new JSONObject(response)); - pixelFedStories.add(pixelFedStory); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - e.printStackTrace(); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - if (apiResponse == null) - apiResponse = new APIResponse(); - apiResponse.setPixelFedStories(pixelFedStories); - return apiResponse; - } - - /** - * Retrieves Pixelfed Own Stories *synchronously* - * - * @return APIResponse - */ - public APIResponse getFriendStories(String max_id) { - pixelFedStories = new ArrayList<>(); - HashMap params = new HashMap<>(); - if (max_id != null) - params.put("max_id", max_id); - try { - HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - String response = httpsConnection.get(getAbsoluteUrl("/recent"), 10, params, prefKeyOauthTokenT); - apiResponse.setSince_id(httpsConnection.getSince_id()); - apiResponse.setMax_id(httpsConnection.getMax_id()); - pixelFedStories = parseStories(new JSONArray(response)); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - e.printStackTrace(); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - if (apiResponse == null) - apiResponse = new APIResponse(); - apiResponse.setPixelFedStories(pixelFedStories); - return apiResponse; - } - - - - /** - * Posts a story - * - * @param status Status object related to the status - * @return APIResponse - */ - public APIResponse postStory(Status status) { - - JsonObject jsonObject = new JsonObject(); - if (status.getMedia_attachments() != null && status.getMedia_attachments().size() > 0) { - JsonArray mediaArray = new JsonArray(); - for (Attachment attachment : status.getMedia_attachments()) - mediaArray.add(attachment.getId()); - jsonObject.add("media_ids", mediaArray); - } - ArrayList statuses = new ArrayList<>(); - try { - HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - String response = httpsConnection.postJson(getAbsoluteUrl("/add"), 30, jsonObject, prefKeyOauthTokenT); - apiResponse.setSince_id(httpsConnection.getSince_id()); - apiResponse.setMax_id(httpsConnection.getMax_id()); - PixelFedStory statusreturned = parseStory(new JSONObject(response)); - statuses.add(statusreturned); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - e.printStackTrace(); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - apiResponse.setPixelFedStories(statuses); - return apiResponse; - } - - - /** - * Retrieves an item from its ID - * - * @return APIResponse - */ - public APIResponse getStoryItem(String id) { - pixelFedStoryItems = new ArrayList<>(); - try { - HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); - String response = httpsConnection.get(getAbsoluteUrl(String.format("/item/%s", id)), 10, null, prefKeyOauthTokenT); - apiResponse.setSince_id(httpsConnection.getSince_id()); - apiResponse.setMax_id(httpsConnection.getMax_id()); - PixelFedStoryItem pixelFedStoryItem = parseStoryItem(new JSONObject(response)); - pixelFedStoryItems.add(pixelFedStoryItem); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { - e.printStackTrace(); - } - if (apiResponse == null) - apiResponse = new APIResponse(); - apiResponse.setPixelFedStoryItems(pixelFedStoryItems); - return apiResponse; - } - - /** - * Delete a Pixelfed Story *synchronously* - * - * @return APIResponse - */ - public int deleteStory(String id) { - - HashMap params = new HashMap<>(); - params.put("id", id); - HttpsConnection httpsConnection; - try { - httpsConnection = new HttpsConnection(context, this.instance); - httpsConnection.delete(getAbsoluteUrl("/delete"), 10, params, prefKeyOauthTokenT); - actionCode = httpsConnection.getActionCode(); - } catch (HttpsConnection.HttpsConnectionException e) { - setError(e.getStatusCode(), e); - } catch (NoSuchAlgorithmException | IOException | KeyManagementException e) { - e.printStackTrace(); - } - return actionCode; - } - - - /** * Parse json response for several stories * @@ -242,8 +100,6 @@ public class PixelfedAPI { return pixelFedStories; } - - /** * Parse a single item for stories * @@ -313,7 +169,140 @@ public class PixelfedAPI { return pixelFedStoryItem; } + /** + * Retrieves Pixelfed Own Stories *synchronously* + * + * @return APIResponse + */ + public APIResponse getMyStories() { + pixelFedStories = new ArrayList<>(); + PixelFedStory pixelFedStory; + try { + HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); + String response = httpsConnection.get(getAbsoluteUrl("/me"), 10, null, prefKeyOauthTokenT); + apiResponse.setSince_id(httpsConnection.getSince_id()); + apiResponse.setMax_id(httpsConnection.getMax_id()); + pixelFedStory = parseStory(new JSONObject(response)); + pixelFedStories.add(pixelFedStory); + } catch (HttpsConnection.HttpsConnectionException e) { + setError(e.getStatusCode(), e); + e.printStackTrace(); + } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { + e.printStackTrace(); + } + if (apiResponse == null) + apiResponse = new APIResponse(); + apiResponse.setPixelFedStories(pixelFedStories); + return apiResponse; + } + /** + * Retrieves Pixelfed Own Stories *synchronously* + * + * @return APIResponse + */ + public APIResponse getFriendStories(String max_id) { + pixelFedStories = new ArrayList<>(); + HashMap params = new HashMap<>(); + if (max_id != null) + params.put("max_id", max_id); + try { + HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); + String response = httpsConnection.get(getAbsoluteUrl("/recent"), 10, params, prefKeyOauthTokenT); + apiResponse.setSince_id(httpsConnection.getSince_id()); + apiResponse.setMax_id(httpsConnection.getMax_id()); + pixelFedStories = parseStories(new JSONArray(response)); + } catch (HttpsConnection.HttpsConnectionException e) { + setError(e.getStatusCode(), e); + e.printStackTrace(); + } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { + e.printStackTrace(); + } + if (apiResponse == null) + apiResponse = new APIResponse(); + apiResponse.setPixelFedStories(pixelFedStories); + return apiResponse; + } + + /** + * Posts a story + * + * @param status Status object related to the status + * @return APIResponse + */ + public APIResponse postStory(Status status) { + + JsonObject jsonObject = new JsonObject(); + if (status.getMedia_attachments() != null && status.getMedia_attachments().size() > 0) { + JsonArray mediaArray = new JsonArray(); + for (Attachment attachment : status.getMedia_attachments()) + mediaArray.add(attachment.getId()); + jsonObject.add("media_ids", mediaArray); + } + ArrayList statuses = new ArrayList<>(); + try { + HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); + String response = httpsConnection.postJson(getAbsoluteUrl("/add"), 30, jsonObject, prefKeyOauthTokenT); + apiResponse.setSince_id(httpsConnection.getSince_id()); + apiResponse.setMax_id(httpsConnection.getMax_id()); + PixelFedStory statusreturned = parseStory(new JSONObject(response)); + statuses.add(statusreturned); + } catch (HttpsConnection.HttpsConnectionException e) { + setError(e.getStatusCode(), e); + e.printStackTrace(); + } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { + e.printStackTrace(); + } + apiResponse.setPixelFedStories(statuses); + return apiResponse; + } + + /** + * Retrieves an item from its ID + * + * @return APIResponse + */ + public APIResponse getStoryItem(String id) { + pixelFedStoryItems = new ArrayList<>(); + try { + HttpsConnection httpsConnection = new HttpsConnection(context, this.instance); + String response = httpsConnection.get(getAbsoluteUrl(String.format("/item/%s", id)), 10, null, prefKeyOauthTokenT); + apiResponse.setSince_id(httpsConnection.getSince_id()); + apiResponse.setMax_id(httpsConnection.getMax_id()); + PixelFedStoryItem pixelFedStoryItem = parseStoryItem(new JSONObject(response)); + pixelFedStoryItems.add(pixelFedStoryItem); + } catch (HttpsConnection.HttpsConnectionException e) { + setError(e.getStatusCode(), e); + } catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) { + e.printStackTrace(); + } + if (apiResponse == null) + apiResponse = new APIResponse(); + apiResponse.setPixelFedStoryItems(pixelFedStoryItems); + return apiResponse; + } + + /** + * Delete a Pixelfed Story *synchronously* + * + * @return APIResponse + */ + public int deleteStory(String id) { + + HashMap params = new HashMap<>(); + params.put("id", id); + HttpsConnection httpsConnection; + try { + httpsConnection = new HttpsConnection(context, this.instance); + httpsConnection.delete(getAbsoluteUrl("/delete"), 10, params, prefKeyOauthTokenT); + actionCode = httpsConnection.getActionCode(); + } catch (HttpsConnection.HttpsConnectionException e) { + setError(e.getStatusCode(), e); + } catch (NoSuchAlgorithmException | IOException | KeyManagementException e) { + e.printStackTrace(); + } + return actionCode; + } /** * Set the error message @@ -354,8 +343,6 @@ public class PixelfedAPI { } - - public Error getError() { return APIError; } 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 474da8751..ea2aed656 100644 --- a/app/src/main/java/app/fedilab/android/client/Tls12SocketFactory.java +++ b/app/src/main/java/app/fedilab/android/client/Tls12SocketFactory.java @@ -3,7 +3,6 @@ package app.fedilab.android.client; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; -import java.net.UnknownHostException; import javax.net.ssl.SSLSocket; import javax.net.ssl.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 6ed917f84..79c361a39 100644 --- a/app/src/main/java/app/fedilab/android/drawers/AccountSearchDevAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/AccountSearchDevAdapter.java @@ -132,13 +132,13 @@ public class AccountSearchDevAdapter extends BaseAdapter implements OnPostAction //Profile picture if (account.getAvatar().startsWith("http")) { - if( !((Activity)context).isFinishing() && !((Activity)context).isDestroyed()) { + if (!((Activity) context).isFinishing() && !((Activity) context).isDestroyed()) { Glide.with(context) .load(account.getAvatar()) .into(holder.account_pp); } } else if (account.getSocial() != null && account.getSocial().contains("OPENCOLLECTIVE")) { - if( !((Activity)context).isFinishing() && !((Activity)context).isDestroyed()) { + if (!((Activity) context).isFinishing() && !((Activity) context).isDestroyed()) { Glide.with(context) .load(R.drawable.missing) .into(holder.account_pp); 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 def2b8b2f..ebc446360 100644 --- a/app/src/main/java/app/fedilab/android/drawers/AccountsFollowRequestAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/AccountsFollowRequestAdapter.java @@ -83,7 +83,7 @@ public class AccountsFollowRequestAdapter extends RecyclerView.Adapter implement 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); //TODO: check if Friendica has a way to accept/deny follow requests - if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU) { holder.btn_authorize.setVisibility(View.GONE); holder.btn_reject.setVisibility(View.GONE); } 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 af93aca37..d3c5e0df4 100644 --- a/app/src/main/java/app/fedilab/android/drawers/AccountsListAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/AccountsListAdapter.java @@ -96,7 +96,7 @@ public class AccountsListAdapter extends RecyclerView.Adapter implements OnPostA API.StatusAction doAction = null; - 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) { holder.account_mute_notification.hide(); if (action == RetrieveAccountsAsyncTask.Type.BLOCKED) account.setFollowType(Account.followAction.BLOCK); 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 09acfc167..b63d1fcd4 100644 --- a/app/src/main/java/app/fedilab/android/drawers/AccountsReplyAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/AccountsReplyAdapter.java @@ -101,7 +101,8 @@ public class AccountsReplyAdapter extends BaseAdapter { try { ((TootActivity) activityWeakReference.get()).changeAccountReply(isChecked, "@" + account.getAcct()); checked[position] = isChecked; - } catch (Exception ignored) {} + } catch (Exception ignored) { + } }); holder.checkbox.setChecked(checked[position]); holder.account_dn.setText(String.format("@%s", account.getAcct())); 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 a70987861..9546d989e 100644 --- a/app/src/main/java/app/fedilab/android/drawers/CustomEmojiAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/CustomEmojiAdapter.java @@ -85,37 +85,37 @@ public class CustomEmojiAdapter extends BaseAdapter { //if (!emoji.isDrawableFound()) { - emoji.setDrawableFound(true); - Glide.with(parent.getContext()) - .asFile() - .load(emoji.getUrl()) - .thumbnail(0.1f) - .into(new SimpleTarget() { - @Override - public void onResourceReady(@NonNull File resourceFile, @Nullable Transition transition) { - Drawable resource; - SharedPreferences sharedpreferences = parent.getContext().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - boolean disableAnimatedEmoji = sharedpreferences.getBoolean(Helper.SET_DISABLE_ANIMATED_EMOJI, false); - if (!disableAnimatedEmoji) { - if (GifParser.isGif(resourceFile.getAbsolutePath())) { - resource = GifDrawable.fromFile(resourceFile.getAbsolutePath()); - emoji.setDrawable(resource); - } else if (APNGParser.isAPNG(resourceFile.getAbsolutePath())) { - resource = APNGDrawable.fromFile(resourceFile.getAbsolutePath()); - emoji.setDrawable(resource); - } else { - resource = Drawable.createFromPath(resourceFile.getAbsolutePath()); - emoji.setDrawable(resource); - - } + emoji.setDrawableFound(true); + Glide.with(parent.getContext()) + .asFile() + .load(emoji.getUrl()) + .thumbnail(0.1f) + .into(new SimpleTarget() { + @Override + public void onResourceReady(@NonNull File resourceFile, @Nullable Transition transition) { + Drawable resource; + SharedPreferences sharedpreferences = parent.getContext().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + boolean disableAnimatedEmoji = sharedpreferences.getBoolean(Helper.SET_DISABLE_ANIMATED_EMOJI, false); + if (!disableAnimatedEmoji) { + if (GifParser.isGif(resourceFile.getAbsolutePath())) { + resource = GifDrawable.fromFile(resourceFile.getAbsolutePath()); + emoji.setDrawable(resource); + } else if (APNGParser.isAPNG(resourceFile.getAbsolutePath())) { + resource = APNGDrawable.fromFile(resourceFile.getAbsolutePath()); + emoji.setDrawable(resource); } else { resource = Drawable.createFromPath(resourceFile.getAbsolutePath()); emoji.setDrawable(resource); + } - imageView.setImageDrawable(emoji.getDrawable()); + } else { + resource = Drawable.createFromPath(resourceFile.getAbsolutePath()); + emoji.setDrawable(resource); } - }); - // } + imageView.setImageDrawable(emoji.getDrawable()); + } + }); + // } return convertView; } } \ No newline at end of file diff --git a/app/src/main/java/app/fedilab/android/drawers/IdentityProofsAdapter.java b/app/src/main/java/app/fedilab/android/drawers/IdentityProofsAdapter.java index 447e311e7..b5c796339 100644 --- a/app/src/main/java/app/fedilab/android/drawers/IdentityProofsAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/IdentityProofsAdapter.java @@ -18,11 +18,14 @@ import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; -import androidx.constraintlayout.widget.ConstraintLayout; import android.widget.TextView; + import androidx.annotation.NonNull; +import androidx.constraintlayout.widget.ConstraintLayout; import androidx.recyclerview.widget.RecyclerView; + import java.util.List; + import app.fedilab.android.R; import app.fedilab.android.client.Entities.IdentityProof; import app.fedilab.android.helper.Helper; @@ -59,7 +62,7 @@ public class IdentityProofsAdapter extends RecyclerView.Adapter { final IdentityProof identityProof = getItem(i); holder.proof_name.setText(String.format("@%s", identityProof.getProvider_username())); holder.proof_name.setOnClickListener(v -> Helper.openBrowser(context, identityProof.getProfile_url())); - holder.proof_name_network.setText(context.getString(R.string.verified_by, identityProof.getProvider(),Helper.shortDateToString(identityProof.getUpdated_at()))); + holder.proof_name_network.setText(context.getString(R.string.verified_by, identityProof.getProvider(), Helper.shortDateToString(identityProof.getUpdated_at()))); holder.proof_container.setOnClickListener(v -> Helper.openBrowser(context, identityProof.getProfile_url())); holder.proof_name_network.setOnClickListener(v -> Helper.openBrowser(context, identityProof.getProof_url())); } 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 df2c240b9..18ae1b443 100644 --- a/app/src/main/java/app/fedilab/android/drawers/NotificationsListAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/NotificationsListAdapter.java @@ -233,7 +233,6 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On Helper.changeDrawableColor(context, R.drawable.ic_pin_drop, iconColor); - holder.status_reply_count.setTextColor(iconColor); holder.status_favorite_count.setTextColor(iconColor); holder.status_reblog_count.setTextColor(iconColor); @@ -341,15 +340,15 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On } holder.notification_type.setCompoundDrawables(imgH, null, null, null); - holder.status_privacy.getLayoutParams().height = (int) Helper.convertDpToPixel(((float)(20 * iconSizePercent) / 100), context); - holder.status_privacy.getLayoutParams().width = (int) Helper.convertDpToPixel(((float)(20 * iconSizePercent)/ 100), context); - holder.status_reply.getLayoutParams().height = (int) Helper.convertDpToPixel(((float)(20 * iconSizePercent)/ 100), context); - holder.status_reply.getLayoutParams().width = (int) Helper.convertDpToPixel(((float)(20 * iconSizePercent) / 100), context); - holder.status_spoiler.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float)(14 * textSizePercent) / 100); + holder.status_privacy.getLayoutParams().height = (int) Helper.convertDpToPixel(((float) (20 * iconSizePercent) / 100), context); + holder.status_privacy.getLayoutParams().width = (int) Helper.convertDpToPixel(((float) (20 * iconSizePercent) / 100), context); + holder.status_reply.getLayoutParams().height = (int) Helper.convertDpToPixel(((float) (20 * iconSizePercent) / 100), context); + holder.status_reply.getLayoutParams().width = (int) Helper.convertDpToPixel(((float) (20 * iconSizePercent) / 100), context); + holder.status_spoiler.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float) (14 * textSizePercent) / 100); - holder.notification_status_content.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float)(14 * textSizePercent) / 100); - holder.notification_type.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float)(14 * textSizePercent) / 100); - holder.status_date.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float)(12 * textSizePercent)/ 100); + holder.notification_status_content.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float) (14 * textSizePercent) / 100); + holder.notification_type.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float) (14 * textSizePercent) / 100); + holder.status_date.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float) (12 * textSizePercent) / 100); int theme_text_header_1_line = prefs.getInt("theme_text_header_1_line", -1); if (theme_text_header_1_line == -1) { theme_text_header_1_line = ThemeHelper.getAttColor(context, R.attr.textColor); @@ -366,11 +365,11 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On holder.spark_button_reblog.setInActiveImageTintColor(iconColor); 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(((float)(20 * iconSizePercent) / 100 * scale + 0.5f), context)); + holder.spark_button_fav.setMinimumWidth((int) Helper.convertDpToPixel(((float) (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(((float)(20 * iconSizePercent) / 100 * scale + 0.5f), context)); + holder.spark_button_reblog.setMinimumWidth((int) Helper.convertDpToPixel(((float) (20 * iconSizePercent) / 100 * scale + 0.5f), context)); final Status status = notification.getStatus(); if (status != null) { @@ -394,7 +393,7 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On holder.status_privacy.setOnClickListener(view -> { String v = status.getVisibility(); - holder.status_privacy.setContentDescription(context.getString(R.string.toot_visibility_tilte) + ": " + v); + holder.status_privacy.setContentDescription(context.getString(R.string.toot_visibility_tilte) + ": " + v); }); holder.notification_status_content.setText(status.getContentSpan(), TextView.BufferType.SPANNABLE); holder.status_spoiler.setText(status.getContentSpanCW(), TextView.BufferType.SPANNABLE); @@ -534,7 +533,7 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On } - if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON ) { + if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { holder.rated.setVisibility(View.GONE); holder.poll_container.setVisibility(View.GONE); holder.multiple_choice.setVisibility(View.GONE); @@ -633,9 +632,9 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On holder.refresh_poll.setOnClickListener(v -> new ManagePollAsyncTask(context, ManagePollAsyncTask.type_s.REFRESH, status, null, NotificationsListAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)); holder.poll_container.setVisibility(View.VISIBLE); holder.number_votes.setText(context.getResources().getQuantityString(R.plurals.number_of_voters, status.getPoll().getVoters_count(), status.getPoll().getVoters_count())); - if( poll.isExpired()){ + if (poll.isExpired()) { holder.remaining_time.setText(context.getString(R.string.poll_finish_at, Helper.dateToStringPoll(poll.getExpires_at()))); - }else{ + } else { holder.remaining_time.setText(context.getString(R.string.poll_finish_in, Helper.dateDiffPoll(context, poll.getExpires_at()))); } } else { 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 f109d2afd..5944dd4d8 100644 --- a/app/src/main/java/app/fedilab/android/drawers/PeertubeNotificationsListAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/PeertubeNotificationsListAdapter.java @@ -191,7 +191,6 @@ public class PeertubeNotificationsListAdapter extends RecyclerView.Adapter { } - static class ViewHolder extends RecyclerView.ViewHolder { ImageView peertube_notif_pp; 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 6aaf501a9..c5d9d29e2 100644 --- a/app/src/main/java/app/fedilab/android/drawers/PixelfedListAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/PixelfedListAdapter.java @@ -1032,7 +1032,7 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA if (trans == Helper.TRANS_DEEPL) { et = MyTransL.translatorEngine.DEEPL; - }else if (trans == Helper.TRANS_SYSTRAN) { + } else if (trans == Helper.TRANS_SYSTRAN) { et = MyTransL.translatorEngine.SYSTRAN; } final MyTransL myTransL = MyTransL.getInstance(et); diff --git a/app/src/main/java/app/fedilab/android/drawers/PixelfedStoriesListAdapter.java b/app/src/main/java/app/fedilab/android/drawers/PixelfedStoriesListAdapter.java index 5ff99ad16..432d62619 100644 --- a/app/src/main/java/app/fedilab/android/drawers/PixelfedStoriesListAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/PixelfedStoriesListAdapter.java @@ -52,16 +52,15 @@ import app.fedilab.android.client.Entities.PixelFedStoryItem; import app.fedilab.android.helper.Helper; - /** * Created by Thomas on 02/11/2019. * Adapter for pixelfed stories drawer */ public class PixelfedStoriesListAdapter extends RecyclerView.Adapter { + private static final int DISPLAYED_STATUS = 1; private Context context; private List stories; - private static final int DISPLAYED_STATUS = 1; private ArrayList attachments; public PixelfedStoriesListAdapter(List stories) { @@ -70,8 +69,6 @@ public class PixelfedStoriesListAdapter extends RecyclerView.Adapter { } - - @Override public long getItemId(int position) { return position; @@ -82,30 +79,6 @@ public class PixelfedStoriesListAdapter extends RecyclerView.Adapter { return stories.size(); } - - - private static class ViewHolderPixelfed extends RecyclerView.ViewHolder { - SliderView imageSlider; - ImageView art_media, art_media_play, pf_pp; - SparkButton pf_share; - TextView pf_username, pf_date; - CardView pf_cardview; - - - ViewHolderPixelfed(View itemView) { - super(itemView); - art_media = itemView.findViewById(R.id.art_media); - art_media_play = itemView.findViewById(R.id.art_media_play); - imageSlider = itemView.findViewById(R.id.imageSlider); - pf_pp = itemView.findViewById(R.id.pf_pp); - pf_username = itemView.findViewById(R.id.pf_username); - pf_date = itemView.findViewById(R.id.pf_date); - pf_share = itemView.findViewById(R.id.pf_share); - pf_cardview = itemView.findViewById(R.id.pf_cardview); - } - } - - public PixelFedStory getItem(int position) { if (stories.size() > position && position >= 0) return stories.get(position); @@ -125,7 +98,6 @@ public class PixelfedStoriesListAdapter extends RecyclerView.Adapter { return new ViewHolderPixelfed(layoutInflater.inflate(R.layout.drawer_pixelfed_story, parent, false)); } - @SuppressLint("SetJavaScriptEnabled") @Override public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder viewHolder, int i) { @@ -136,12 +108,12 @@ public class PixelfedStoriesListAdapter extends RecyclerView.Adapter { attachments = new ArrayList<>(); - for(PixelFedStoryItem pixelFedStoryItem: pixelFedStory.getPixelFedStoryItems()){ + for (PixelFedStoryItem pixelFedStoryItem : pixelFedStory.getPixelFedStoryItems()) { Attachment attachment = new Attachment(); - if( pixelFedStoryItem.getPreview() != null){ + if (pixelFedStoryItem.getPreview() != null) { attachment.setPreview_url(pixelFedStoryItem.getPreview()); - }else{ + } else { attachment.setPreview_url(pixelFedStoryItem.getSrc()); } attachment.setUrl(pixelFedStoryItem.getSrc()); @@ -157,7 +129,6 @@ public class PixelfedStoriesListAdapter extends RecyclerView.Adapter { .into(holder.pf_pp); - holder.art_media.setOnClickListener(v -> { Intent intent = new Intent(context, SlideMediaActivity.class); Bundle b = new Bundle(); @@ -168,27 +139,25 @@ public class PixelfedStoriesListAdapter extends RecyclerView.Adapter { }); - - holder.art_media_play.setVisibility(View.GONE); - if (attachments != null && attachments.size() > 1){ - SliderAdapter sliderAdapter = new SliderAdapter(new WeakReference<>((Activity)context), false, attachments); + if (attachments != null && attachments.size() > 1) { + SliderAdapter sliderAdapter = new SliderAdapter(new WeakReference<>((Activity) context), false, attachments); holder.imageSlider.setSliderAdapter(sliderAdapter); holder.imageSlider.setIndicatorAnimation(IndicatorAnimations.WORM); holder.imageSlider.setSliderTransformAnimation(SliderAnimations.SIMPLETRANSFORMATION); holder.art_media.setVisibility(View.GONE); holder.imageSlider.setVisibility(View.VISIBLE); - }else if(attachments != null ){ + } else if (attachments != null) { holder.art_media.setVisibility(View.VISIBLE); holder.imageSlider.setVisibility(View.GONE); - if( attachments.get(0).getType().toLowerCase().equals("video")){ + if (attachments.get(0).getType().toLowerCase().equals("video")) { holder.art_media_play.setVisibility(View.VISIBLE); } String url; - if(attachments.get(0).getPreview_url().endsWith("no-preview.png") ){ + if (attachments.get(0).getPreview_url().endsWith("no-preview.png")) { url = attachments.get(0).getUrl(); - }else{ + } else { url = attachments.get(0).getPreview_url(); } Glide.with(holder.itemView.getContext()) @@ -199,7 +168,6 @@ public class PixelfedStoriesListAdapter extends RecyclerView.Adapter { } - holder.pf_date.setText(Helper.longDateToString(pixelFedStory.getLastUpdated())); @@ -223,4 +191,25 @@ public class PixelfedStoriesListAdapter extends RecyclerView.Adapter { } + private static class ViewHolderPixelfed extends RecyclerView.ViewHolder { + SliderView imageSlider; + ImageView art_media, art_media_play, pf_pp; + SparkButton pf_share; + TextView pf_username, pf_date; + CardView pf_cardview; + + + ViewHolderPixelfed(View itemView) { + super(itemView); + art_media = itemView.findViewById(R.id.art_media); + art_media_play = itemView.findViewById(R.id.art_media_play); + imageSlider = itemView.findViewById(R.id.imageSlider); + pf_pp = itemView.findViewById(R.id.pf_pp); + pf_username = itemView.findViewById(R.id.pf_username); + pf_date = itemView.findViewById(R.id.pf_date); + pf_share = itemView.findViewById(R.id.pf_share); + pf_cardview = itemView.findViewById(R.id.pf_cardview); + } + } + } \ No newline at end of file diff --git a/app/src/main/java/app/fedilab/android/drawers/SliderAdapter.java b/app/src/main/java/app/fedilab/android/drawers/SliderAdapter.java index 846dad978..47909e168 100644 --- a/app/src/main/java/app/fedilab/android/drawers/SliderAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/SliderAdapter.java @@ -16,7 +16,6 @@ package app.fedilab.android.drawers; import android.app.Activity; -import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; 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 c479fbf91..26e08c671 100644 --- a/app/src/main/java/app/fedilab/android/drawers/StatusListAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/StatusListAdapter.java @@ -190,11 +190,11 @@ import static app.fedilab.android.activities.BaseMainActivity.social; */ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostActionInterface, OnRetrieveFeedsInterface, OnRetrieveImageInterface, OnRetrieveEmojiInterface, OnRetrieveRepliesInterface, OnRetrieveCardInterface, OnPollInterface, OnRefreshCachedStatusInterface, OnRetrieveSearcAccountshInterface, OnRetrieveSearchInterface, OnPostStatusActionInterface, OnRetrieveRelationshipQuickReplyInterface { - private static final int HIDDEN_STATUS = 0; public static final int DISPLAYED_STATUS = 1; - private static final int FOCUSED_STATUS = 2; public static final int COMPACT_STATUS = 3; public static final int CONSOLE_STATUS = 4; + private static final int HIDDEN_STATUS = 0; + private static final int FOCUSED_STATUS = 2; public static boolean fetch_all_more = false; private final Object lock = new Object(); private Context context; @@ -222,27 +222,6 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct private List emojisPicker; private Status statusForQuickReply; private String instanceType; - - - - public StatusListAdapter(StatusDrawerParams statusDrawerParams){ - statuses = statusDrawerParams.getStatuses(); - isOnWifi = statusDrawerParams.isOnWifi(); - statusListAdapter = this; - type = statusDrawerParams.getType(); - targetedId = statusDrawerParams.getTargetedId(); - tagTimeline = statusDrawerParams.getTagTimeline(); - conversationPosition = statusDrawerParams.getPosition(); - redraft = false; - lstHolders = new ArrayList<>(); - toot_content = null; - toot_cw_content = null; - tootReply = null; - currentToId = -1; - instanceType = statusDrawerParams.getInstanceType(); - } - - private Runnable updateAnimatedEmoji = new Runnable() { @Override public void run() { @@ -263,9 +242,25 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } } }; - private Handler mHandler = new Handler(); + public StatusListAdapter(StatusDrawerParams statusDrawerParams) { + statuses = statusDrawerParams.getStatuses(); + isOnWifi = statusDrawerParams.isOnWifi(); + statusListAdapter = this; + type = statusDrawerParams.getType(); + targetedId = statusDrawerParams.getTargetedId(); + tagTimeline = statusDrawerParams.getTagTimeline(); + conversationPosition = statusDrawerParams.getPosition(); + redraft = false; + lstHolders = new ArrayList<>(); + toot_content = null; + toot_cw_content = null; + tootReply = null; + currentToId = -1; + instanceType = statusDrawerParams.getInstanceType(); + } + @Override public void onAttachedToRecyclerView(@NotNull RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); @@ -578,9 +573,9 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct if (social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED && type == RetrieveFeedsAsyncTask.Type.CONTEXT) { return COMPACT_STATUS; } else { - if( instanceType == null || instanceType.compareTo("NITTER") != 0 ) { + if (instanceType == null || instanceType.compareTo("NITTER") != 0) { return statuses.get(position).getViewType(); - }else{ + } else { return COMPACT_STATUS; } } @@ -636,7 +631,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.status_privacy.setOnClickListener(view -> { String v = status.getVisibility(); - holder.status_privacy.setContentDescription(context.getString(R.string.toot_visibility_tilte)+": " + v); + holder.status_privacy.setContentDescription(context.getString(R.string.toot_visibility_tilte) + ": " + v); }); if (type == RetrieveFeedsAsyncTask.Type.CONTEXT && holder.status_reply_indicator_top != null) { @@ -845,9 +840,9 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.refresh_poll.setOnClickListener(v -> new ManagePollAsyncTask(context, ManagePollAsyncTask.type_s.REFRESH, status, null, StatusListAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)); holder.poll_container.setVisibility(View.VISIBLE); holder.number_votes.setText(context.getResources().getQuantityString(R.plurals.number_of_voters, poll.getVoters_count(), poll.getVoters_count())); - if( poll.isExpired()){ + if (poll.isExpired()) { holder.remaining_time.setText(context.getString(R.string.poll_finish_at, Helper.dateToStringPoll(poll.getExpires_at()))); - }else{ + } else { holder.remaining_time.setText(context.getString(R.string.poll_finish_in, Helper.dateDiffPoll(context, poll.getExpires_at()))); } } else { @@ -958,29 +953,29 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.new_element.setVisibility(View.GONE); - holder.status_reply.getLayoutParams().height = (int) Helper.convertDpToPixel(((float)(20 * iconSizePercent) / 100), context); - holder.status_reply.getLayoutParams().width = (int) Helper.convertDpToPixel(((float)(20 * iconSizePercent) / 100), context); - holder.status_more.getLayoutParams().height = (int) Helper.convertDpToPixel(((float)(20 * iconSizePercent) / 100), context); - holder.status_more.getLayoutParams().width = (int) Helper.convertDpToPixel(((float)(20 * iconSizePercent) / 100), context); - holder.status_privacy.getLayoutParams().height = (int) Helper.convertDpToPixel(((float)(20 * iconSizePercent) / 100), context); - holder.status_privacy.getLayoutParams().width = (int) Helper.convertDpToPixel(((float)(20 * iconSizePercent) / 100), context); + holder.status_reply.getLayoutParams().height = (int) Helper.convertDpToPixel(((float) (20 * iconSizePercent) / 100), context); + holder.status_reply.getLayoutParams().width = (int) Helper.convertDpToPixel(((float) (20 * iconSizePercent) / 100), context); + holder.status_more.getLayoutParams().height = (int) Helper.convertDpToPixel(((float) (20 * iconSizePercent) / 100), context); + holder.status_more.getLayoutParams().width = (int) Helper.convertDpToPixel(((float) (20 * iconSizePercent) / 100), context); + holder.status_privacy.getLayoutParams().height = (int) Helper.convertDpToPixel(((float) (20 * iconSizePercent) / 100), context); + holder.status_privacy.getLayoutParams().width = (int) Helper.convertDpToPixel(((float) (20 * iconSizePercent) / 100), context); if (getItemViewType(viewHolder.getAdapterPosition()) == FOCUSED_STATUS) { - holder.status_content.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float)(16 * textSizePercent) / 100); - holder.status_account_displayname.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float)(16 * textSizePercent) / 100); - holder.status_account_username.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float)(14 * textSizePercent) / 100); - holder.status_toot_date.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float)(14 * textSizePercent) / 100); - holder.status_content_translated.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float)(16 * textSizePercent) / 100); + holder.status_content.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float) (16 * textSizePercent) / 100); + holder.status_account_displayname.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float) (16 * textSizePercent) / 100); + holder.status_account_username.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float) (14 * textSizePercent) / 100); + holder.status_toot_date.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float) (14 * textSizePercent) / 100); + holder.status_content_translated.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float) (16 * textSizePercent) / 100); } else { - holder.status_account_displayname.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float)(14 * textSizePercent) / 100); - holder.status_account_username.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float)(12 * textSizePercent) / 100); - holder.status_content.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float)(14 * textSizePercent) / 100); - holder.status_toot_date.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float)(12 * textSizePercent) / 100); - holder.status_content_translated.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float)(14 * textSizePercent) / 100); + holder.status_account_displayname.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float) (14 * textSizePercent) / 100); + holder.status_account_username.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float) (12 * textSizePercent) / 100); + holder.status_content.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float) (14 * textSizePercent) / 100); + holder.status_toot_date.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float) (12 * textSizePercent) / 100); + holder.status_content_translated.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float) (14 * textSizePercent) / 100); } - holder.status_spoiler.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float)(14 * textSizePercent) / 100); + holder.status_spoiler.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float) (14 * textSizePercent) / 100); switch (translator) { case Helper.TRANS_NONE: @@ -1043,7 +1038,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.status_account_displayname.setTextColor(theme_text_header_2_line); holder.status_toot_date.setTextColor(theme_text_header_2_line); - if( holder.status_boosted_date != null ) { + if (holder.status_boosted_date != null) { holder.status_boosted_date.setTextColor(theme_text_header_2_line); } Helper.changeDrawableColor(context, R.drawable.ic_repeat_head_toot, theme_text_header_2_line); @@ -1056,7 +1051,6 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct Helper.changeDrawableColor(context, holder.cached_status, theme_text_header_1_line); - if (holder.cached_status != null && holder.getItemViewType() == DISPLAYED_STATUS) { if (status.iscached()) { holder.cached_status.setVisibility(View.VISIBLE); @@ -1178,16 +1172,16 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct 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(((float)(20 * iconSizePercent) / 100 * scale + 0.5f), context)); + holder.spark_button_reblog.setMinimumWidth((int) Helper.convertDpToPixel(((float) (20 * iconSizePercent) / 100 * scale + 0.5f), context)); Drawable imgConversation = null; - if( social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { + if (social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { if (type != RetrieveFeedsAsyncTask.Type.CONTEXT && ((status.getIn_reply_to_account_id() != null && status.getIn_reply_to_account_id().equals(status.getAccount().getId())) || (status.getReblog() != null && status.getReblog().getIn_reply_to_account_id() != null && status.getReblog().getIn_reply_to_account_id().equals(status.getReblog().getAccount().getId())))) { imgConversation = ContextCompat.getDrawable(context, R.drawable.ic_conversation); imgConversation.setBounds(0, 0, (int) (15 * iconSizePercent / 100 * scale + 0.5f), (int) (15 * iconSizePercent / 100 * scale + 0.5f)); } - }else { + } else { if (type != RetrieveFeedsAsyncTask.Type.CONTEXT && status.getIn_reply_to_id() != null) { imgConversation = ContextCompat.getDrawable(context, R.drawable.ic_conversation); imgConversation.setBounds(0, 0, (int) (15 * iconSizePercent / 100 * scale + 0.5f), (int) (15 * iconSizePercent / 100 * scale + 0.5f)); @@ -1230,12 +1224,12 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } if (instanceType != null && instanceType.compareTo("NITTER") == 0) { holder.status_action_container.setVisibility(View.GONE); - if( holder.status_action_container_twitter != null){ + if (holder.status_action_container_twitter != null) { holder.status_action_container_twitter.setVisibility(View.VISIBLE); holder.status_action_container_twitter.setOnClickListener(v -> { Intent sendIntent = new Intent(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.shared_via)); - String url = status.getUrl(); + String url = status.getUrl(); String extra_text; extra_text = (status.getReblog() != null) ? status.getReblog().getAccount().getAcct() : status.getAccount().getAcct(); @@ -1277,7 +1271,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct }); //Click on a conversation - if (( instanceType == null || instanceType.compareTo("NITTER") != 0) && (getItemViewType(viewHolder.getAdapterPosition()) == DISPLAYED_STATUS || getItemViewType(viewHolder.getAdapterPosition()) == COMPACT_STATUS || getItemViewType(viewHolder.getAdapterPosition()) == CONSOLE_STATUS)) { + if ((instanceType == null || instanceType.compareTo("NITTER") != 0) && (getItemViewType(viewHolder.getAdapterPosition()) == DISPLAYED_STATUS || getItemViewType(viewHolder.getAdapterPosition()) == COMPACT_STATUS || getItemViewType(viewHolder.getAdapterPosition()) == CONSOLE_STATUS)) { holder.status_spoiler.setOnClickListener(v -> { if (type != RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE && type != RetrieveFeedsAsyncTask.Type.NEWS) { @@ -2184,7 +2178,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.status_cardview.setVisibility(View.GONE); holder.status_cardview_video.setVisibility(View.VISIBLE); String user_agent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, null); - if( user_agent != null) { + if (user_agent != null) { holder.status_cardview_webview.getSettings().setUserAgentString(user_agent); } holder.status_cardview_webview.getSettings().setJavaScriptEnabled(true); @@ -2951,7 +2945,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } }); - } else if( instanceType == null || instanceType.compareTo("NITTER") != 0){ + } else if (instanceType == null || instanceType.compareTo("NITTER") != 0) { holder.status_account_profile.setOnClickListener(v -> { if (status.getReblog() != null) { @@ -3038,8 +3032,8 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct holder.status_horizontal_document_container.setVisibility(View.VISIBLE); else holder.status_document_container.setVisibility(View.VISIBLE); - if (attachments.size() == 1 ) { - if ((status.getCard() == null || status.getCard().getType().compareTo("video") != 0|| status.getCard().getImage() == null)) { + if (attachments.size() == 1) { + if ((status.getCard() == null || status.getCard().getType().compareTo("video") != 0 || status.getCard().getImage() == null)) { if (!fullAttachement) holder.status_container2.setVisibility(View.GONE); else { @@ -3055,7 +3049,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct else holder.status_document_container.setVisibility(View.GONE); } - }else { + } else { if (fullAttachement) holder.status_horizontal_document_container.setVisibility(View.GONE); else @@ -3615,7 +3609,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct toot.setSpoiler_text(toot_cw_content.getText().toString().trim()); toot.setVisibility(status.getQuickReplyPrivacy()); toot.setIn_reply_to_id(in_reply_to_status); - if( content == null) { + if (content == null) { content = status.getQuickReplyContent(); } toot.setContent(context, content); diff --git a/app/src/main/java/app/fedilab/android/drawers/TrendsAdapter.java b/app/src/main/java/app/fedilab/android/drawers/TrendsAdapter.java index df3bd712b..502b8cc42 100644 --- a/app/src/main/java/app/fedilab/android/drawers/TrendsAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/TrendsAdapter.java @@ -28,7 +28,6 @@ import androidx.core.content.ContextCompat; import com.github.mikephil.charting.charts.LineChart; import com.github.mikephil.charting.components.Description; -import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.LineData; @@ -45,7 +44,6 @@ import app.fedilab.android.R; import app.fedilab.android.activities.HashTagActivity; import app.fedilab.android.client.Entities.Trends; import app.fedilab.android.client.Entities.TrendsHistory; -import app.fedilab.android.helper.Helper; /** @@ -106,9 +104,9 @@ public class TrendsAdapter extends BaseAdapter { int uses = 0; LinkedHashMap tendency = new LinkedHashMap<>(); - for(TrendsHistory _th : trendsHistory) { + for (TrendsHistory _th : trendsHistory) { people += _th.getAccounts(); - days ++; + days++; uses += _th.getUses(); tendency.put(_th.getDays(), _th.getUses()); } @@ -134,7 +132,7 @@ public class TrendsAdapter extends BaseAdapter { trendsEntry.add(0, new Entry((long) pair.getKey(), (int) pair.getValue())); it.remove(); } - LineDataSet dataTrending = new LineDataSet(trendsEntry,context.getString(R.string.trending)); + LineDataSet dataTrending = new LineDataSet(trendsEntry, context.getString(R.string.trending)); dataTrending.setColor(ContextCompat.getColor(context, R.color.cyanea_accent_reference)); dataTrending.setValueTextColor(ContextCompat.getColor(context, R.color.cyanea_accent_reference)); dataTrending.setFillColor(ContextCompat.getColor(context, R.color.cyanea_accent_reference)); @@ -162,7 +160,6 @@ public class TrendsAdapter extends BaseAdapter { } - private static class ViewHolderTag { LinearLayout trends_container; TextView tag_name; diff --git a/app/src/main/java/app/fedilab/android/fragments/ColorSettingsFragment.java b/app/src/main/java/app/fedilab/android/fragments/ColorSettingsFragment.java index fcdb5b398..67dec1997 100644 --- a/app/src/main/java/app/fedilab/android/fragments/ColorSettingsFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/ColorSettingsFragment.java @@ -176,14 +176,14 @@ public class ColorSettingsFragment extends PreferenceFragmentCompat implements S if (key.compareTo("base_theme") == 0) { SharedPreferences sharedpreferences = getActivity().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); SharedPreferences.Editor appEditor = sharedpreferences.edit(); - if( value != null && value.matches("-?\\d+")) { + if (value != null && value.matches("-?\\d+")) { appEditor.putInt(Helper.SET_THEME, Integer.parseInt(value)); } appEditor.commit(); } else if (key.compareTo("pref_color_navigation_bar") == 0 || key.compareTo("pref_color_status_bar") == 0) { editor.putBoolean(key, Boolean.parseBoolean(value)); } else { - if( value != null && value.matches("-?\\d+")) { + if (value != null && value.matches("-?\\d+")) { editor.putInt(key, Integer.parseInt(value)); } } @@ -248,7 +248,7 @@ public class ColorSettingsFragment extends PreferenceFragmentCompat implements S PreferenceScreen preferenceScreen = getPreferenceScreen(); FragmentActivity context = getActivity(); assert context != null; - if( preferenceScreen == null){ + if (preferenceScreen == null) { Toasty.error(getActivity(), getString(R.string.toast_error), Toasty.LENGTH_SHORT).show(); return; } @@ -269,7 +269,7 @@ public class ColorSettingsFragment extends PreferenceFragmentCompat implements S Preference pref_import = findPreference("pref_import"); Preference pref_export = findPreference("pref_export"); Preference reset_pref = findPreference("reset_pref"); - if (!sharedpreferences.getBoolean("use_custom_theme", false) ) { + if (!sharedpreferences.getBoolean("use_custom_theme", false)) { preferenceScreen.removePreference(theme_link_color); preferenceScreen.removePreference(theme_boost_header_color); preferenceScreen.removePreference(theme_text_header_1_line); diff --git a/app/src/main/java/app/fedilab/android/fragments/ContentSettingsFragment.java b/app/src/main/java/app/fedilab/android/fragments/ContentSettingsFragment.java index 24d8d1171..7bd19e25e 100644 --- a/app/src/main/java/app/fedilab/android/fragments/ContentSettingsFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/ContentSettingsFragment.java @@ -923,7 +923,6 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot }); - TextView set_user_agent = rootView.findViewById(R.id.set_user_agent); String user_agent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, null); @@ -934,9 +933,11 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot @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) { SharedPreferences.Editor editor = sharedpreferences.edit(); @@ -1368,7 +1369,7 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot notification_container.setVisibility(View.VISIBLE); notification_container.setVisibility(View.VISIBLE); Helper.startStreaming(context); - }else { + } else { context.sendBroadcast(new Intent(context, StopLiveNotificationReceiver.class)); context.sendBroadcast(new Intent(context, StopDelayedNotificationReceiver.class)); ApplicationJob.cancelAllJob(NotificationsSyncJob.NOTIFICATION_REFRESH); 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 7e16fde85..a23122f39 100644 --- a/app/src/main/java/app/fedilab/android/fragments/DisplayNotificationsFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/DisplayNotificationsFragment.java @@ -36,7 +36,9 @@ import androidx.localbroadcastmanager.content.LocalBroadcastManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; + import org.jetbrains.annotations.NotNull; + import java.util.ArrayList; import java.util.List; 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 075809407..ca1d8a010 100644 --- a/app/src/main/java/app/fedilab/android/fragments/DisplayStatusFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/DisplayStatusFragment.java @@ -41,7 +41,6 @@ import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; - import com.bumptech.glide.Glide; import com.bumptech.glide.ListPreloader; import com.bumptech.glide.RequestBuilder; @@ -143,8 +142,6 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn } - - @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_status, container, false); @@ -208,7 +205,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn new FixedPreloadSizeProvider(640, 480); ListPreloader.PreloadModelProvider modelProvider = new MyPreloadModelProvider(); RecyclerViewPreloader preloader = - new RecyclerViewPreloader<>(Glide.with(context), modelProvider, sizeProvider, 20 ); + new RecyclerViewPreloader<>(Glide.with(context), modelProvider, sizeProvider, 20); lv_status.addOnScrollListener(preloader); mainLoader = rootView.findViewById(R.id.loader); @@ -388,7 +385,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn } }); - }else if(instanceType.equals("PEERTUBE")){ + } else if (instanceType.equals("PEERTUBE")) { swipeRefreshLayout.setOnRefreshListener(() -> { if (peertubes.size() > 0) { int size = peertubes.size(); @@ -404,7 +401,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn } } }); - }else { + } else { swipeRefreshLayout.setOnRefreshListener(() -> { if (statuses.size() > 0) { int size = statuses.size(); @@ -555,7 +552,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn } flag_loading = false; firstLoad = false; - }else if (instanceType.equals("NITTER")) { + } else if (instanceType.equals("NITTER")) { int previousPosition = this.statuses.size(); //max_id needs to work like an offset this.statuses.addAll(apiResponse.getStatuses()); @@ -647,7 +644,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn } //Let's deal with statuses if (statuses != null && statuses.size() > 0) { - if (statusListAdapter != null && (instanceType.equals("MASTODON") || instanceType.equals("MISSKEY") || instanceType.equals("GNU"))) { + 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")) { @@ -897,7 +894,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn public void scrollToTop() { - if( mLayoutManager != null ) { + if (mLayoutManager != null) { mLayoutManager.scrollToPositionWithOffset(0, 0); } } @@ -1152,7 +1149,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn if (context instanceof BaseMainActivity) { boolean remember_position_home = sharedpreferences.getBoolean(Helper.SET_REMEMBER_POSITION_HOME, true); if (remember_position_home) - asyncTask = new RetrieveFeedsAsyncTask(context, type, initialBookMark, true,DisplayStatusFragment.this).execute(); + asyncTask = new RetrieveFeedsAsyncTask(context, type, initialBookMark, true, DisplayStatusFragment.this).execute(); else asyncTask = new RetrieveFeedsAsyncTask(context, type, null, DisplayStatusFragment.this).execute(); } @@ -1179,7 +1176,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn return; } if (apiResponse.getError() != null) { - if (!apiResponse.getError().getError().startsWith("404 -")&&!apiResponse.getError().getError().startsWith("501 -")) + if (!apiResponse.getError().getError().startsWith("404 -") && !apiResponse.getError().getError().startsWith("501 -")) if (apiResponse.getError().getError().length() < 100) { Toasty.error(context, apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); } else { @@ -1269,18 +1266,18 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn @Override @NonNull public List getPreloadItems(int position) { - if( statuses == null || statuses.size() == 0){ + if (statuses == null || statuses.size() == 0) { return Collections.emptyList(); } Status status = statuses.get(position); - if (status.getMedia_attachments() == null || status.getMedia_attachments().size() ==0) { + if (status.getMedia_attachments() == null || status.getMedia_attachments().size() == 0) { return Collections.emptyList(); } List preloaded_urls = new ArrayList<>(); - for(Attachment attachment: status.getMedia_attachments()) { + for (Attachment attachment : status.getMedia_attachments()) { preloaded_urls.add(attachment.getPreview_url()); } - return preloaded_urls; + return preloaded_urls; } @Nullable diff --git a/app/src/main/java/app/fedilab/android/fragments/DisplayStoriesFragment.java b/app/src/main/java/app/fedilab/android/fragments/DisplayStoriesFragment.java index e40027e03..b1983997b 100644 --- a/app/src/main/java/app/fedilab/android/fragments/DisplayStoriesFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/DisplayStoriesFragment.java @@ -48,7 +48,6 @@ import app.fedilab.android.interfaces.OnRetrieveStoriesInterface; import es.dmoral.toasty.Toasty; - /** * Created by Thomas on 02/11/2019. * Fragment to display PixelfFed Stories @@ -56,6 +55,7 @@ import es.dmoral.toasty.Toasty; public class DisplayStoriesFragment extends Fragment implements OnRetrieveStoriesInterface { + LinearLayoutManager mLayoutManager; private boolean flag_loading; private Context context; private AsyncTask asyncTask; @@ -67,15 +67,12 @@ public class DisplayStoriesFragment extends Fragment implements OnRetrieveStorie private SwipeRefreshLayout swipeRefreshLayout; private boolean swiped; private RecyclerView lv_stories; - LinearLayoutManager mLayoutManager; private RetrieveStoriesAsyncTask.type type; public DisplayStoriesFragment() { } - - @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { @@ -113,7 +110,7 @@ public class DisplayStoriesFragment extends Fragment implements OnRetrieveStorie if (firstVisibleItem + visibleItemCount == totalItemCount && context != null) { if (!flag_loading) { flag_loading = true; - asyncTask = new RetrieveStoriesAsyncTask(context, max_id, type,DisplayStoriesFragment.this).execute(); + asyncTask = new RetrieveStoriesAsyncTask(context, max_id, type, DisplayStoriesFragment.this).execute(); nextElementLoader.setVisibility(View.VISIBLE); } } else { @@ -124,7 +121,6 @@ public class DisplayStoriesFragment extends Fragment implements OnRetrieveStorie }); - swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { @@ -134,7 +130,7 @@ public class DisplayStoriesFragment extends Fragment implements OnRetrieveStorie if (pixelFedStories != null && pixelFedStories.size() > 0) sinceId = pixelFedStories.get(0).getId(); if (context != null) - asyncTask = new RetrieveStoriesAsyncTask(context, null, type,DisplayStoriesFragment.this).execute(); + asyncTask = new RetrieveStoriesAsyncTask(context, null, type, DisplayStoriesFragment.this).execute(); } }); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); @@ -160,13 +156,13 @@ public class DisplayStoriesFragment extends Fragment implements OnRetrieveStorie break; } if (context != null) - asyncTask = new RetrieveStoriesAsyncTask(context, max_id, type,DisplayStoriesFragment.this).execute(); + asyncTask = new RetrieveStoriesAsyncTask(context, max_id, type, DisplayStoriesFragment.this).execute(); else new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { if (context != null) - asyncTask = new RetrieveStoriesAsyncTask(context, max_id, type,DisplayStoriesFragment.this).execute(); + asyncTask = new RetrieveStoriesAsyncTask(context, max_id, type, DisplayStoriesFragment.this).execute(); } }, 500); return rootView; @@ -180,10 +176,10 @@ public class DisplayStoriesFragment extends Fragment implements OnRetrieveStorie if (apiResponse.getError() != null) { - if(apiResponse.getError().getError().length() < 100) { + if (apiResponse.getError().getError().length() < 100) { Toasty.error(context, apiResponse.getError().getError(), Toast.LENGTH_LONG).show(); - }else{ - Toasty.error(context, getString(R.string.long_api_error,"\ud83d\ude05"), Toast.LENGTH_LONG).show(); + } else { + Toasty.error(context, getString(R.string.long_api_error, "\ud83d\ude05"), Toast.LENGTH_LONG).show(); } flag_loading = false; swipeRefreshLayout.setRefreshing(false); @@ -277,7 +273,7 @@ public class DisplayStoriesFragment extends Fragment implements OnRetrieveStorie * @param sinceId String */ void retrieveMissingNotifications(String sinceId) { - asyncTask = new RetrieveStoriesAsyncTask(context, null, type,DisplayStoriesFragment.this).execute(); + asyncTask = new RetrieveStoriesAsyncTask(context, null, type, DisplayStoriesFragment.this).execute(); } @Override @@ -297,6 +293,4 @@ public class DisplayStoriesFragment extends Fragment implements OnRetrieveStorie } - - } diff --git a/app/src/main/java/app/fedilab/android/fragments/MediaSliderFragment.java b/app/src/main/java/app/fedilab/android/fragments/MediaSliderFragment.java index 99005b9ae..78b537ee4 100644 --- a/app/src/main/java/app/fedilab/android/fragments/MediaSliderFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/MediaSliderFragment.java @@ -295,7 +295,7 @@ public class MediaSliderFragment extends Fragment implements MediaPlayer.OnCompl webview_video.getSettings().setDomStorageEnabled(true); webview_video.getSettings().setAppCacheEnabled(true); String user_agent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, null); - if( user_agent != null) { + if (user_agent != null) { webview_video.getSettings().setUserAgentString(user_agent); } webview_video.getSettings().setMediaPlaybackRequiresUserGesture(false); 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 4ae70fa2d..49c67216f 100644 --- a/app/src/main/java/app/fedilab/android/fragments/TabLayoutNotificationsFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/TabLayoutNotificationsFragment.java @@ -210,7 +210,7 @@ public class TabLayoutNotificationsFragment extends Fragment { int mNumOfTabs; private PagerAdapter(FragmentManager fm, int NumOfTabs) { - super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT); + super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT); this.mNumOfTabs = NumOfTabs; } 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 506699440..f462ad056 100644 --- a/app/src/main/java/app/fedilab/android/fragments/TabLayoutScheduleFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/TabLayoutScheduleFragment.java @@ -86,7 +86,7 @@ public class TabLayoutScheduleFragment extends Fragment { int mNumOfTabs; private PagerAdapter(FragmentManager fm, int NumOfTabs) { - super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT); + super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT); this.mNumOfTabs = NumOfTabs; } 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 ec28f530f..cd6fe6a77 100644 --- a/app/src/main/java/app/fedilab/android/fragments/TabLayoutTootsFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/TabLayoutTootsFragment.java @@ -101,7 +101,7 @@ public class TabLayoutTootsFragment extends Fragment { int mNumOfTabs; private PagerAdapter(FragmentManager fm, int NumOfTabs) { - super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT); + super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT); this.mNumOfTabs = NumOfTabs; } 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 fe150bb5e..4d624df02 100644 --- a/app/src/main/java/app/fedilab/android/helper/CrossActions.java +++ b/app/src/main/java/app/fedilab/android/helper/CrossActions.java @@ -106,7 +106,7 @@ public class CrossActions { 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")|| account.getSocial().equals("FRIENDICA")) + if (account.getSocial() == null || account.getSocial().equals("MASTODON") || account.getSocial().equals("PLEROMA") || account.getSocial().equals("FRIENDICA")) accounts.add(account); } } @@ -341,9 +341,9 @@ public class CrossActions { url = "https://" + remoteAccount.getInstance() + "/@" + remoteAccount.getAcct(); } APIResponse apiResponse; - if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { GNUAPI api = new GNUAPI(contextReference.get(), account.getInstance(), account.getToken()); - apiResponse = api.search(remoteAccount.getAcct()+"@"+remoteAccount.getInstance()); + apiResponse = api.search(remoteAccount.getAcct() + "@" + remoteAccount.getInstance()); } else { API api = new API(contextReference.get(), account.getInstance(), account.getToken()); apiResponse = api.search2(url, null, null); @@ -426,7 +426,7 @@ public class CrossActions { protected Void doInBackground(Void... voids) { APIResponse apiResponse; - if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { GNUAPI api = new GNUAPI(contextReference.get(), account.getInstance(), account.getToken()); apiResponse = api.search2(remoteStatus.getUrl()); } else { @@ -643,7 +643,6 @@ public class CrossActions { protected Void doInBackground(Void... voids) { - String uri; if (status.getReblog() != null) { if (status.getReblog().getUri().startsWith("http")) @@ -656,13 +655,13 @@ public class CrossActions { else uri = status.getUrl(); } - if( account.getSocial().compareTo("FRIENDICA") != 0 ) { + if (account.getSocial().compareTo("FRIENDICA") != 0) { API api = new API(contextReference.get(), account.getInstance(), account.getToken()); APIResponse search = api.search(uri); if (search != null && search.getResults() != null) { remoteStatuses = search.getResults().getStatuses(); } - }else{ + } else { GNUAPI api = new GNUAPI(contextReference.get(), account.getInstance(), account.getToken()); APIResponse search = api.search2(uri); if (search != null && search.getResults() != null) { diff --git a/app/src/main/java/app/fedilab/android/helper/Helper.java b/app/src/main/java/app/fedilab/android/helper/Helper.java index 74cd0cd01..7ad3bd640 100644 --- a/app/src/main/java/app/fedilab/android/helper/Helper.java +++ b/app/src/main/java/app/fedilab/android/helper/Helper.java @@ -58,7 +58,6 @@ import android.os.Build; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Environment; -import android.os.Looper; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.provider.OpenableColumns; @@ -184,7 +183,6 @@ import java.util.Map; import java.util.Objects; import java.util.Random; import java.util.TimeZone; -import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -2467,9 +2465,9 @@ public class Helper { public static CustomWebview initializeWebview(Activity activity, int webviewId, View rootView) { CustomWebview webView; - if( rootView == null) { + if (rootView == null) { webView = activity.findViewById(webviewId); - }else{ + } else { webView = rootView.findViewById(webviewId); } final SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); @@ -2486,7 +2484,7 @@ public class Helper { webView.getSettings().setSupportMultipleWindows(false); webView.getSettings().setMediaPlaybackRequiresUserGesture(true); String user_agent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, null); - if( user_agent != null) { + if (user_agent != null) { webView.getSettings().setUserAgentString(user_agent); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { @@ -3160,7 +3158,7 @@ public class Helper { 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) { - if( social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA && social != UpdateAccountInfoAsyncTask.SOCIAL.GNU) { + if (social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA && social != UpdateAccountInfoAsyncTask.SOCIAL.GNU) { if (account.isLocked()) { if (navigationView.getMenu().findItem(R.id.nav_follow_request) != null) navigationView.getMenu().findItem(R.id.nav_follow_request).setVisible(true); @@ -4143,7 +4141,7 @@ public class Helper { String cleaned_content = original_content; final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); boolean utm_parameters = sharedpreferences.getBoolean(Helper.SET_FILTER_UTM, true); - if( utm_parameters ) { + if (utm_parameters) { 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._-]*", ""); @@ -4258,10 +4256,11 @@ public class Helper { /** * Download from Glid cache + * * @param context * @param url */ - public static void manageMove(Context context, String url, boolean share){ + public static void manageMove(Context context, String url, boolean share) { Glide.with(context) .asFile() .load(url) @@ -4275,11 +4274,12 @@ public class Helper { /** * Notify after moving a file from Glide cache + * * @param context * @param url * @param sourceFile */ - private static void notifyDownload(Context context, String url, File sourceFile, boolean share){ + private static void notifyDownload(Context context, String url, File sourceFile, boolean share) { final String fileName = URLUtil.guessFileName(url, null, null); final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); @@ -4289,9 +4289,8 @@ public class Helper { FileOutputStream fos = null; FileChannel in = null; FileChannel out = null; - try - { - File backupFile = new File(targeted_folder+"/"+fileName); + try { + File backupFile = new File(targeted_folder + "/" + fileName); backupFile.createNewFile(); fis = new FileInputStream(sourceFile); fos = new FileOutputStream(backupFile); @@ -4324,25 +4323,28 @@ public class Helper { } } catch (Throwable e) { e.printStackTrace(); - } - finally { + } finally { try { if (fis != null) fis.close(); - } catch (Throwable ignore) {} + } catch (Throwable ignore) { + } try { if (fos != null) fos.close(); - } catch (Throwable ignore) {} + } catch (Throwable ignore) { + } try { if (in != null && in.isOpen()) in.close(); - } catch (Throwable ignore) {} + } catch (Throwable ignore) { + } try { if (out != null && out.isOpen()) out.close(); - } catch (Throwable ignore) {} + } catch (Throwable ignore) { + } } } @@ -4386,7 +4388,7 @@ public class Helper { public static OkHttpClient getHttpClient(Context context) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); boolean proxyEnabled = sharedpreferences.getBoolean(Helper.SET_PROXY_ENABLED, false); - int cacheSize = 30*1024*1024; + int cacheSize = 30 * 1024 * 1024; Cache cache = new Cache(context.getCacheDir(), cacheSize); OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder() .followRedirects(true) @@ -4716,7 +4718,8 @@ public class Helper { } else { context.startService(streamingIntent); } - } catch (Exception ignored) {} + } catch (Exception ignored) { + } } } @@ -4763,6 +4766,13 @@ public class Helper { return socialNetwork; } + public static Thread getThreadByName(String threadName) { + for (Thread t : Thread.getAllStackTraces().keySet()) { + if (t.getName().equals(threadName)) return t; + } + return null; + } + //Event Type public enum EventStreaming { UPDATE, @@ -4771,6 +4781,7 @@ public class Helper { NONE } + public enum NotifType { FOLLLOW, MENTION, @@ -4782,7 +4793,6 @@ public class Helper { TOOT } - public enum MediaType { MEDIA, PROFILE @@ -4883,12 +4893,4 @@ public class Helper { .show(); } } - - - public static Thread getThreadByName(String threadName) { - for (Thread t : Thread.getAllStackTraces().keySet()) { - if (t.getName().equals(threadName)) return t; - } - return null; - } } diff --git a/app/src/main/java/app/fedilab/android/helper/LongClickLinkMovementMethod.java b/app/src/main/java/app/fedilab/android/helper/LongClickLinkMovementMethod.java index 1097af0d4..cd29cac7e 100644 --- a/app/src/main/java/app/fedilab/android/helper/LongClickLinkMovementMethod.java +++ b/app/src/main/java/app/fedilab/android/helper/LongClickLinkMovementMethod.java @@ -14,17 +14,26 @@ import android.widget.TextView; //https://stackoverflow.com/a/20435892 public class LongClickLinkMovementMethod extends LinkMovementMethod { - private Handler mLongClickHandler; private static int LONG_CLICK_TIME = 1000; + private static LongClickLinkMovementMethod sInstance; + private Handler mLongClickHandler; private boolean mIsLongPressed = false; + public static MovementMethod getInstance() { + if (sInstance == null) { + sInstance = new LongClickLinkMovementMethod(); + sInstance.mLongClickHandler = new Handler(); + } + + return sInstance; + } @Override public boolean onTouchEvent(final TextView widget, Spannable buffer, MotionEvent event) { int action = event.getAction(); - if(action == MotionEvent.ACTION_CANCEL){ - if(mLongClickHandler!=null){ + if (action == MotionEvent.ACTION_CANCEL) { + if (mLongClickHandler != null) { mLongClickHandler.removeCallbacksAndMessages(null); } } @@ -48,10 +57,10 @@ public class LongClickLinkMovementMethod extends LinkMovementMethod { if (link.length != 0) { if (action == MotionEvent.ACTION_UP) { - if(mLongClickHandler!=null){ + if (mLongClickHandler != null) { mLongClickHandler.removeCallbacksAndMessages(null); } - if(!mIsLongPressed) { + if (!mIsLongPressed) { link[0].onClick(widget); } mIsLongPressed = false; @@ -66,7 +75,7 @@ public class LongClickLinkMovementMethod extends LinkMovementMethod { mIsLongPressed = true; widget.invalidate(); } - },LONG_CLICK_TIME); + }, LONG_CLICK_TIME); } return true; } @@ -76,15 +85,4 @@ public class LongClickLinkMovementMethod extends LinkMovementMethod { } - public static MovementMethod getInstance() { - if (sInstance == null) { - sInstance = new LongClickLinkMovementMethod(); - sInstance.mLongClickHandler = new Handler(); - } - - return sInstance; - } - private static LongClickLinkMovementMethod sInstance; - - } \ No newline at end of file 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 540982721..a1716de69 100644 --- a/app/src/main/java/app/fedilab/android/jobs/NotificationsSyncJob.java +++ b/app/src/main/java/app/fedilab/android/jobs/NotificationsSyncJob.java @@ -141,10 +141,10 @@ public class NotificationsSyncJob extends Job { //Retrieve users in db that owner has. for (Account account : accounts) { APIResponse apiResponse; - if(account.getSocial().compareTo("FRIENDICA") != 0 && account.getSocial().compareTo("GNU") != 0 ) { + if (account.getSocial().compareTo("FRIENDICA") != 0 && account.getSocial().compareTo("GNU") != 0) { API api = new API(getContext(), account.getInstance(), account.getToken()); apiResponse = api.getNotificationsSince(DisplayNotificationsFragment.Type.ALL, null, false); - }else{ + } else { GNUAPI gnuApi = new GNUAPI(getContext(), account.getInstance(), account.getToken()); apiResponse = gnuApi.getNotificationsSince(DisplayNotificationsFragment.Type.ALL, null, false); } diff --git a/app/src/main/java/app/fedilab/android/services/LiveNotificationDelayedService.java b/app/src/main/java/app/fedilab/android/services/LiveNotificationDelayedService.java index 959f754e0..b77e14938 100644 --- a/app/src/main/java/app/fedilab/android/services/LiveNotificationDelayedService.java +++ b/app/src/main/java/app/fedilab/android/services/LiveNotificationDelayedService.java @@ -102,7 +102,7 @@ public class LiveNotificationDelayedService extends Service { SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); List accountStreams = new AccountDAO(getApplicationContext(), db).getAllAccountCrossAction(); totalAccount = 0; - if( accountStreams != null) { + if (accountStreams != null) { for (Account account : accountStreams) { boolean allowStream = sharedpreferences.getBoolean(Helper.SET_ALLOW_STREAM + account.getId() + account.getInstance(), true); if (allowStream) { @@ -129,7 +129,7 @@ public class LiveNotificationDelayedService extends Service { } - if( !notify ){ + if (!notify) { stopSelf(); return; } @@ -146,7 +146,7 @@ public class LiveNotificationDelayedService extends Service { public void onDestroy() { super.onDestroy(); for (Thread t : Thread.getAllStackTraces().keySet()) { - if (t.getName().startsWith("notif_delayed_")){ + if (t.getName().startsWith("notif_delayed_")) { t.interrupt(); } } @@ -154,7 +154,6 @@ public class LiveNotificationDelayedService extends Service { } - @Override public int onStartCommand(Intent intent, int flags, int startId) { final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); @@ -163,7 +162,7 @@ public class LiveNotificationDelayedService extends Service { totalAccount = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { stopForeground(STOP_FOREGROUND_DETACH); - NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); assert notificationManager != null; notificationManager.deleteNotificationChannel(CHANNEL_ID); } @@ -196,10 +195,10 @@ public class LiveNotificationDelayedService extends Service { if (!sleeps.containsKey(key)) { sleeps.put(key, 30000); } - Thread thread = Helper.getThreadByName("notif_delayed_"+key); - if( thread == null){ + Thread thread = Helper.getThreadByName("notif_delayed_" + key); + if (thread == null) { startThread(accountStream, key); - } else if(thread.getState() != Thread.State.RUNNABLE) { + } else if (thread.getState() != Thread.State.RUNNABLE) { thread.interrupt(); startThread(accountStream, key); } @@ -208,7 +207,7 @@ public class LiveNotificationDelayedService extends Service { } } - private void startThread(Account accountStream, String key){ + private void startThread(Account accountStream, String key) { Thread thread = new Thread() { @Override public void run() { @@ -225,7 +224,7 @@ public class LiveNotificationDelayedService extends Service { } } }; - thread.setName("notif_delayed_"+key); + thread.setName("notif_delayed_" + key); thread.start(); } @@ -246,11 +245,11 @@ public class LiveNotificationDelayedService extends Service { } apiResponse = null; try { - if(account.getSocial().compareTo("FRIENDICA") != 0 && account.getSocial().compareTo("GNU") != 0 ) { + if (account.getSocial().compareTo("FRIENDICA") != 0 && account.getSocial().compareTo("GNU") != 0) { API api; api = new API(getApplicationContext(), account.getInstance(), account.getToken()); apiResponse = api.getNotificationsSince(DisplayNotificationsFragment.Type.ALL, last_notifid, false); - }else{ + } else { GNUAPI gnuApi; gnuApi = new GNUAPI(getApplicationContext(), account.getInstance(), account.getToken()); apiResponse = gnuApi.getNotificationsSince(DisplayNotificationsFragment.Type.ALL, last_notifid, false); 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 76e18bd7f..1107092dd 100644 --- a/app/src/main/java/app/fedilab/android/services/LiveNotificationService.java +++ b/app/src/main/java/app/fedilab/android/services/LiveNotificationService.java @@ -120,7 +120,7 @@ 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; - if( accountStreams != null) { + if (accountStreams != null) { for (Account account : accountStreams) { if (account.getSocial() == null || account.getSocial().equals("MASTODON") || account.getSocial().equals("PLEROMA")) { boolean allowStream = sharedpreferences.getBoolean(Helper.SET_ALLOW_STREAM + account.getId() + account.getInstance(), true); @@ -145,7 +145,7 @@ public class LiveNotificationService extends Service implements NetworkStateRece startForeground(1, notification); } - if( !notify ){ + if (!notify) { stopSelf(); return; } @@ -179,7 +179,7 @@ public class LiveNotificationService extends Service implements NetworkStateRece totalAccount = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { stopForeground(STOP_FOREGROUND_DETACH); - NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); assert notificationManager != null; notificationManager.deleteNotificationChannel(CHANNEL_ID); } @@ -198,13 +198,13 @@ public class LiveNotificationService extends Service implements NetworkStateRece public void onDestroy() { super.onDestroy(); for (Thread t : Thread.getAllStackTraces().keySet()) { - if (t.getName().startsWith("notif_live_")){ + if (t.getName().startsWith("notif_live_")) { t.interrupt(); t = null; - }; + } } Thread.currentThread().interrupt(); - if( networkStateReceiver != null) { + if (networkStateReceiver != null) { networkStateReceiver.removeListener(this); unregisterReceiver(networkStateReceiver); } @@ -283,17 +283,17 @@ public class LiveNotificationService extends Service implements NetworkStateRece private void startWork(Account accountStream) { String key = accountStream.getAcct() + "@" + accountStream.getInstance(); - Thread thread = Helper.getThreadByName("notif_live_"+key); - if( thread == null){ + Thread thread = Helper.getThreadByName("notif_live_" + key); + if (thread == null) { thread = new Thread() { @Override public void run() { taks(accountStream); } }; - thread.setName("notif_live_"+key); + thread.setName("notif_live_" + key); thread.start(); - } else if(thread.getState() != Thread.State.RUNNABLE) { + } else if (thread.getState() != Thread.State.RUNNABLE) { thread.interrupt(); thread = new Thread() { @Override @@ -301,7 +301,7 @@ public class LiveNotificationService extends Service implements NetworkStateRece taks(accountStream); } }; - thread.setName("notif_live_"+key); + thread.setName("notif_live_" + key); thread.start(); } @@ -534,10 +534,10 @@ public class LiveNotificationService extends Service implements NetworkStateRece @Override public void networkUnavailable() { for (Thread t : Thread.getAllStackTraces().keySet()) { - if (t.getName().startsWith("notif_live_")){ + if (t.getName().startsWith("notif_live_")) { t.interrupt(); t = null; - }; + } } Thread.currentThread().interrupt(); } 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 7435c9a29..79b158306 100644 --- a/app/src/main/java/app/fedilab/android/services/RestartLiveNotificationReceiver.java +++ b/app/src/main/java/app/fedilab/android/services/RestartLiveNotificationReceiver.java @@ -46,7 +46,7 @@ public class RestartLiveNotificationReceiver extends BroadcastReceiver { context.startService(streamingServiceIntent); } catch (Exception ignored) { } - }else{ + } else { NotificationsSyncJob.schedule(false); } } diff --git a/app/src/main/java/app/fedilab/android/services/StopDelayedNotificationReceiver.java b/app/src/main/java/app/fedilab/android/services/StopDelayedNotificationReceiver.java index 5a473fb10..800456da7 100644 --- a/app/src/main/java/app/fedilab/android/services/StopDelayedNotificationReceiver.java +++ b/app/src/main/java/app/fedilab/android/services/StopDelayedNotificationReceiver.java @@ -34,7 +34,8 @@ public class StopDelayedNotificationReceiver extends BroadcastReceiver { 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/StopLiveNotificationReceiver.java b/app/src/main/java/app/fedilab/android/services/StopLiveNotificationReceiver.java index 5131890d7..083bb4ff7 100644 --- a/app/src/main/java/app/fedilab/android/services/StopLiveNotificationReceiver.java +++ b/app/src/main/java/app/fedilab/android/services/StopLiveNotificationReceiver.java @@ -20,7 +20,6 @@ import android.content.Context; import android.content.Intent; - /** * Created by Thomas on 22/09/2017. * BroadcastReceiver for restarting the service @@ -35,7 +34,8 @@ public class StopLiveNotificationReceiver extends BroadcastReceiver { 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 c6029da83..32915efa1 100644 --- a/app/src/main/java/app/fedilab/android/services/StreamingFederatedTimelineService.java +++ b/app/src/main/java/app/fedilab/android/services/StreamingFederatedTimelineService.java @@ -72,6 +72,7 @@ public class StreamingFederatedTimelineService extends IntentService { public StreamingFederatedTimelineService(String name) { super(name); } + @SuppressWarnings("unused") public StreamingFederatedTimelineService() { super("StreamingFederatedTimelineService"); 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 0dc3da46f..b52667d56 100644 --- a/app/src/main/java/app/fedilab/android/services/StreamingHomeTimelineService.java +++ b/app/src/main/java/app/fedilab/android/services/StreamingHomeTimelineService.java @@ -72,6 +72,7 @@ public class StreamingHomeTimelineService extends IntentService { public StreamingHomeTimelineService(String name) { super(name); } + @SuppressWarnings("unused") public StreamingHomeTimelineService() { super("StreamingHomeTimelineService"); 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 9eb313928..43f758511 100644 --- a/app/src/main/java/app/fedilab/android/services/StreamingLocalTimelineService.java +++ b/app/src/main/java/app/fedilab/android/services/StreamingLocalTimelineService.java @@ -72,6 +72,7 @@ public class StreamingLocalTimelineService extends IntentService { public StreamingLocalTimelineService(String name) { super(name); } + @SuppressWarnings("unused") public StreamingLocalTimelineService() { super("StreamingLocalTimelineService"); 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 fb7c92873..9c35dc2ee 100644 --- a/app/src/main/java/app/fedilab/android/sqlite/AccountDAO.java +++ b/app/src/main/java/app/fedilab/android/sqlite/AccountDAO.java @@ -255,7 +255,7 @@ public class AccountDAO { public List getAllAccountCrossAction() { try { - Cursor c = db.query(Sqlite.TABLE_USER_ACCOUNT, null, Sqlite.COL_SOCIAL + " != 'PEERTUBE' AND " + Sqlite.COL_SOCIAL + " != 'GNU' AND " +Sqlite.COL_OAUTHTOKEN + " != 'null'", null, null, null, Sqlite.COL_INSTANCE + " ASC", null); + Cursor c = db.query(Sqlite.TABLE_USER_ACCOUNT, null, Sqlite.COL_SOCIAL + " != 'PEERTUBE' AND " + Sqlite.COL_SOCIAL + " != 'GNU' AND " + Sqlite.COL_OAUTHTOKEN + " != 'null'", null, null, null, Sqlite.COL_INSTANCE + " ASC", null); return cursorToListUser(c); } catch (Exception e) { return null; 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 b29384b08..0412fb845 100644 --- a/app/src/main/java/app/fedilab/android/webview/MastalabWebViewClient.java +++ b/app/src/main/java/app/fedilab/android/webview/MastalabWebViewClient.java @@ -83,7 +83,7 @@ public class MastalabWebViewClient extends WebViewClient { } } catch (URISyntaxException e) { try { - if ( url.length() > 50) { + if (url.length() > 50) { url = url.substring(0, 50); } uri = new URI(url); 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 17ca8142c..cac5ae7dd 100644 --- a/app/src/main/java/app/fedilab/android/webview/ProxyHelper.java +++ b/app/src/main/java/app/fedilab/android/webview/ProxyHelper.java @@ -18,7 +18,6 @@ import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.net.Proxy; -import android.os.Build; import android.util.ArrayMap; import java.lang.reflect.Constructor;