diff --git a/app/build.gradle b/app/build.gradle index 7ba373c84..e187c9ba9 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -6,8 +6,8 @@ android { defaultConfig { minSdkVersion 19 targetSdkVersion 29 - versionCode 366 - versionName "2.35.3" + versionCode 368 + versionName "2.35.4" multiDexEnabled true renderscriptTargetApi 28 as int renderscriptSupportModeEnabled true @@ -87,7 +87,7 @@ dependencies { } annotationProcessor "com.github.bumptech.glide:compiler:4.11.0" annotationProcessor 'com.android.support:support-annotations:28.0.0' - implementation "org.conscrypt:conscrypt-android:2.2.1" + implementation "org.conscrypt:conscrypt-android:2.4.0" implementation "com.evernote:android-job:1.2.6" implementation "com.google.code.gson:gson:2.8.5" implementation "com.google.guava:guava:28.2-android" @@ -128,7 +128,7 @@ dependencies { implementation 'com.github.penfeizhou.android.animation:glide-plugin:2.2.0' implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0' implementation 'com.github.smarteist:autoimageslider:1.3.2' - debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.2' + //debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.2' implementation 'com.jaredrummler:cyanea:1.0.2' } diff --git a/app/src/main/assets/changelogs/367.txt b/app/src/main/assets/changelogs/367.txt new file mode 100644 index 000000000..31665cbe7 --- /dev/null +++ b/app/src/main/assets/changelogs/367.txt @@ -0,0 +1,13 @@ +Added: +- 100 Mb of cache for videos (can be changed in settings) +- Bibliogram support (default: disabled) +- Ouiches support for audio + +Changed: +- Closing media +- Smoother settings + +Fixed: +- Peertube comments +- Some layout issues +- Some other crashes \ No newline at end of file diff --git a/app/src/main/assets/changelogs/368.txt b/app/src/main/assets/changelogs/368.txt new file mode 100644 index 000000000..31665cbe7 --- /dev/null +++ b/app/src/main/assets/changelogs/368.txt @@ -0,0 +1,13 @@ +Added: +- 100 Mb of cache for videos (can be changed in settings) +- Bibliogram support (default: disabled) +- Ouiches support for audio + +Changed: +- Closing media +- Smoother settings + +Fixed: +- Peertube comments +- Some layout issues +- Some other crashes \ No newline at end of file diff --git a/app/src/main/java/app/fedilab/android/activities/AccountReportActivity.java b/app/src/main/java/app/fedilab/android/activities/AccountReportActivity.java index 97552b888..9fb9e16c4 100644 --- a/app/src/main/java/app/fedilab/android/activities/AccountReportActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/AccountReportActivity.java @@ -15,8 +15,8 @@ package app.fedilab.android.activities; * see . */ import android.app.Activity; -import android.app.AlertDialog; import android.content.Intent; +import android.content.SharedPreferences; import android.graphics.PorterDuff; import android.graphics.drawable.ColorDrawable; import android.os.AsyncTask; @@ -34,6 +34,7 @@ import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.ActionBar; +import androidx.appcompat.app.AlertDialog; import androidx.constraintlayout.widget.Group; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.LinearLayoutManager; @@ -175,8 +176,18 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction public void onAdminAction(APIResponse apiResponse) { if (apiResponse.getError() != null) { if (apiResponse.getError().getStatusCode() == 403) { + SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); + int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); + int style; + if (theme == Helper.THEME_DARK) { + style = R.style.DialogDark; + } else if (theme == Helper.THEME_BLACK) { + style = R.style.DialogBlack; + } else { + style = R.style.Dialog; + } AlertDialog.Builder builderInner; - builderInner = new AlertDialog.Builder(AccountReportActivity.this, R.style.AppThemeDark); + builderInner = new AlertDialog.Builder(AccountReportActivity.this, style); builderInner.setTitle(R.string.reconnect_account); builderInner.setMessage(R.string.reconnect_account_message); builderInner.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()); 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 3e97bb0a1..6ecb3e377 100644 --- a/app/src/main/java/app/fedilab/android/activities/BaseActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/BaseActivity.java @@ -52,7 +52,7 @@ public class BaseActivity extends CyaneaAppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { - if (BuildConfig.DEBUG) { + /*if (BuildConfig.DEBUG) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() @@ -67,7 +67,7 @@ public class BaseActivity extends CyaneaAppCompatActivity { .penaltyLog() // .penaltyDeath() .build()); - } + }*/ canShowActionMode = true; super.onCreate(savedInstanceState); diff --git a/app/src/main/java/app/fedilab/android/activities/BaseFragmentActivity.java b/app/src/main/java/app/fedilab/android/activities/BaseFragmentActivity.java new file mode 100644 index 000000000..a4a2f6b0f --- /dev/null +++ b/app/src/main/java/app/fedilab/android/activities/BaseFragmentActivity.java @@ -0,0 +1,26 @@ +package app.fedilab.android.activities; + +import android.annotation.SuppressLint; + +import androidx.appcompat.app.AppCompatActivity; + +import com.vanniktech.emoji.EmojiManager; +import com.vanniktech.emoji.one.EmojiOneProvider; + +import app.fedilab.android.helper.Helper; + +/** + * Created by Thomas on 16/05/2020. + * Fragment base activity which updates security provider + */ + +@SuppressLint("Registered") +public class BaseFragmentActivity extends AppCompatActivity { + + + static { + Helper.installProvider(); + EmojiManager.install(new EmojiOneProvider()); + } + +} 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 c1928b179..f22ff876b 100644 --- a/app/src/main/java/app/fedilab/android/activities/BaseMainActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/BaseMainActivity.java @@ -1258,7 +1258,7 @@ public abstract class BaseMainActivity extends BaseActivity int lastReleaseNoteRead = sharedpreferences.getInt(Helper.SET_POPUP_RELEASE_NOTES, 0); int versionCode = BuildConfig.VERSION_CODE; - if (lastReleaseNoteRead != versionCode ) { //Need to push release notes + if (lastReleaseNoteRead != versionCode) { //Need to push release notes if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { new RetrieveRemoteDataAsyncTask(BaseMainActivity.this, BaseMainActivity.this).execute(); } @@ -1279,12 +1279,12 @@ public abstract class BaseMainActivity extends BaseActivity Button liberapay_support = dialogReleaseNoteView.findViewById(R.id.liberapay_support); release_title.setText(getString(R.string.release_note_title, BuildConfig.VERSION_NAME)); release_notes.setText(finalContent); - if( BuildConfig.DONATIONS) { + if (BuildConfig.DONATIONS) { liberapay_support.setVisibility(View.VISIBLE); - }else{ + } else { liberapay_support.setVisibility(View.GONE); } - liberapay_support.setOnClickListener(v->{ + liberapay_support.setOnClickListener(v -> { Intent intentLiberapay = new Intent(Intent.ACTION_VIEW); intentLiberapay.setData(Uri.parse("https://liberapay.com/tom79")); try { @@ -1693,7 +1693,7 @@ public abstract class BaseMainActivity extends BaseActivity } }); } - if( trackingDomains != null){ + if (trackingDomains != null) { trackingDomains = null; } if (hidde_menu != null) 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 c188ecc4e..f05ad7b91 100644 --- a/app/src/main/java/app/fedilab/android/activities/PeertubeActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/PeertubeActivity.java @@ -60,10 +60,10 @@ import androidx.recyclerview.widget.RecyclerView; import com.google.android.exoplayer2.ExoPlayerFactory; import com.google.android.exoplayer2.SimpleExoPlayer; -import com.google.android.exoplayer2.source.ExtractorMediaSource; +import com.google.android.exoplayer2.source.ProgressiveMediaSource; import com.google.android.exoplayer2.ui.AspectRatioFrameLayout; -import com.google.android.exoplayer2.ui.PlaybackControlView; -import com.google.android.exoplayer2.ui.SimpleExoPlayerView; +import com.google.android.exoplayer2.ui.PlayerControlView; +import com.google.android.exoplayer2.ui.PlayerView; import com.google.android.exoplayer2.upstream.DataSource; import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory; import com.google.android.exoplayer2.util.Util; @@ -96,6 +96,7 @@ import app.fedilab.android.client.Entities.Status; import app.fedilab.android.client.Entities.StatusDrawerParams; import app.fedilab.android.client.TLSSocketFactory; import app.fedilab.android.drawers.StatusListAdapter; +import app.fedilab.android.helper.CacheDataSourceFactory; import app.fedilab.android.helper.CrossActions; import app.fedilab.android.helper.FullScreenMediaController; import app.fedilab.android.helper.Helper; @@ -130,7 +131,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube private ScrollView peertube_information_container; private Peertube peertube; private TextView toolbar_title; - private SimpleExoPlayerView playerView; + private PlayerView playerView; private SimpleExoPlayer player; private boolean fullScreenMode; private Dialog fullScreenDialog; @@ -278,10 +279,8 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube peertube_information_container.setVisibility(View.VISIBLE); } }); - String user_agent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, null); - if (user_agent != null) { - webview_video.getSettings().setUserAgentString(user_agent); - } + String user_agent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, Helper.USER_AGENT); + webview_video.getSettings().setUserAgentString(user_agent); webview_video.getSettings().setAllowFileAccess(true); webview_video.setWebChromeClient(mastalabWebChromeClient); webview_video.getSettings().setDomStorageEnabled(true); @@ -369,40 +368,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube case R.id.action_comment: if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { Toasty.info(PeertubeActivity.this, getString(R.string.retrieve_remote_status), Toast.LENGTH_LONG).show(); - new AsyncTask() { - - private List remoteStatuses; - private WeakReference contextReference = new WeakReference<>(PeertubeActivity.this); - - @Override - protected Void doInBackground(Void... voids) { - - if (peertube != null) { - APIResponse search = new API(contextReference.get()).search("https://" + peertube.getAccount().getHost() + "/videos/watch/" + peertube.getUuid()); - 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_SHORT).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 commentTask(new WeakReference<>(PeertubeActivity.this), peertube).execute(); } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { if (!peertube.isCommentsEnabled()) { Toasty.info(PeertubeActivity.this, getString(R.string.comment_no_allowed_peertube), Toast.LENGTH_LONG).show(); @@ -583,16 +549,24 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube if (mode == Helper.VIDEO_MODE_DIRECT) { - DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(PeertubeActivity.this, - Util.getUserAgent(PeertubeActivity.this, "Mastalab"), null); - ExtractorMediaSource videoSource = new ExtractorMediaSource.Factory(dataSourceFactory) - .createMediaSource(Uri.parse(apiResponse.getPeertubes().get(0).getFileUrl(null, apiResponse.getPeertubes().get(0).isStreamService()))); + String userAgent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, Helper.USER_AGENT); + int video_cache = sharedpreferences.getInt(Helper.SET_VIDEO_CACHE, Helper.DEFAULT_VIDEO_CACHE_MB); + ProgressiveMediaSource videoSource; + if (video_cache == 0) { + DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(PeertubeActivity.this, + Util.getUserAgent(PeertubeActivity.this, userAgent), null); + videoSource = new ProgressiveMediaSource.Factory(dataSourceFactory) + .createMediaSource(Uri.parse(apiResponse.getPeertubes().get(0).getFileUrl(null, apiResponse.getPeertubes().get(0).isStreamService()))); + } else { + CacheDataSourceFactory cacheDataSourceFactory = new CacheDataSourceFactory(PeertubeActivity.this); + videoSource = new ProgressiveMediaSource.Factory(cacheDataSourceFactory) + .createMediaSource(Uri.parse(apiResponse.getPeertubes().get(0).getFileUrl(null, apiResponse.getPeertubes().get(0).isStreamService()))); + } player = ExoPlayerFactory.newSimpleInstance(PeertubeActivity.this); playerView.setPlayer(player); loader.setVisibility(View.GONE); - player.prepare(videoSource); player.setPlayWhenReady(true); } @@ -662,7 +636,6 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube }); } - @Override public void onConfigurationChanged(@NotNull Configuration newConfig) { super.onConfigurationChanged(newConfig); @@ -745,7 +718,6 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube } } - @Override public void onResume() { super.onResume(); @@ -777,7 +749,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube if (playerView != null) { loader.setVisibility(View.VISIBLE); long position = player.getCurrentPosition(); - PlaybackControlView controlView = playerView.findViewById(R.id.exo_controller); + PlayerControlView controlView = playerView.findViewById(R.id.exo_controller); resolution = controlView.findViewById(R.id.resolution); resolution.setText(String.format("%sp", res)); if (mode == Helper.VIDEO_MODE_DIRECT) { @@ -786,11 +758,19 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube player = ExoPlayerFactory.newSimpleInstance(PeertubeActivity.this); playerView.setPlayer(player); loader.setVisibility(View.GONE); - DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(PeertubeActivity.this, - Util.getUserAgent(PeertubeActivity.this, "Mastalab"), null); - - ExtractorMediaSource videoSource = new ExtractorMediaSource.Factory(dataSourceFactory) - .createMediaSource(Uri.parse(peertube.getFileUrl(res, peertube.isStreamService()))); + String userAgent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, Helper.USER_AGENT); + int video_cache = sharedpreferences.getInt(Helper.SET_VIDEO_CACHE, Helper.DEFAULT_VIDEO_CACHE_MB); + ProgressiveMediaSource videoSource; + if (video_cache == 0) { + DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(PeertubeActivity.this, + Util.getUserAgent(PeertubeActivity.this, userAgent), null); + videoSource = new ProgressiveMediaSource.Factory(dataSourceFactory) + .createMediaSource(Uri.parse(peertube.getFileUrl(res, peertube.isStreamService()))); + } else { + CacheDataSourceFactory cacheDataSourceFactory = new CacheDataSourceFactory(PeertubeActivity.this); + videoSource = new ProgressiveMediaSource.Factory(cacheDataSourceFactory) + .createMediaSource(Uri.parse(peertube.getFileUrl(res, peertube.isStreamService()))); + } player.prepare(videoSource); player.seekTo(0, position); player.setPlayWhenReady(true); @@ -809,7 +789,6 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube } - private void initFullscreenDialog() { fullScreenDialog = new Dialog(this, android.R.style.Theme_Black_NoTitleBar_Fullscreen) { @@ -830,7 +809,6 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube fullScreenDialog.show(); } - private void closeFullscreenDialog() { ((ViewGroup) playerView.getParent()).removeView(playerView); @@ -842,7 +820,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube private void initFullscreenButton() { - PlaybackControlView controlView = playerView.findViewById(R.id.exo_controller); + PlayerControlView controlView = playerView.findViewById(R.id.exo_controller); fullScreenIcon = controlView.findViewById(R.id.exo_fullscreen_icon); View fullScreenButton = controlView.findViewById(R.id.exo_fullscreen_button); fullScreenButton.setOnClickListener(v -> { @@ -854,13 +832,12 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube } private void initResolution() { - PlaybackControlView controlView = playerView.findViewById(R.id.exo_controller); + PlayerControlView controlView = playerView.findViewById(R.id.exo_controller); resolution = controlView.findViewById(R.id.resolution); resolution.setText(String.format("%sp", peertube.getResolution().get(0))); resolution.setOnClickListener(v -> displayResolution()); } - private void changeColor() { if (peertube.getMyRating() != null && peertube.getMyRating().equals("like")) { changeDrawableColor(PeertubeActivity.this, R.drawable.ic_thumb_up_peertube, R.color.positive_thumbs); @@ -882,4 +859,49 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube playlists = apiResponse.getPlaylists(); } } + + private static class commentTask extends AsyncTask { + + private WeakReference contextReference; + private Peertube peertube; + + commentTask(WeakReference contextReference, Peertube peertube) { + this.peertube = peertube; + this.contextReference = contextReference; + } + + @Override + protected app.fedilab.android.client.Entities.Status doInBackground(Void... voids) { + + List remoteStatuses = null; + if (peertube != null) { + APIResponse search = new API(contextReference.get()).search("https://" + peertube.getAccount().getHost() + "/videos/watch/" + peertube.getUuid()); + if (search != null && search.getResults() != null) { + remoteStatuses = search.getResults().getStatuses(); + } + } + if (remoteStatuses != null && remoteStatuses.size() > 0) { + return remoteStatuses.get(0); + } else { + return null; + } + } + + @Override + protected void onPostExecute(app.fedilab.android.client.Entities.Status remoteStatuses) { + Intent intent = new Intent(contextReference.get(), TootActivity.class); + Bundle b = new Bundle(); + if (remoteStatuses == null) { + Toasty.error(contextReference.get(), contextReference.get().getString(R.string.toast_error), Toast.LENGTH_SHORT).show(); + return; + } + if (remoteStatuses.getReblog() != null) { + b.putParcelable("tootReply", remoteStatuses.getReblog()); + } else { + b.putParcelable("tootReply", remoteStatuses); + } + intent.putExtras(b); + contextReference.get().startActivity(intent); + } + } } diff --git a/app/src/main/java/app/fedilab/android/activities/PeertubeEditUploadActivity.java b/app/src/main/java/app/fedilab/android/activities/PeertubeEditUploadActivity.java index 6caa20a5c..44810105d 100644 --- a/app/src/main/java/app/fedilab/android/activities/PeertubeEditUploadActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/PeertubeEditUploadActivity.java @@ -80,6 +80,7 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie private String videoId; private Account channel; + @SuppressWarnings("SuspiciousMethodCalls") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -539,6 +540,7 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie List tags = peertube.getTags(); if (tags != null && tags.size() > 0) { + //noinspection ToArrayCallWithZeroLengthArrayArgument String[] tagsA = tags.toArray(new String[tags.size()]); p_video_tags.setTags(tagsA); } 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 687fda9da..05e9ed813 100644 --- a/app/src/main/java/app/fedilab/android/activities/PeertubeUploadActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/PeertubeUploadActivity.java @@ -16,6 +16,7 @@ package app.fedilab.android.activities; import android.Manifest; +import android.annotation.SuppressLint; import android.app.Activity; import android.app.PendingIntent; import android.content.Context; @@ -193,6 +194,7 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe } + @SuppressWarnings("SuspiciousMethodCalls") @Override public void onRetrievePeertubeChannels(APIResponse apiResponse) { if (apiResponse.getError() != null || apiResponse.getAccounts() == null || apiResponse.getAccounts().size() == 0) { @@ -277,32 +279,29 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe }); set_upload_file.setEnabled(true); - set_upload_file.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (ContextCompat.checkSelfPermission(PeertubeUploadActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != - PackageManager.PERMISSION_GRANTED) { - ActivityCompat.requestPermissions(PeertubeUploadActivity.this, - new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, - MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE); - return; - } - Intent intent = new Intent(Intent.ACTION_GET_CONTENT); - intent.addCategory(Intent.CATEGORY_OPENABLE); - if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { - intent.setType("*/*"); - String[] mimetypes = {"video/*"}; - intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes); - startActivityForResult(intent, PICK_IVDEO); - } else { - intent.setType("video/*"); - Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); - Intent chooserIntent = Intent.createChooser(intent, getString(R.string.toot_select_image)); - chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{pickIntent}); - startActivityForResult(chooserIntent, PICK_IVDEO); - } - + set_upload_file.setOnClickListener(v -> { + if (ContextCompat.checkSelfPermission(PeertubeUploadActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != + PackageManager.PERMISSION_GRANTED) { + ActivityCompat.requestPermissions(PeertubeUploadActivity.this, + new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, + MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE); + return; } + Intent intent = new Intent(Intent.ACTION_GET_CONTENT); + intent.addCategory(Intent.CATEGORY_OPENABLE); + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { + intent.setType("*/*"); + String[] mimetypes = {"video/*"}; + intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes); + startActivityForResult(intent, PICK_IVDEO); + } else { + intent.setType("video/*"); + Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); + Intent chooserIntent = Intent.createChooser(intent, getString(R.string.toot_select_image)); + chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{pickIntent}); + startActivityForResult(chooserIntent, PICK_IVDEO); + } + }); //Manage languages @@ -391,6 +390,7 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe exception.printStackTrace(); } + @SuppressLint("ApplySharedPref") @Override public void onCompleted(Context context, UploadInfo uploadInfo, ServerResponse serverResponse) { try { 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 55495958c..9be6379ca 100644 --- a/app/src/main/java/app/fedilab/android/activities/SettingsActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/SettingsActivity.java @@ -154,7 +154,7 @@ public class SettingsActivity extends BaseActivity { } @Override - public void onDestroy(){ + public void onDestroy() { super.onDestroy(); } 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 bb39b6732..18ee706b0 100644 --- a/app/src/main/java/app/fedilab/android/activities/ShowAccountActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/ShowAccountActivity.java @@ -737,6 +737,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt attachments.add(attachment); intent.putParcelableArrayListExtra("mediaArray", attachments); b.putInt("position", 1); + b.putInt("bgcolor", getResources().getColor(R.color.cyanea_primary_dark)); intent.putExtras(b); startActivity(intent); }); @@ -1330,8 +1331,13 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt return true; case R.id.action_block: builderInner = new AlertDialog.Builder(ShowAccountActivity.this, style); - builderInner.setTitle(stringArrayConf[1]); - doActionAccount = API.StatusAction.BLOCK; + if (relationship.isBlocking()) { + builderInner.setTitle(stringArrayConf[5]); + doActionAccount = API.StatusAction.UNBLOCK; + } else { + builderInner.setTitle(stringArrayConf[1]); + doActionAccount = API.StatusAction.BLOCK; + } break; case R.id.action_block_instance: builderInner = new AlertDialog.Builder(ShowAccountActivity.this, style); 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 695456f1a..58807de8f 100644 --- a/app/src/main/java/app/fedilab/android/activities/SlideMediaActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/SlideMediaActivity.java @@ -24,7 +24,6 @@ import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager; -import android.graphics.Color; import android.graphics.Point; import android.graphics.drawable.ColorDrawable; import android.net.Uri; @@ -49,11 +48,6 @@ import androidx.fragment.app.FragmentStatePagerAdapter; import androidx.viewpager.widget.PagerAdapter; import androidx.viewpager.widget.ViewPager; -import com.r0adkll.slidr.Slidr; -import com.r0adkll.slidr.model.SlidrConfig; -import com.r0adkll.slidr.model.SlidrInterface; -import com.r0adkll.slidr.model.SlidrPosition; - import org.jetbrains.annotations.NotNull; import java.util.ArrayList; @@ -72,7 +66,7 @@ import es.dmoral.toasty.Toasty; * Media Activity */ -public class SlideMediaActivity extends BaseActivity implements OnDownloadInterface { +public class SlideMediaActivity extends BaseFragmentActivity implements OnDownloadInterface { int flags; private ArrayList attachments; @@ -80,13 +74,13 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf private ViewPager mPager; private long downloadID; private boolean fullscreen; - private SlidrInterface slidrInterface; private TextView media_description; private Handler handler; - private boolean swipeEnabled; private int minTouch, maxTouch; private float startX; private float startY; + private int bgColor; + private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { @@ -131,21 +125,24 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf media_description = findViewById(R.id.media_description); final int med_desc_timeout = sharedpreferences.getInt(Helper.SET_MED_DESC_TIMEOUT, 3) * 1000; flags = getWindow().getDecorView().getSystemUiVisibility(); + if (getIntent().getExtras() != null) { + mediaPosition = getIntent().getExtras().getInt("position", 1); + bgColor = getIntent().getExtras().getInt("bgcolor", -1); + } - swipeEnabled = true; ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { - //actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(SlideMediaActivity.this, R.color.cyanea_primary))); + actionBar.setBackgroundDrawable(new ColorDrawable(bgColor)); LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); assert inflater != null; View view = inflater.inflate(R.layout.media_action_bar, new LinearLayout(SlideMediaActivity.this), false); - view.setBackground(new ColorDrawable(ContextCompat.getColor(SlideMediaActivity.this, R.color.cyanea_primary))); + view.setBackgroundColor(bgColor); actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close); TextView toolbar_title = actionBar.getCustomView().findViewById(R.id.toolbar_title); - ImageView media_save = getSupportActionBar().getCustomView().findViewById(R.id.media_save); - ImageView media_share = getSupportActionBar().getCustomView().findViewById(R.id.media_share); + ImageView media_save = actionBar.getCustomView().findViewById(R.id.media_save); + ImageView media_share = actionBar.getCustomView().findViewById(R.id.media_share); toolbar_close.setOnClickListener(v -> finish()); media_save.setOnClickListener(view12 -> { int position = mPager.getCurrentItem(); @@ -198,8 +195,7 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf } attachments = getIntent().getParcelableArrayListExtra("mediaArray"); - if (getIntent().getExtras() != null) - mediaPosition = getIntent().getExtras().getInt("position", 1); + if (attachments == null || attachments.size() == 0) finish(); @@ -246,19 +242,7 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf } }); - SlidrConfig config = new SlidrConfig.Builder() - .sensitivity(1f) - .scrimColor(Color.BLACK) - .scrimStartAlpha(0.8f) - .scrimEndAlpha(0f) - .position(SlidrPosition.VERTICAL) - .velocityThreshold(2400) - .distanceThreshold(0.25f) - .edgeSize(0.18f) - .build(); - - slidrInterface = Slidr.attach(SlideMediaActivity.this, config); setFullscreen(true); Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); @@ -352,15 +336,6 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf super.onPostResume(); } - public void enableSliding(boolean enable) { - if (enable && !swipeEnabled) { - slidrInterface.unlock(); - swipeEnabled = true; - } else if (!enable && swipeEnabled) { - slidrInterface.lock(); - swipeEnabled = false; - } - } public boolean getFullScreen() { return this.fullscreen; @@ -419,6 +394,7 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf MediaSliderFragment mediaSliderFragment = new MediaSliderFragment(); bundle.putInt("position", position); bundle.putParcelable("attachment", attachments.get(position)); + bundle.putInt("bgcolor", bgColor); mediaSliderFragment.setArguments(bundle); return mediaSliderFragment; } 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 c920816e1..f360dcc3c 100644 --- a/app/src/main/java/app/fedilab/android/activities/WebviewConnectActivity.java +++ b/app/src/main/java/app/fedilab/android/activities/WebviewConnectActivity.java @@ -125,7 +125,7 @@ public class WebviewConnectActivity extends BaseActivity { webView = findViewById(R.id.webviewConnect); clearCookies(WebviewConnectActivity.this); webView.getSettings().setJavaScriptEnabled(true); - String user_agent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, null); + String user_agent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, Helper.USER_AGENT); if (user_agent != null) { webView.getSettings().setUserAgentString(user_agent); } diff --git a/app/src/main/java/app/fedilab/android/asynctasks/DownloadTrackingDomainsAsyncTask.java b/app/src/main/java/app/fedilab/android/asynctasks/DownloadTrackingDomainsAsyncTask.java index e1ad99c1b..8dfb2132f 100644 --- a/app/src/main/java/app/fedilab/android/asynctasks/DownloadTrackingDomainsAsyncTask.java +++ b/app/src/main/java/app/fedilab/android/asynctasks/DownloadTrackingDomainsAsyncTask.java @@ -33,7 +33,6 @@ import java.util.List; import javax.net.ssl.HttpsURLConnection; import app.fedilab.android.R; -import app.fedilab.android.helper.Helper; import app.fedilab.android.sqlite.DomainBlockDAO; import app.fedilab.android.sqlite.Sqlite; import es.dmoral.toasty.Toasty; 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 43007d129..11cee0aed 100644 --- a/app/src/main/java/app/fedilab/android/client/API.java +++ b/app/src/main/java/app/fedilab/android/client/API.java @@ -18,7 +18,10 @@ import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; +import android.os.Build; import android.os.Bundle; +import android.text.Html; +import android.text.SpannableString; import androidx.localbroadcastmanager.content.LocalBroadcastManager; @@ -412,6 +415,13 @@ public class API { status.setEmojis(new ArrayList<>()); status.setMedia_attachments(new ArrayList<>()); status.setVisibility("public"); + status.setViewType(context); + SpannableString spannableString; + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) + spannableString = new SpannableString(Html.fromHtml(status.getContent(), Html.FROM_HTML_MODE_LEGACY)); + else + spannableString = new SpannableString(Html.fromHtml(status.getContent())); + status.setContentSpan(new SpannableString(spannableString)); i++; statuses.add(status); } @@ -2205,6 +2215,9 @@ public class API { JSONObject resobj = new JSONObject(response); JSONObject jsonObject = resobj.getJSONObject("software"); String name = jsonObject.getString("name").toUpperCase(); + if (name.compareTo("CORGIDON") == 0) { + name = "MASTODON"; + } instanceNodeInfo.setName(name); instanceNodeInfo.setVersion(jsonObject.getString("version")); instanceNodeInfo.setOpenRegistrations(resobj.getBoolean("openRegistrations")); @@ -3696,13 +3709,16 @@ public class API { if (apiResponse.getStatuses() != null && apiResponse.getStatuses().size() > 0) { for (Status status : apiResponse.getStatuses()) { if (status.getMedia_attachments() != null) { - String statusSerialized = Helper.statusToStringStorage(status); - for (Attachment attachment : status.getMedia_attachments()) { - Status newStatus = Helper.restoreStatusFromString(statusSerialized); - if (newStatus == null) - break; - newStatus.setArt_attachment(attachment); - apiResponseReply.getStatuses().add(newStatus); + try { + String statusSerialized = Helper.statusToStringStorage(status); + for (Attachment attachment : status.getMedia_attachments()) { + Status newStatus = Helper.restoreStatusFromString(statusSerialized); + if (newStatus == null) + break; + newStatus.setArt_attachment(attachment); + apiResponseReply.getStatuses().add(newStatus); + } + } catch (Exception ignored) { } } } 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 fb2ec3b98..a59f94d7d 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 @@ -500,10 +500,11 @@ public class ManageTimelines { if (mPageReferenceMap != null) { FragmentTransaction fragTransaction = ((MainActivity) context).getSupportFragmentManager().beginTransaction(); DisplayStatusFragment displayStatusFragment = (DisplayStatusFragment) mPageReferenceMap.get(tl.getPosition()); - assert displayStatusFragment != null; - fragTransaction.detach(displayStatusFragment); - fragTransaction.attach(displayStatusFragment); - fragTransaction.commit(); + if (displayStatusFragment != null) { + fragTransaction.detach(displayStatusFragment); + fragTransaction.attach(displayStatusFragment); + fragTransaction.commit(); + } } } }); 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 dbaf113d1..edd0862c5 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 @@ -310,6 +310,44 @@ public class Status implements Parcelable { } } + matcher = Helper.bibliogramPattern.matcher(content); + boolean bibliogram = sharedpreferences.getBoolean(Helper.SET_BIBLIOGRAM, false); + if (bibliogram) { + while (matcher.find()) { + final String bibliogram_directory = matcher.group(2); + String bibliogramHost = sharedpreferences.getString(Helper.SET_BIBLIOGRAM_HOST, Helper.DEFAULT_BIBLIOGRAM_HOST).toLowerCase(); + content = content.replaceAll("https://" + Pattern.quote(matcher.group()), Matcher.quoteReplacement("https://" + bibliogramHost + bibliogram_directory)); + content = content.replaceAll(">" + Pattern.quote(matcher.group()), Matcher.quoteReplacement(">" + bibliogramHost + bibliogram_directory)); + } + } + + matcher = Helper.ouichesPattern.matcher(content); + + while (matcher.find()) { + Attachment attachment = new Attachment(); + attachment.setType("audio"); + String tag = matcher.group(1); + attachment.setId(tag); + if (tag == null) { + continue; + } + attachment.setRemote_url("http://ouich.es/mp3/" + tag + ".mp3"); + attachment.setUrl("http://ouich.es/mp3/" + tag + ".mp3"); + if (status.getMedia_attachments() == null) { + status.setMedia_attachments(new ArrayList<>()); + } + boolean alreadyAdded = false; + for (Attachment at : status.getMedia_attachments()) { + if (tag.compareTo(at.getId()) == 0) { + alreadyAdded = true; + break; + } + } + if (!alreadyAdded) { + status.getMedia_attachments().add(attachment); + } + } + Pattern aLink = Pattern.compile("]*(((?!"); Matcher matcherALink = aLink.matcher(content); int count = 0; diff --git a/app/src/main/java/app/fedilab/android/drawers/ArtListAdapter.java b/app/src/main/java/app/fedilab/android/drawers/ArtListAdapter.java index 0fce270be..859b8b011 100644 --- a/app/src/main/java/app/fedilab/android/drawers/ArtListAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/ArtListAdapter.java @@ -173,6 +173,7 @@ public class ArtListAdapter extends RecyclerView.Adapter implements OnPostAction else if (status.getMedia_attachments() != null && status.getMedia_attachments().size() > 0) attachments.add(status.getMedia_attachments().get(0)); intent.putParcelableArrayListExtra("mediaArray", attachments); + b.putInt("bgcolor", context.getResources().getColor(R.color.cyanea_primary_dark)); b.putInt("position", 1); intent.putExtras(b); context.startActivity(intent); diff --git a/app/src/main/java/app/fedilab/android/drawers/ImageAdapter.java b/app/src/main/java/app/fedilab/android/drawers/ImageAdapter.java index e346f8a24..8c4b76b14 100644 --- a/app/src/main/java/app/fedilab/android/drawers/ImageAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/ImageAdapter.java @@ -84,6 +84,7 @@ public class ImageAdapter extends RecyclerView.Adapter { } intent.putParcelableArrayListExtra("mediaArray", attachmentsTmp); b.putInt("position", (viewHolder.getAdapterPosition() + 1)); + b.putInt("bgcolor", context.getResources().getColor(R.color.cyanea_primary_dark)); intent.putExtras(b); context.startActivity(intent); }); 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 bf028988e..e1d77bce0 100644 --- a/app/src/main/java/app/fedilab/android/drawers/NotificationsListAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/NotificationsListAdapter.java @@ -1184,6 +1184,7 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On Bundle b = new Bundle(); intent.putParcelableArrayListExtra("mediaArray", notification.getStatus().getMedia_attachments()); b.putInt("position", finalPosition); + b.putInt("bgcolor", context.getResources().getColor(R.color.cyanea_primary_dark)); intent.putExtras(b); context.startActivity(intent); }); 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 54b5126b7..de0124764 100644 --- a/app/src/main/java/app/fedilab/android/drawers/PixelfedListAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/PixelfedListAdapter.java @@ -397,6 +397,7 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA Bundle b = new Bundle(); intent.putParcelableArrayListExtra("mediaArray", status.getMedia_attachments()); b.putInt("position", 1); + b.putInt("bgcolor", context.getResources().getColor(R.color.cyanea_primary_dark)); intent.putExtras(b); context.startActivity(intent); }); 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 432d62619..6731b7941 100644 --- a/app/src/main/java/app/fedilab/android/drawers/PixelfedStoriesListAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/PixelfedStoriesListAdapter.java @@ -134,6 +134,7 @@ public class PixelfedStoriesListAdapter extends RecyclerView.Adapter { Bundle b = new Bundle(); intent.putParcelableArrayListExtra("mediaArray", attachments); b.putInt("position", 1); + b.putInt("bgcolor", context.getResources().getColor(R.color.cyanea_primary_dark)); intent.putExtras(b); context.startActivity(intent); }); 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 37ec990cd..310b51280 100644 --- a/app/src/main/java/app/fedilab/android/drawers/SliderAdapter.java +++ b/app/src/main/java/app/fedilab/android/drawers/SliderAdapter.java @@ -107,6 +107,7 @@ public class SliderAdapter extends SliderViewAdapter { AlertDialog.Builder builderInner; @@ -2287,6 +2290,15 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct url = url.replaceAll("https://" + Pattern.quote(matcher.group()), Matcher.quoteReplacement("https://" + nitterHost + nitter_directory)); } } + boolean bibliogram = sharedpreferences.getBoolean(Helper.SET_BIBLIOGRAM, false); + if (bibliogram) { + Matcher matcher = Helper.bibliogramPattern.matcher(url); + while (matcher.find()) { + final String bibliogram_directory = matcher.group(2); + String bibliogramHost = sharedpreferences.getString(Helper.SET_BIBLIOGRAM_HOST, Helper.DEFAULT_BIBLIOGRAM_HOST).toLowerCase(); + url = url.replaceAll("https://" + Pattern.quote(matcher.group()), Matcher.quoteReplacement("https://" + bibliogramHost + bibliogram_directory)); + } + } Helper.openBrowser(context, url); }); } else if (card.getType().toLowerCase().equals("video") && (display_video_preview || (type == RetrieveFeedsAsyncTask.Type.CONTEXT && viewHolder.getAdapterPosition() == conversationPosition))) { @@ -2296,7 +2308,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct .into(holder.webview_preview_card); holder.status_cardview.setVisibility(View.GONE); holder.status_cardview_video.setVisibility(View.VISIBLE); - String user_agent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, null); + String user_agent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, Helper.USER_AGENT); if (user_agent != null) { holder.status_cardview_webview.getSettings().setUserAgentString(user_agent); } @@ -3393,6 +3405,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct Intent intent = new Intent(context, SlideMediaActivity.class); Bundle b = new Bundle(); intent.putParcelableArrayListExtra("mediaArray", attachmentArrayList); + b.putInt("bgcolor", context.getResources().getColor(R.color.cyanea_primary_dark)); b.putInt("position", finalPosition); intent.putExtras(b); context.startActivity(intent); 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 7dcbe3ad7..a94eadc63 100644 --- a/app/src/main/java/app/fedilab/android/fragments/ColorSettingsFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/ColorSettingsFragment.java @@ -275,7 +275,7 @@ public class ColorSettingsFragment extends PreferenceFragmentCompat implements S entryValues[2] = String.valueOf(Helper.THEME_BLACK); pref_theme_picker.setEntries(entries); int default_theme_value; - switch (theme){ + switch (theme) { case Helper.THEME_LIGHT: default_theme_value = 1; break; 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 c421d3db7..283b59c04 100644 --- a/app/src/main/java/app/fedilab/android/fragments/ContentSettingsFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/ContentSettingsFragment.java @@ -15,12 +15,12 @@ package app.fedilab.android.fragments; * see . */ +import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.TimePickerDialog; import android.content.ComponentName; import android.content.ContentUris; import android.content.Context; -import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; @@ -54,7 +54,6 @@ import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; -import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.SwitchCompat; import androidx.fragment.app.Fragment; @@ -337,17 +336,19 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot @Override public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - View rootView = inflater.inflate(R.layout.fragment_settings_reveal, container, false); Bundle bundle = this.getArguments(); if (bundle != null) { type = (type) bundle.getSerializable("typeOfSettings"); } context = getActivity(); + View rootView = null; + assert context != null; SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); + if (theme == Helper.THEME_DARK) { style = R.style.DialogDark; } else if (theme == Helper.THEME_BLACK) { @@ -356,1196 +357,1409 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot style = R.style.Dialog; } - LinearLayout settings_timeline = rootView.findViewById(R.id.settings_timeline); - LinearLayout settings_notifications = rootView.findViewById(R.id.settings_notifications); - LinearLayout settings_admin = rootView.findViewById(R.id.settings_admin); - LinearLayout settings_interface = rootView.findViewById(R.id.settings_interface); - LinearLayout settings_compose = rootView.findViewById(R.id.settings_compose); - LinearLayout settings_privacy = rootView.findViewById(R.id.settings_privacy); - LinearLayout settings_hide_menu = rootView.findViewById(R.id.settings_hide_menu); - LinearLayout settings_translation = rootView.findViewById(R.id.settings_translation); - - - if (type == null || type.equals(TIMELINES)) { - settings_timeline.setVisibility(View.VISIBLE); - } else if (type == NOTIFICATIONS) { - settings_notifications.setVisibility(View.VISIBLE); - } else if (type == ADMIN) { - settings_admin.setVisibility(View.VISIBLE); - } else if (type == INTERFACE) { - settings_interface.setVisibility(View.VISIBLE); - } else if (type == COMPOSE) { - settings_compose.setVisibility(View.VISIBLE); - } else if (type == PRIVACY) { - settings_privacy.setVisibility(View.VISIBLE); - } else if (type == MENU) { - settings_hide_menu.setVisibility(View.VISIBLE); - } else if (type == LANGUAGE) { - settings_translation.setVisibility(View.VISIBLE); - } - - - boolean auto_store = sharedpreferences.getBoolean(Helper.SET_AUTO_STORE, true); - - final SwitchCompat set_auto_store = rootView.findViewById(R.id.set_auto_store); - set_auto_store.setChecked(auto_store); - set_auto_store.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_AUTO_STORE, set_auto_store.isChecked()); - editor.apply(); - }); - - boolean display_content_after_fetch_more = sharedpreferences.getBoolean(Helper.SET_DISPLAY_CONTENT_AFTER_FM, true); - final SwitchCompat set_display_content_after_fetch_more = rootView.findViewById(R.id.set_display_content_after_fetch_more); - set_display_content_after_fetch_more.setChecked(display_content_after_fetch_more); - set_display_content_after_fetch_more.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_DISPLAY_CONTENT_AFTER_FM, set_display_content_after_fetch_more.isChecked()); - editor.apply(); - }); - String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(context)); - boolean auto_backup = sharedpreferences.getBoolean(Helper.SET_AUTO_BACKUP_STATUSES + userId + instance, false); - final SwitchCompat set_auto_backup = rootView.findViewById(R.id.set_auto_backup); - set_auto_backup.setChecked(auto_backup); - set_auto_backup.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_AUTO_BACKUP_STATUSES + userId + instance, set_auto_backup.isChecked()); - editor.apply(); - }); - - - boolean clear_cache_exit = sharedpreferences.getBoolean(Helper.SET_CLEAR_CACHE_EXIT, false); - final SwitchCompat set_clear_cache_exit = rootView.findViewById(R.id.set_clear_cache_exit); - set_clear_cache_exit.setChecked(clear_cache_exit); - set_clear_cache_exit.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_CLEAR_CACHE_EXIT, set_clear_cache_exit.isChecked()); - editor.apply(); - }); - - boolean auto_backup_notifications = sharedpreferences.getBoolean(Helper.SET_AUTO_BACKUP_NOTIFICATIONS + userId + instance, false); - final SwitchCompat set_auto_backup_notifications = rootView.findViewById(R.id.set_auto_backup_notifications); - set_auto_backup_notifications.setChecked(auto_backup_notifications); - set_auto_backup_notifications.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_AUTO_BACKUP_NOTIFICATIONS + userId + instance, set_auto_backup_notifications.isChecked()); - editor.apply(); - }); - - - TagsEditText set_featured_tags = rootView.findViewById(R.id.set_featured_tags); - if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { - Set featuredTagsSet = sharedpreferences.getStringSet(Helper.SET_FEATURED_TAGS, null); - - - List tags = new ArrayList<>(); - if (featuredTagsSet != null) { - tags = new ArrayList<>(featuredTagsSet); - } - String[] tagsString = tags.toArray(new String[tags.size()]); - set_featured_tags.setTags(tagsString); - - set_featured_tags.setTagsListener(new TagsEditText.TagsEditListener() { - @Override - public void onTagsChanged(Collection collection) { - Set set = ImmutableSet.copyOf(collection); - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putStringSet(Helper.SET_FEATURED_TAGS, set); - editor.apply(); - } - - @Override - public void onEditingFinished() { - - } - }); - } else { - set_featured_tags.setVisibility(View.GONE); - } - - - Button update_tracking_domains = rootView.findViewById(R.id.update_tracking_domains); - update_tracking_domains.setOnClickListener(v -> { - new DownloadTrackingDomainsAsyncTask(Objects.requireNonNull(getActivity()), update_tracking_domains).execute(); - }); - - - Spinner set_attachment_group = rootView.findViewById(R.id.set_attachment_group); - String[] attachment_labels = {context.getString(R.string.set_attachment_always), context.getString(R.string.set_attachment_wifi), context.getString(R.string.set_attachment_ask)}; - ArrayAdapter adapterAttachment = new ArrayAdapter<>(Objects.requireNonNull(getActivity()), - android.R.layout.simple_spinner_dropdown_item, attachment_labels); - set_attachment_group.setAdapter(adapterAttachment); - int attachmentAction = sharedpreferences.getInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ALWAYS); - switch (attachmentAction) { - case Helper.ATTACHMENT_ALWAYS: - set_attachment_group.setSelection(0, false); - break; - case Helper.ATTACHMENT_WIFI: - set_attachment_group.setSelection(1, false); - break; - case Helper.ATTACHMENT_ASK: - set_attachment_group.setSelection(2, false); - break; - } - - set_attachment_group.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - SharedPreferences.Editor editor = sharedpreferences.edit(); - switch (position) { - case 0: - editor.putInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ALWAYS); - editor.apply(); - break; - case 1: - editor.putInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_WIFI); - editor.apply(); - break; - case 2: - editor.putInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ASK); - editor.apply(); - break; - } - } - - @Override - public void onNothingSelected(AdapterView parent) { - - } - }); - - - int videoMode = sharedpreferences.getInt(Helper.SET_VIDEO_MODE, Helper.VIDEO_MODE_DIRECT); - - - //Video mode - final Spinner video_mode_spinner = rootView.findViewById(R.id.set_video_mode); - ArrayAdapter video_mode_spinnerAdapter = ArrayAdapter.createFromResource(Objects.requireNonNull(getActivity()), - R.array.settings_video_mode, android.R.layout.simple_spinner_dropdown_item); - video_mode_spinner.setAdapter(video_mode_spinnerAdapter); - if (videoMode == Helper.VIDEO_MODE_TORRENT) - videoMode = Helper.VIDEO_MODE_DIRECT; - int positionVideoMode = 0; - if (videoMode == Helper.VIDEO_MODE_DIRECT) - positionVideoMode = 1; - videoSpinnerCount = 0; - video_mode_spinner.setSelection(positionVideoMode); - video_mode_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - if (videoSpinnerCount > 0) { - SharedPreferences.Editor editor = sharedpreferences.edit(); - switch (position) { - case 0: - editor.putInt(Helper.SET_VIDEO_MODE, Helper.VIDEO_MODE_WEBVIEW); - editor.apply(); - break; - case 1: - editor.putInt(Helper.SET_VIDEO_MODE, Helper.VIDEO_MODE_DIRECT); - editor.apply(); - break; - } - } else { - videoSpinnerCount++; - } - } - - @Override - public void onNothingSelected(AdapterView parent) { - - } - }); - - boolean patch_provider = sharedpreferences.getBoolean(Helper.SET_SECURITY_PROVIDER, true); - final SwitchCompat set_security_provider = rootView.findViewById(R.id.set_security_provider); - set_security_provider.setChecked(patch_provider); - - set_security_provider.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_SECURITY_PROVIDER, set_security_provider.isChecked()); - editor.apply(); - }); - - - boolean display_card = sharedpreferences.getBoolean(Helper.SET_DISPLAY_CARD, false); - - final SwitchCompat set_display_card = rootView.findViewById(R.id.set_display_card); - set_display_card.setChecked(display_card); - set_display_card.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_DISPLAY_CARD, set_display_card.isChecked()); - editor.apply(); - }); - - - boolean display_admin_menu = sharedpreferences.getBoolean(Helper.SET_DISPLAY_ADMIN_MENU + userId + instance, false); - - final SwitchCompat set_display_admin_menu = rootView.findViewById(R.id.set_display_admin_menu); - set_display_admin_menu.setChecked(display_admin_menu); - set_display_admin_menu.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_DISPLAY_ADMIN_MENU + userId + instance, set_display_admin_menu.isChecked()); - editor.apply(); - Bundle b = new Bundle(); - if (set_display_admin_menu.isChecked()) { - b.putString("menu", "show_admin"); - } else { - b.putString("menu", "hide_admin"); - } - Intent intentBC = new Intent(Helper.RECEIVE_HIDE_ITEM); - intentBC.putExtras(b); - LocalBroadcastManager.getInstance(context).sendBroadcast(intentBC); - }); - - boolean display_admin_statuses = sharedpreferences.getBoolean(Helper.SET_DISPLAY_ADMIN_STATUSES + userId + instance, false); - - final SwitchCompat set_display_admin_statuses = rootView.findViewById(R.id.set_display_admin_statuses); - set_display_admin_statuses.setChecked(display_admin_statuses); - set_display_admin_statuses.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_DISPLAY_ADMIN_STATUSES + userId + instance, set_display_admin_statuses.isChecked()); - editor.apply(); - }); - - boolean show_media_urls = sharedpreferences.getBoolean(Helper.SET_MEDIA_URLS, false); - final SwitchCompat set_auto_add_media_url = rootView.findViewById(R.id.set_auto_add_media_url); - set_auto_add_media_url.setChecked(show_media_urls); - - set_auto_add_media_url.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_MEDIA_URLS, set_auto_add_media_url.isChecked()); - editor.apply(); - }); - - boolean display_video_preview = sharedpreferences.getBoolean(Helper.SET_DISPLAY_VIDEO_PREVIEWS, true); - final SwitchCompat set_display_video_preview = rootView.findViewById(R.id.set_display_video_preview); - set_display_video_preview.setChecked(display_video_preview); - - set_display_video_preview.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_DISPLAY_VIDEO_PREVIEWS, set_display_video_preview.isChecked()); - editor.apply(); - }); - - boolean notif_validation = sharedpreferences.getBoolean(Helper.SET_NOTIF_VALIDATION, true); - final SwitchCompat set_share_validation = rootView.findViewById(R.id.set_share_validation); - set_share_validation.setChecked(notif_validation); - - set_share_validation.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_NOTIF_VALIDATION, set_share_validation.isChecked()); - editor.apply(); - }); - your_api_key = rootView.findViewById(R.id.translation_key); - - your_api_key.addTextChangedListener(new TextWatcher() { - @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(); - int translatore = sharedpreferences.getInt(Helper.SET_TRANSLATOR, Helper.TRANS_YANDEX); - String store = null; - if (translatore == Helper.TRANS_YANDEX) - store = Helper.SET_YANDEX_API_KEY; - else if (translatore == Helper.TRANS_DEEPL) - store = Helper.SET_DEEPL_API_KEY; - else if (translatore == Helper.TRANS_SYSTRAN) - store = Helper.SET_SYSTRAN_API_KEY; - if (store != null) - if (s != null && s.length() > 0) - editor.putString(store, s.toString().trim()); - else - editor.putString(store, null); - editor.apply(); - } - }); - - boolean notif_validation_fav = sharedpreferences.getBoolean(Helper.SET_NOTIF_VALIDATION_FAV, false); - final SwitchCompat set_share_validation_fav = rootView.findViewById(R.id.set_share_validation_fav); - set_share_validation_fav.setChecked(notif_validation_fav); - - set_share_validation_fav.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_NOTIF_VALIDATION_FAV, set_share_validation_fav.isChecked()); - editor.apply(); - }); - - - boolean expand_cw = sharedpreferences.getBoolean(Helper.SET_EXPAND_CW, false); - final SwitchCompat set_expand_cw = rootView.findViewById(R.id.set_expand_cw); - set_expand_cw.setChecked(expand_cw); - - set_expand_cw.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_EXPAND_CW, set_expand_cw.isChecked()); - editor.apply(); - }); - - boolean display_emoji = sharedpreferences.getBoolean(Helper.SET_DISPLAY_EMOJI, false); - final SwitchCompat set_display_emoji = rootView.findViewById(R.id.set_display_emoji); - set_display_emoji.setChecked(display_emoji); - - set_display_emoji.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_DISPLAY_EMOJI, set_display_emoji.isChecked()); - editor.apply(); - }); - - boolean expand_media = sharedpreferences.getBoolean(Helper.SET_EXPAND_MEDIA, false); - final SwitchCompat set_expand_media = rootView.findViewById(R.id.set_expand_image); - set_expand_media.setChecked(expand_media); - - set_expand_media.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_EXPAND_MEDIA, set_expand_media.isChecked()); - editor.apply(); - }); - - - boolean photo_editor = sharedpreferences.getBoolean(Helper.SET_PHOTO_EDITOR, true); - final SwitchCompat set_photo_editor = rootView.findViewById(R.id.set_photo_editor); - set_photo_editor.setChecked(photo_editor); - - set_photo_editor.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_PHOTO_EDITOR, set_photo_editor.isChecked()); - editor.apply(); - }); - - int upload_img_max_retry_times = sharedpreferences.getInt(Helper.MAX_UPLOAD_IMG_RETRY_TIMES, 3); - final SeekBar max_times_bar = rootView.findViewById(R.id.max_upload_image_retry_times); - final TextView max_times_value = rootView.findViewById(R.id.max_upload_image_retry_times_value); - max_times_bar.setProgress(upload_img_max_retry_times); - max_times_value.setText(String.valueOf(upload_img_max_retry_times)); - max_times_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - } - - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - max_times_value.setText(String.valueOf(progress)); - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putInt(Helper.MAX_UPLOAD_IMG_RETRY_TIMES, progress); - editor.apply(); - } - }); - boolean remember_position_home = sharedpreferences.getBoolean(Helper.SET_REMEMBER_POSITION_HOME, true); - final SwitchCompat set_remember_position = rootView.findViewById(R.id.set_remember_position); - set_remember_position.setChecked(remember_position_home); - - set_remember_position.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_REMEMBER_POSITION_HOME, set_remember_position.isChecked()); - editor.apply(); - }); - - - boolean hide_delete_notification_on_tab = sharedpreferences.getBoolean(Helper.SET_HIDE_DELETE_BUTTON_ON_TAB, false); - final SwitchCompat set_hide_delete_notification_on_tab = rootView.findViewById(R.id.set_hide_delete_notification_on_tab); - set_hide_delete_notification_on_tab.setChecked(hide_delete_notification_on_tab); - - set_hide_delete_notification_on_tab.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_HIDE_DELETE_BUTTON_ON_TAB, set_hide_delete_notification_on_tab.isChecked()); - editor.apply(); - if (getActivity() != null) - getActivity().recreate(); - Intent intent = new Intent(context, MainActivity.class); - if (getActivity() != null) - getActivity().finish(); - startActivity(intent); - }); - - - boolean blur_sensitive = sharedpreferences.getBoolean(Helper.SET_BLUR_SENSITIVE, true); - final SwitchCompat set_blur_sensitive = rootView.findViewById(R.id.set_blur_sensitive); - set_blur_sensitive.setChecked(blur_sensitive); - - set_blur_sensitive.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_BLUR_SENSITIVE, set_blur_sensitive.isChecked()); - editor.apply(); - }); - - - TextView set_invidious_host = rootView.findViewById(R.id.set_invidious_host); - - - boolean invidious = sharedpreferences.getBoolean(Helper.SET_INVIDIOUS, false); - final SwitchCompat set_invidious = rootView.findViewById(R.id.set_invidious); - set_invidious.setChecked(invidious); - - set_invidious.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_INVIDIOUS, set_invidious.isChecked()); - editor.apply(); - if (set_invidious.isChecked()) { - set_invidious_host.setVisibility(View.VISIBLE); - } else { - set_invidious_host.setVisibility(View.GONE); - } - }); - if (invidious) { - set_invidious_host.setVisibility(View.VISIBLE); - } else { - set_invidious_host.setVisibility(View.GONE); - } - - String invidiousHost = sharedpreferences.getString(Helper.SET_INVIDIOUS_HOST, null); - if (invidiousHost != null) { - set_invidious_host.setText(invidiousHost); - } - set_invidious_host.addTextChangedListener(new TextWatcher() { - @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(); - if (s.toString().trim().length() > 0) { - editor.putString(Helper.SET_INVIDIOUS_HOST, s.toString().toLowerCase().trim()); - } else { - editor.putString(Helper.SET_INVIDIOUS_HOST, null); - } - editor.apply(); - } - }); - - - TextView set_user_agent = rootView.findViewById(R.id.set_user_agent); - String user_agent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, null); - - if (user_agent != null) { - set_user_agent.setText(user_agent); - } - set_user_agent.addTextChangedListener(new TextWatcher() { - @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(); - if (s.toString().trim().length() > 0) { - editor.putString(Helper.SET_CUSTOM_USER_AGENT, s.toString().toLowerCase().trim()); - } else { - editor.putString(Helper.SET_CUSTOM_USER_AGENT, null); - } - editor.apply(); - } - }); - - - final SwitchCompat set_utm_parameters = rootView.findViewById(R.id.set_utm_parameters); - boolean utm_parameters = sharedpreferences.getBoolean(Helper.SET_FILTER_UTM, true); - set_utm_parameters.setChecked(utm_parameters); - - set_utm_parameters.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_FILTER_UTM, set_utm_parameters.isChecked()); - editor.apply(); - }); - - TextView set_nitter_host = rootView.findViewById(R.id.set_nitter_host); - boolean nitter = sharedpreferences.getBoolean(Helper.SET_NITTER, false); - final SwitchCompat set_nitter = rootView.findViewById(R.id.set_nitter); - set_nitter.setChecked(nitter); - - set_nitter.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_NITTER, set_nitter.isChecked()); - editor.apply(); - if (set_nitter.isChecked()) { - set_nitter_host.setVisibility(View.VISIBLE); - } else { - set_nitter_host.setVisibility(View.GONE); - } - }); - if (nitter) { - set_nitter_host.setVisibility(View.VISIBLE); - } else { - set_nitter_host.setVisibility(View.GONE); - } - - String nitterHost = sharedpreferences.getString(Helper.SET_NITTER_HOST, null); - if (nitterHost != null) { - set_nitter_host.setText(nitterHost); - } - set_nitter_host.addTextChangedListener(new TextWatcher() { - @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(); - if (s.toString().trim().length() > 0) { - editor.putString(Helper.SET_NITTER_HOST, s.toString().toLowerCase().trim()); - } else { - editor.putString(Helper.SET_NITTER_HOST, null); - } - editor.apply(); - } - }); - - boolean long_press_media = sharedpreferences.getBoolean(Helper.SET_LONG_PRESS_MEDIA, true); - final SwitchCompat set_long_press_media = rootView.findViewById(R.id.set_long_press_media); - set_long_press_media.setChecked(long_press_media); - - set_long_press_media.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_LONG_PRESS_MEDIA, set_long_press_media.isChecked()); - editor.apply(); - }); - - - boolean display_timeline_in_list = sharedpreferences.getBoolean(Helper.SET_DISPLAY_TIMELINE_IN_LIST, false); - final SwitchCompat set_display_timeline_in_list = rootView.findViewById(R.id.set_display_timeline_in_list); - set_display_timeline_in_list.setChecked(display_timeline_in_list); - - set_display_timeline_in_list.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_DISPLAY_TIMELINE_IN_LIST, set_display_timeline_in_list.isChecked()); - editor.apply(); - Bundle b = new Bundle(); - if (set_display_timeline_in_list.isChecked()) { - b.putString("menu", "show_list_button"); - } else { - b.putString("menu", "hide_list_button"); - } - Intent intentBC = new Intent(Helper.RECEIVE_HIDE_ITEM); - intentBC.putExtras(b); - LocalBroadcastManager.getInstance(context).sendBroadcast(intentBC); - }); - - - boolean unfollow_validation = sharedpreferences.getBoolean(Helper.SET_UNFOLLOW_VALIDATION, true); - final SwitchCompat set_unfollow_validation = rootView.findViewById(R.id.set_unfollow_validation); - set_unfollow_validation.setChecked(unfollow_validation); - - set_unfollow_validation.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_UNFOLLOW_VALIDATION, set_unfollow_validation.isChecked()); - editor.apply(); - }); - - - boolean send_crash_reports = sharedpreferences.getBoolean(Helper.SET_SEND_CRASH_REPORTS, false); - final SwitchCompat set_enable_crash_report = rootView.findViewById(R.id.set_enable_crash_report); - set_enable_crash_report.setChecked(send_crash_reports); - - set_enable_crash_report.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_SEND_CRASH_REPORTS, set_enable_crash_report.isChecked()); - editor.apply(); - if (getActivity() != null) - getActivity().recreate(); - }); - - int truncate_toots_size = sharedpreferences.getInt(Helper.SET_TRUNCATE_TOOTS_SIZE, 0); - SeekBar set_truncate_size = rootView.findViewById(R.id.set_truncate_size); - set_truncate_size.setMax(20); - set_truncate_size.setProgress(truncate_toots_size); - TextView set_truncate_toots = rootView.findViewById(R.id.set_truncate_toots); - set_truncate_toots.setText(String.valueOf(truncate_toots_size)); - set_truncate_size.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - } - - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - set_truncate_toots.setText(String.valueOf(progress)); - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putInt(Helper.SET_TRUNCATE_TOOTS_SIZE, progress); - editor.apply(); - } - }); - - - boolean new_badge = sharedpreferences.getBoolean(Helper.SET_DISPLAY_NEW_BADGE, true); - final SwitchCompat set_new_badge = rootView.findViewById(R.id.set_display_new_badge); - set_new_badge.setChecked(new_badge); - - set_new_badge.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_DISPLAY_NEW_BADGE, set_new_badge.isChecked()); - editor.apply(); - }); - - boolean fedilab_features_button = sharedpreferences.getBoolean(Helper.SET_DISPLAY_FEDILAB_FEATURES_BUTTON, true); - final SwitchCompat set_fedilab_features_button = rootView.findViewById(R.id.set_display_fedilab_features_button); - set_fedilab_features_button.setChecked(fedilab_features_button); - - set_fedilab_features_button.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_DISPLAY_FEDILAB_FEATURES_BUTTON, set_fedilab_features_button.isChecked()); - editor.apply(); - }); - - boolean bot_icon = sharedpreferences.getBoolean(Helper.SET_DISPLAY_BOT_ICON, true); - final SwitchCompat set_bot_icon = rootView.findViewById(R.id.set_display_bot_icon); - set_bot_icon.setChecked(bot_icon); - - set_bot_icon.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_DISPLAY_BOT_ICON, set_bot_icon.isChecked()); - editor.apply(); - }); - - boolean display_confirm = sharedpreferences.getBoolean(Helper.SET_DISPLAY_CONFIRM, true); - final SwitchCompat set_display_confirm = rootView.findViewById(R.id.set_display_confirm); - set_display_confirm.setChecked(display_confirm); - - set_display_confirm.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_DISPLAY_CONFIRM, set_display_confirm.isChecked()); - editor.apply(); - }); - - boolean quick_reply = sharedpreferences.getBoolean(Helper.SET_QUICK_REPLY, true); - final SwitchCompat set_quick_reply = rootView.findViewById(R.id.set_quick_reply); - set_quick_reply.setChecked(quick_reply); - - set_quick_reply.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_QUICK_REPLY, set_quick_reply.isChecked()); - editor.apply(); - }); - - boolean fit_preview = sharedpreferences.getBoolean(Helper.SET_FULL_PREVIEW, false); - final SwitchCompat set_fit_preview = rootView.findViewById(R.id.set_fit_preview); - set_fit_preview.setChecked(fit_preview); - - set_fit_preview.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_FULL_PREVIEW, set_fit_preview.isChecked()); - editor.apply(); - }); - - - Spinner set_mode = rootView.findViewById(R.id.set_mode); - String[] mode_labels = {context.getString(R.string.set_normal), context.getString(R.string.set_compact), context.getString(R.string.set_console)}; - ArrayAdapter adapterMode = new ArrayAdapter<>(Objects.requireNonNull(getActivity()), - android.R.layout.simple_spinner_dropdown_item, mode_labels); - set_mode.setAdapter(adapterMode); - boolean compact_mode = sharedpreferences.getBoolean(Helper.SET_COMPACT_MODE, false); - boolean console_mode = sharedpreferences.getBoolean(Helper.SET_CONSOLE_MODE, false); - - if (compact_mode) { - set_mode.setSelection(1); - } else if (console_mode) { - set_mode.setSelection(2); - } else { - set_mode.setSelection(0); - } - - set_mode.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - SharedPreferences.Editor editor = sharedpreferences.edit(); - switch (position) { - case 0: - editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_COMPACT_MODE, false); - editor.putBoolean(Helper.SET_CONSOLE_MODE, false); - editor.apply(); - break; - case 1: - editor.putBoolean(Helper.SET_COMPACT_MODE, true); - editor.putBoolean(Helper.SET_CONSOLE_MODE, false); - editor.apply(); - break; - case 2: - editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_COMPACT_MODE, false); - editor.putBoolean(Helper.SET_CONSOLE_MODE, true); - editor.apply(); - break; - } - } - - @Override - public void onNothingSelected(AdapterView parent) { - - } - }); - - - boolean share_details = sharedpreferences.getBoolean(Helper.SET_SHARE_DETAILS, true); - final SwitchCompat set_share_details = rootView.findViewById(R.id.set_share_details); - set_share_details.setChecked(share_details); - - set_share_details.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_SHARE_DETAILS, set_share_details.isChecked()); - editor.apply(); - }); - - // retrieve metadata if URL from external apps when composing - boolean should_retrieve_metadata = sharedpreferences.getBoolean(Helper.SET_RETRIEVE_METADATA_IF_URL_FROM_EXTERAL, true); - final SwitchCompat set_retrieve_metadata = rootView.findViewById(R.id.set_retrieve_metadata_share_from_extras); - set_retrieve_metadata.setChecked(should_retrieve_metadata); - - set_retrieve_metadata.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_RETRIEVE_METADATA_IF_URL_FROM_EXTERAL, set_retrieve_metadata.isChecked()); - editor.apply(); - }); - - // Custom Sharing - final EditText edit_custom_sharing_url = rootView.findViewById(R.id.custom_sharing_url); - boolean custom_sharing = sharedpreferences.getBoolean(Helper.SET_CUSTOM_SHARING, false); - final SwitchCompat set_custom_sharing = rootView.findViewById(R.id.set_custom_sharing); - set_custom_sharing.setChecked(custom_sharing); - if (custom_sharing) - edit_custom_sharing_url.setVisibility(View.VISIBLE); - else - edit_custom_sharing_url.setVisibility(View.GONE); - set_custom_sharing.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_CUSTOM_SHARING, set_custom_sharing.isChecked()); - editor.apply(); - if (set_custom_sharing.isChecked()) - edit_custom_sharing_url.setVisibility(View.VISIBLE); - else - edit_custom_sharing_url.setVisibility(View.GONE); - }); - - // forward tags in replies - boolean forward_tags = sharedpreferences.getBoolean(Helper.SET_FORWARD_TAGS_IN_REPLY, false); - final SwitchCompat set_forward_tags = rootView.findViewById(R.id.set_forward_tags); - set_forward_tags.setChecked(forward_tags); - set_forward_tags.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_FORWARD_TAGS_IN_REPLY, set_forward_tags.isChecked()); - editor.apply(); - }); - - String custom_sharing_url = sharedpreferences.getString(Helper.SET_CUSTOM_SHARING_URL, ""); - if (custom_sharing_url.equals("")) { - custom_sharing_url = "http://cs.example.net/add?token=umVe1zurZk47ihElSOQcBG05KUSA2v-GSet4_fFnJ4M&url=${url}&title=${title}&source=${source}&id=${id}&description=${description}&keywords=${keywords}&creator=${creator}&thumbnailurl=${thumbnailurl}"; - } - edit_custom_sharing_url.setText(custom_sharing_url); - - - edit_custom_sharing_url.addTextChangedListener(new TextWatcher() { - @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(); - editor.putString(Helper.SET_CUSTOM_SHARING_URL, s.toString().trim()); - editor.apply(); - } - }); - - boolean disableGif = sharedpreferences.getBoolean(Helper.SET_DISABLE_GIF, false); - final SwitchCompat set_disable_gif = rootView.findViewById(R.id.set_disable_gif); - set_disable_gif.setChecked(disableGif); - set_disable_gif.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_DISABLE_GIF, set_disable_gif.isChecked()); - editor.apply(); - if (getActivity() != null) - getActivity().recreate(); - }); - - - boolean disableAnimatedEmoji = sharedpreferences.getBoolean(Helper.SET_DISABLE_ANIMATED_EMOJI, false); - final SwitchCompat set_disable_animated_emoji = rootView.findViewById(R.id.set_disable_animated_emoji); - set_disable_animated_emoji.setChecked(disableAnimatedEmoji); - set_disable_animated_emoji.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_DISABLE_ANIMATED_EMOJI, set_disable_animated_emoji.isChecked()); - editor.apply(); - }); - - - boolean notify = sharedpreferences.getBoolean(Helper.SET_NOTIFY, true); - final SwitchCompat switchCompatNotify = rootView.findViewById(R.id.set_notify); - switchCompatNotify.setChecked(notify); - final LinearLayout notification_container = rootView.findViewById(R.id.notification_container); - if (notify) { - notification_container.setVisibility(View.VISIBLE); - } else { - notification_container.setVisibility(View.GONE); - } - switchCompatNotify.setOnCheckedChangeListener((buttonView, isChecked) -> { - // Save the state here - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_NOTIFY, isChecked); - editor.apply(); - if (isChecked) { - notification_container.setVisibility(View.VISIBLE); - notification_container.setVisibility(View.VISIBLE); - Helper.startStreaming(context); - } else { - context.sendBroadcast(new Intent(context, StopLiveNotificationReceiver.class)); - context.sendBroadcast(new Intent(context, StopDelayedNotificationReceiver.class)); - ApplicationJob.cancelAllJob(NotificationsSyncJob.NOTIFICATION_REFRESH); - notification_container.setVisibility(View.GONE); - } - }); - - - //Live notification mode - final Spinner set_live_type = rootView.findViewById(R.id.set_live_type); - String[] labels = {context.getString(R.string.live_notif), context.getString(R.string.live_delayed), context.getString(R.string.no_live_notif)}; - ArrayAdapter adapterLive = new ArrayAdapter<>(Objects.requireNonNull(getActivity()), - android.R.layout.simple_spinner_dropdown_item, labels); - - LinearLayout live_notif_per_account = rootView.findViewById(R.id.live_notif_per_account); - set_live_type.setAdapter(adapterLive); - if (Helper.liveNotifType(context) == Helper.NOTIF_NONE) { - live_notif_per_account.setVisibility(View.GONE); - } - TextView set_live_type_indication = rootView.findViewById(R.id.set_live_type_indication); - switch (Helper.liveNotifType(context)) { - case Helper.NOTIF_LIVE: - set_live_type_indication.setText(R.string.live_notif_indication); - break; - case Helper.NOTIF_DELAYED: - set_live_type_indication.setText(R.string.set_live_type_indication); - break; - case Helper.NOTIF_NONE: - set_live_type_indication.setText(R.string.no_live_indication); - break; - } - set_live_type.setSelection(Helper.liveNotifType(context)); - liveNotificationCount = 0; - set_live_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - if (liveNotificationCount > 0) { - SharedPreferences.Editor editor = sharedpreferences.edit(); - - context.sendBroadcast(new Intent(context, StopLiveNotificationReceiver.class)); - context.sendBroadcast(new Intent(context, StopDelayedNotificationReceiver.class)); - ApplicationJob.cancelAllJob(NotificationsSyncJob.NOTIFICATION_REFRESH); - switch (position) { - case Helper.NOTIF_LIVE: - editor.putBoolean(Helper.SET_LIVE_NOTIFICATIONS, true); - editor.putBoolean(Helper.SET_DELAYED_NOTIFICATIONS, false); - live_notif_per_account.setVisibility(View.VISIBLE); - editor.commit(); - set_live_type_indication.setText(R.string.live_notif_indication); - Helper.startStreaming(context); - break; - case Helper.NOTIF_DELAYED: - editor.putBoolean(Helper.SET_LIVE_NOTIFICATIONS, false); - editor.putBoolean(Helper.SET_DELAYED_NOTIFICATIONS, true); - live_notif_per_account.setVisibility(View.VISIBLE); - set_live_type_indication.setText(R.string.set_live_type_indication); - editor.commit(); - Helper.startStreaming(context); - break; - case Helper.NOTIF_NONE: - editor.putBoolean(Helper.SET_LIVE_NOTIFICATIONS, false); - editor.putBoolean(Helper.SET_DELAYED_NOTIFICATIONS, false); - editor.commit(); - set_live_type_indication.setText(R.string.no_live_indication); - live_notif_per_account.setVisibility(View.GONE); - NotificationsSyncJob.schedule(false); - break; - } - } else { - liveNotificationCount++; - } - } - - @Override - public void onNothingSelected(AdapterView parent) { - - } - }); - - - boolean capitalize = sharedpreferences.getBoolean(Helper.SET_CAPITALIZE, true); - final SwitchCompat set_capitalize = rootView.findViewById(R.id.set_capitalize); - set_capitalize.setChecked(capitalize); - - set_capitalize.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_CAPITALIZE, set_capitalize.isChecked()); - editor.apply(); - }); - - - if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { - LinearLayout set_wysiwyg_container = rootView.findViewById(R.id.set_wysiwyg_container); - set_wysiwyg_container.setVisibility(View.VISIBLE); - } - - boolean wysiwyg = sharedpreferences.getBoolean(Helper.SET_WYSIWYG, false); - final SwitchCompat set_wysiwyg = rootView.findViewById(R.id.set_wysiwyg); - set_wysiwyg.setChecked(wysiwyg); - - set_wysiwyg.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_WYSIWYG, set_wysiwyg.isChecked()); - editor.apply(); - }); - - - final SwitchCompat set_embedded_browser = rootView.findViewById(R.id.set_embedded_browser); - final LinearLayout set_javascript_container = rootView.findViewById(R.id.set_javascript_container); - final SwitchCompat set_custom_tabs = rootView.findViewById(R.id.set_custom_tabs); - final LinearLayout custom_tabs_container = rootView.findViewById(R.id.custom_tabs_container); - final SwitchCompat set_javascript = rootView.findViewById(R.id.set_javascript); - boolean javascript = sharedpreferences.getBoolean(Helper.SET_JAVASCRIPT, true); - boolean embedded_browser = sharedpreferences.getBoolean(Helper.SET_EMBEDDED_BROWSER, true); - boolean custom_tabs = sharedpreferences.getBoolean(Helper.SET_CUSTOM_TABS, true); - if (!embedded_browser) { - set_javascript_container.setVisibility(View.GONE); - custom_tabs_container.setVisibility(View.VISIBLE); - } else { - set_javascript_container.setVisibility(View.VISIBLE); - custom_tabs_container.setVisibility(View.GONE); - } - set_embedded_browser.setChecked(embedded_browser); - set_embedded_browser.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_EMBEDDED_BROWSER, set_embedded_browser.isChecked()); - editor.apply(); - if (!set_embedded_browser.isChecked()) { - set_javascript_container.setVisibility(View.GONE); - custom_tabs_container.setVisibility(View.VISIBLE); - } else { - set_javascript_container.setVisibility(View.VISIBLE); - custom_tabs_container.setVisibility(View.GONE); - } - }); - - set_javascript.setChecked(javascript); - set_javascript.setOnCheckedChangeListener((buttonView, isChecked) -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_JAVASCRIPT, isChecked); - editor.apply(); - }); - - set_custom_tabs.setChecked(custom_tabs); - set_custom_tabs.setOnCheckedChangeListener((buttonView, isChecked) -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_CUSTOM_TABS, isChecked); - editor.apply(); - }); - - final LinearLayout set_cookies_container = rootView.findViewById(R.id.set_cookies_container); - final SwitchCompat set_cookies = rootView.findViewById(R.id.set_cookies); - boolean cookies = sharedpreferences.getBoolean(Helper.SET_COOKIES, false); - - set_cookies.setChecked(cookies); - set_cookies.setOnCheckedChangeListener((buttonView, isChecked) -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_COOKIES, isChecked); - editor.apply(); - }); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - set_cookies_container.setVisibility(View.VISIBLE); - } else { - set_cookies_container.setVisibility(View.GONE); - } - final String targeted_folder = sharedpreferences.getString(Helper.SET_FOLDER_RECORD, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()); - - set_folder = rootView.findViewById(R.id.set_folder); - set_folder.setText(targeted_folder); - set_folder.setOnClickListener(view -> { - FileListerDialog fileListerDialog = FileListerDialog.createFileListerDialog(context, style); - fileListerDialog.setDefaultDir(targeted_folder); - fileListerDialog.setFileFilter(FileListerDialog.FILE_FILTER.DIRECTORY_ONLY); - fileListerDialog.setOnFileSelectedListener((file, path) -> { - if (path == null) - path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(); - final SharedPreferences sharedpreferences1 = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - SharedPreferences.Editor editor = sharedpreferences1.edit(); - editor.putString(Helper.SET_FOLDER_RECORD, path); - editor.apply(); - set_folder.setText(path); - }); - fileListerDialog.show(); - }); - - - SeekBar toot_per_page = rootView.findViewById(R.id.set_toot_per_page); - final TextView set_toot_per_page_count = rootView.findViewById(R.id.set_toot_per_page_count); - toot_per_page.setMax(20); - int tootperpage = sharedpreferences.getInt(Helper.SET_TOOT_PER_PAGE, Helper.TOOTS_PER_PAGE); - toot_per_page.setProgress(tootperpage - Helper.TOOTS_PER_PAGE); - set_toot_per_page_count.setText(String.valueOf(tootperpage)); - - toot_per_page.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - } - - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - - int value = progress + 20; - set_toot_per_page_count.setText(String.valueOf(value)); - - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putInt(Helper.SET_TOOT_PER_PAGE, value); - editor.apply(); - } - }); - - - // NSFW Timeout - SeekBar nsfwTimeoutSeekBar = rootView.findViewById(R.id.set_nsfw_timeout); - final TextView set_nsfw_timeout_value = rootView.findViewById(R.id.set_nsfw_timeout_value); - - nsfwTimeoutSeekBar.setMax(30); - - int nsfwTimeout = sharedpreferences.getInt(Helper.SET_NSFW_TIMEOUT, 5); - - nsfwTimeoutSeekBar.setProgress(nsfwTimeout); - set_nsfw_timeout_value.setText(String.valueOf(nsfwTimeout)); - - nsfwTimeoutSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - } - - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - - set_nsfw_timeout_value.setText(String.valueOf(progress)); - - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putInt(Helper.SET_NSFW_TIMEOUT, progress); - editor.apply(); - } - }); - - - // Media Description Timeout - SeekBar medDescTimeoutSeekBar = rootView.findViewById(R.id.set_med_desc_timeout); - final TextView set_med_desc_timeout_value = rootView.findViewById(R.id.set_med_desc_timeout_value); - - medDescTimeoutSeekBar.setMax(30); - - int medDescTimeout = sharedpreferences.getInt(Helper.SET_MED_DESC_TIMEOUT, 3); - - medDescTimeoutSeekBar.setProgress(medDescTimeout); - set_med_desc_timeout_value.setText(String.valueOf(medDescTimeout)); - - medDescTimeoutSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - } - - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - - set_med_desc_timeout_value.setText(String.valueOf(progress)); - - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putInt(Helper.SET_MED_DESC_TIMEOUT, progress); - editor.apply(); - } - }); - - - LinearLayout toot_visibility_container = rootView.findViewById(R.id.toot_visibility_container); SQLiteDatabase db = Sqlite.getInstance(context.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); final Account account = new AccountDAO(context, db).getUniqAccount(userId, instance); - final ImageView set_toot_visibility = rootView.findViewById(R.id.set_toot_visibility); - //Only displayed for non locked accounts - if (account != null) { - String defaultVisibility = account.isLocked() ? "private" : "public"; - String tootVisibility = sharedpreferences.getString(Helper.SET_TOOT_VISIBILITY + "@" + account.getAcct() + "@" + account.getInstance(), defaultVisibility); - switch (tootVisibility) { - case "public": - set_toot_visibility.setImageResource(R.drawable.ic_public); + if (type == null || type.equals(TIMELINES)) { + rootView = inflater.inflate(R.layout.fragment_settings_timeline, container, false); + + SeekBar toot_per_page = rootView.findViewById(R.id.set_toot_per_page); + final TextView set_toot_per_page_count = rootView.findViewById(R.id.set_toot_per_page_count); + toot_per_page.setMax(20); + int tootperpage = sharedpreferences.getInt(Helper.SET_TOOT_PER_PAGE, Helper.TOOTS_PER_PAGE); + toot_per_page.setProgress(tootperpage - Helper.TOOTS_PER_PAGE); + set_toot_per_page_count.setText(String.valueOf(tootperpage)); + + toot_per_page.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { + @Override + public void onStopTrackingTouch(SeekBar seekBar) { + } + + @Override + public void onStartTrackingTouch(SeekBar seekBar) { + } + + @Override + public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { + + int value = progress + 20; + set_toot_per_page_count.setText(String.valueOf(value)); + + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putInt(Helper.SET_TOOT_PER_PAGE, value); + editor.apply(); + } + }); + + + boolean disableAnimatedEmoji = sharedpreferences.getBoolean(Helper.SET_DISABLE_ANIMATED_EMOJI, false); + final SwitchCompat set_disable_animated_emoji = rootView.findViewById(R.id.set_disable_animated_emoji); + set_disable_animated_emoji.setChecked(disableAnimatedEmoji); + set_disable_animated_emoji.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_DISABLE_ANIMATED_EMOJI, set_disable_animated_emoji.isChecked()); + editor.apply(); + }); + + boolean disableGif = sharedpreferences.getBoolean(Helper.SET_DISABLE_GIF, false); + final SwitchCompat set_disable_gif = rootView.findViewById(R.id.set_disable_gif); + set_disable_gif.setChecked(disableGif); + set_disable_gif.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_DISABLE_GIF, set_disable_gif.isChecked()); + editor.apply(); + if (getActivity() != null) + getActivity().recreate(); + }); + + boolean fit_preview = sharedpreferences.getBoolean(Helper.SET_FULL_PREVIEW, false); + final SwitchCompat set_fit_preview = rootView.findViewById(R.id.set_fit_preview); + set_fit_preview.setChecked(fit_preview); + + set_fit_preview.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_FULL_PREVIEW, set_fit_preview.isChecked()); + editor.apply(); + }); + + + boolean quick_reply = sharedpreferences.getBoolean(Helper.SET_QUICK_REPLY, true); + final SwitchCompat set_quick_reply = rootView.findViewById(R.id.set_quick_reply); + set_quick_reply.setChecked(quick_reply); + + set_quick_reply.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_QUICK_REPLY, set_quick_reply.isChecked()); + editor.apply(); + }); + + + boolean display_confirm = sharedpreferences.getBoolean(Helper.SET_DISPLAY_CONFIRM, true); + final SwitchCompat set_display_confirm = rootView.findViewById(R.id.set_display_confirm); + set_display_confirm.setChecked(display_confirm); + + set_display_confirm.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_DISPLAY_CONFIRM, set_display_confirm.isChecked()); + editor.apply(); + }); + + boolean bot_icon = sharedpreferences.getBoolean(Helper.SET_DISPLAY_BOT_ICON, true); + final SwitchCompat set_bot_icon = rootView.findViewById(R.id.set_display_bot_icon); + set_bot_icon.setChecked(bot_icon); + + set_bot_icon.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_DISPLAY_BOT_ICON, set_bot_icon.isChecked()); + editor.apply(); + }); + + + boolean fedilab_features_button = sharedpreferences.getBoolean(Helper.SET_DISPLAY_FEDILAB_FEATURES_BUTTON, true); + final SwitchCompat set_fedilab_features_button = rootView.findViewById(R.id.set_display_fedilab_features_button); + set_fedilab_features_button.setChecked(fedilab_features_button); + + set_fedilab_features_button.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_DISPLAY_FEDILAB_FEATURES_BUTTON, set_fedilab_features_button.isChecked()); + editor.apply(); + }); + + + boolean new_badge = sharedpreferences.getBoolean(Helper.SET_DISPLAY_NEW_BADGE, true); + final SwitchCompat set_new_badge = rootView.findViewById(R.id.set_display_new_badge); + set_new_badge.setChecked(new_badge); + + set_new_badge.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_DISPLAY_NEW_BADGE, set_new_badge.isChecked()); + editor.apply(); + }); + + boolean long_press_media = sharedpreferences.getBoolean(Helper.SET_LONG_PRESS_MEDIA, true); + final SwitchCompat set_long_press_media = rootView.findViewById(R.id.set_long_press_media); + set_long_press_media.setChecked(long_press_media); + + set_long_press_media.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_LONG_PRESS_MEDIA, set_long_press_media.isChecked()); + editor.apply(); + }); + + boolean blur_sensitive = sharedpreferences.getBoolean(Helper.SET_BLUR_SENSITIVE, true); + final SwitchCompat set_blur_sensitive = rootView.findViewById(R.id.set_blur_sensitive); + set_blur_sensitive.setChecked(blur_sensitive); + + set_blur_sensitive.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_BLUR_SENSITIVE, set_blur_sensitive.isChecked()); + editor.apply(); + }); + + + boolean hide_delete_notification_on_tab = sharedpreferences.getBoolean(Helper.SET_HIDE_DELETE_BUTTON_ON_TAB, false); + final SwitchCompat set_hide_delete_notification_on_tab = rootView.findViewById(R.id.set_hide_delete_notification_on_tab); + set_hide_delete_notification_on_tab.setChecked(hide_delete_notification_on_tab); + + set_hide_delete_notification_on_tab.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_HIDE_DELETE_BUTTON_ON_TAB, set_hide_delete_notification_on_tab.isChecked()); + editor.apply(); + if (getActivity() != null) + getActivity().recreate(); + Intent intent = new Intent(context, MainActivity.class); + if (getActivity() != null) + getActivity().finish(); + startActivity(intent); + }); + + boolean remember_position_home = sharedpreferences.getBoolean(Helper.SET_REMEMBER_POSITION_HOME, true); + final SwitchCompat set_remember_position = rootView.findViewById(R.id.set_remember_position); + set_remember_position.setChecked(remember_position_home); + + set_remember_position.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_REMEMBER_POSITION_HOME, set_remember_position.isChecked()); + editor.apply(); + }); + + + boolean expand_media = sharedpreferences.getBoolean(Helper.SET_EXPAND_MEDIA, false); + final SwitchCompat set_expand_media = rootView.findViewById(R.id.set_expand_image); + set_expand_media.setChecked(expand_media); + + set_expand_media.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_EXPAND_MEDIA, set_expand_media.isChecked()); + editor.apply(); + }); + + boolean expand_cw = sharedpreferences.getBoolean(Helper.SET_EXPAND_CW, false); + final SwitchCompat set_expand_cw = rootView.findViewById(R.id.set_expand_cw); + set_expand_cw.setChecked(expand_cw); + + set_expand_cw.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_EXPAND_CW, set_expand_cw.isChecked()); + editor.apply(); + }); + + boolean notif_validation_fav = sharedpreferences.getBoolean(Helper.SET_NOTIF_VALIDATION_FAV, false); + final SwitchCompat set_share_validation_fav = rootView.findViewById(R.id.set_share_validation_fav); + set_share_validation_fav.setChecked(notif_validation_fav); + + set_share_validation_fav.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_NOTIF_VALIDATION_FAV, set_share_validation_fav.isChecked()); + editor.apply(); + }); + + boolean display_content_after_fetch_more = sharedpreferences.getBoolean(Helper.SET_DISPLAY_CONTENT_AFTER_FM, true); + final SwitchCompat set_display_content_after_fetch_more = rootView.findViewById(R.id.set_display_content_after_fetch_more); + set_display_content_after_fetch_more.setChecked(display_content_after_fetch_more); + set_display_content_after_fetch_more.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_DISPLAY_CONTENT_AFTER_FM, set_display_content_after_fetch_more.isChecked()); + editor.apply(); + }); + + boolean display_card = sharedpreferences.getBoolean(Helper.SET_DISPLAY_CARD, false); + + final SwitchCompat set_display_card = rootView.findViewById(R.id.set_display_card); + set_display_card.setChecked(display_card); + set_display_card.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_DISPLAY_CARD, set_display_card.isChecked()); + editor.apply(); + }); + + + boolean display_video_preview = sharedpreferences.getBoolean(Helper.SET_DISPLAY_VIDEO_PREVIEWS, true); + final SwitchCompat set_display_video_preview = rootView.findViewById(R.id.set_display_video_preview); + set_display_video_preview.setChecked(display_video_preview); + + set_display_video_preview.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_DISPLAY_VIDEO_PREVIEWS, set_display_video_preview.isChecked()); + editor.apply(); + }); + + boolean notif_validation = sharedpreferences.getBoolean(Helper.SET_NOTIF_VALIDATION, true); + final SwitchCompat set_share_validation = rootView.findViewById(R.id.set_share_validation); + set_share_validation.setChecked(notif_validation); + + set_share_validation.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_NOTIF_VALIDATION, set_share_validation.isChecked()); + editor.apply(); + }); + } else if (type == NOTIFICATIONS) { + rootView = inflater.inflate(R.layout.fragment_settings_notifications, container, false); + + + boolean notif_follow = sharedpreferences.getBoolean(Helper.SET_NOTIF_FOLLOW, true); + boolean notif_add = sharedpreferences.getBoolean(Helper.SET_NOTIF_ADD, true); + boolean notif_mention = sharedpreferences.getBoolean(Helper.SET_NOTIF_MENTION, true); + boolean notif_share = sharedpreferences.getBoolean(Helper.SET_NOTIF_SHARE, true); + boolean notif_poll = sharedpreferences.getBoolean(Helper.SET_NOTIF_POLL, true); + + boolean notif_wifi = sharedpreferences.getBoolean(Helper.SET_WIFI_ONLY, false); + boolean notif_silent = sharedpreferences.getBoolean(Helper.SET_NOTIF_SILENT, false); + + + final String time_from = sharedpreferences.getString(Helper.SET_TIME_FROM, "07:00"); + final String time_to = sharedpreferences.getString(Helper.SET_TIME_TO, "22:00"); + + + final SwitchCompat set_notif_follow = rootView.findViewById(R.id.set_notif_follow); + final SwitchCompat set_notif_follow_add = rootView.findViewById(R.id.set_notif_follow_add); + final SwitchCompat set_notif_follow_mention = rootView.findViewById(R.id.set_notif_follow_mention); + final SwitchCompat set_notif_follow_share = rootView.findViewById(R.id.set_notif_follow_share); + final SwitchCompat set_notif_follow_poll = rootView.findViewById(R.id.set_notif_follow_poll); + + + final SwitchCompat switchCompatWIFI = rootView.findViewById(R.id.set_wifi_only); + final SwitchCompat switchCompatSilent = rootView.findViewById(R.id.set_silence); + + final Button settings_time_from = rootView.findViewById(R.id.settings_time_from); + final Button settings_time_to = rootView.findViewById(R.id.settings_time_to); + + final LinearLayout channels_container = rootView.findViewById(R.id.channels_container); + final Button sound_boost = rootView.findViewById(R.id.sound_boost); + final Button sound_fav = rootView.findViewById(R.id.sound_fav); + final Button sound_follow = rootView.findViewById(R.id.sound_follow); + final Button sound_mention = rootView.findViewById(R.id.sound_mention); + final Button sound_poll = rootView.findViewById(R.id.sound_poll); + final Button sound_backup = rootView.findViewById(R.id.sound_backup); + final Button sound_media = rootView.findViewById(R.id.sound_media); + final ImageButton set_hide_status_bar = rootView.findViewById(R.id.set_hide_status_bar); + + Button set_notif_sound = rootView.findViewById(R.id.set_notif_sound); + settings_time_from.setText(time_from); + settings_time_to.setText(time_to); + final LinearLayout set_hide_status_bar_container = rootView.findViewById(R.id.set_hide_status_bar_container); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + set_notif_sound.setVisibility(View.GONE); + channels_container.setVisibility(View.VISIBLE); + set_hide_status_bar_container.setVisibility(View.VISIBLE); + set_hide_status_bar.setOnClickListener(v -> { + Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS); + intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName()); + intent.putExtra(Settings.EXTRA_CHANNEL_ID, LiveNotificationDelayedService.CHANNEL_ID); + startActivity(intent); + }); + + + sound_boost.setOnClickListener(v -> { + Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS); + intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName()); + intent.putExtra(Settings.EXTRA_CHANNEL_ID, "channel_boost"); + startActivity(intent); + }); + + sound_fav.setOnClickListener(v -> { + Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS); + intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName()); + intent.putExtra(Settings.EXTRA_CHANNEL_ID, "channel_fav"); + startActivity(intent); + }); + + sound_follow.setOnClickListener(v -> { + Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS); + intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName()); + intent.putExtra(Settings.EXTRA_CHANNEL_ID, "channel_follow"); + startActivity(intent); + }); + + sound_mention.setOnClickListener(v -> { + Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS); + intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName()); + intent.putExtra(Settings.EXTRA_CHANNEL_ID, "channel_mention"); + startActivity(intent); + }); + + sound_poll.setOnClickListener(v -> { + Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS); + intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName()); + intent.putExtra(Settings.EXTRA_CHANNEL_ID, "channel_poll"); + startActivity(intent); + }); + + sound_backup.setOnClickListener(v -> { + Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS); + intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName()); + intent.putExtra(Settings.EXTRA_CHANNEL_ID, "channel_backup"); + startActivity(intent); + }); + + sound_media.setOnClickListener(v -> { + Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS); + intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName()); + intent.putExtra(Settings.EXTRA_CHANNEL_ID, "channel_store"); + startActivity(intent); + }); + } else { + set_notif_sound.setVisibility(View.VISIBLE); + channels_container.setVisibility(View.GONE); + set_notif_sound.setOnClickListener(v -> { + Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER); + intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION); + intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, context.getString(R.string.select_sound)); + intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, (Uri) null); + startActivityForResult(intent, ACTIVITY_CHOOSE_SOUND); + }); + } + + + boolean enable_time_slot = sharedpreferences.getBoolean(Helper.SET_ENABLE_TIME_SLOT, true); + final SwitchCompat set_enable_time_slot = rootView.findViewById(R.id.set_enable_time_slot); + set_enable_time_slot.setChecked(enable_time_slot); + + set_enable_time_slot.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_ENABLE_TIME_SLOT, set_enable_time_slot.isChecked()); + editor.apply(); + }); + + + settings_time_from.setOnClickListener(v -> { + String[] datetime = time_from.split(":"); + TimePickerDialog timePickerDialog = new TimePickerDialog(getActivity(), style, (view, hourOfDay, minute) -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + String hours = (String.valueOf(hourOfDay).length() == 1) ? "0" + hourOfDay : String.valueOf(hourOfDay); + String minutes = (String.valueOf(minute).length() == 1) ? "0" + minute : String.valueOf(minute); + String newDate = hours + ":" + minutes; + if (Helper.compareDate(context, newDate, false)) { + editor.putString(Helper.SET_TIME_FROM, newDate); + editor.apply(); + settings_time_from.setText(newDate); + } else { + String ateRef = sharedpreferences.getString(Helper.SET_TIME_TO, "22:00"); + Toasty.error(context, context.getString(R.string.settings_time_lower, ateRef), Toast.LENGTH_LONG).show(); + } + }, Integer.parseInt(datetime[0]), Integer.parseInt(datetime[1]), true); + timePickerDialog.setTitle(context.getString(R.string.settings_hour_init)); + timePickerDialog.show(); + }); + + settings_time_to.setOnClickListener(v -> { + String[] datetime = time_to.split(":"); + TimePickerDialog timePickerDialog = new TimePickerDialog(getActivity(), style, (view, hourOfDay, minute) -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + String hours = (String.valueOf(hourOfDay).length() == 1) ? "0" + hourOfDay : String.valueOf(hourOfDay); + String minutes = (String.valueOf(minute).length() == 1) ? "0" + minute : String.valueOf(minute); + String newDate = hours + ":" + minutes; + if (Helper.compareDate(context, newDate, true)) { + editor.putString(Helper.SET_TIME_TO, newDate); + editor.apply(); + settings_time_to.setText(newDate); + } else { + String ateRef = sharedpreferences.getString(Helper.SET_TIME_FROM, "07:00"); + Toasty.error(context, context.getString(R.string.settings_time_greater, ateRef), Toast.LENGTH_LONG).show(); + } + }, Integer.parseInt(datetime[0]), Integer.parseInt(datetime[1]), true); + timePickerDialog.setTitle(context.getString(R.string.settings_hour_end)); + timePickerDialog.show(); + }); + + + final Spinner action_notification = rootView.findViewById(R.id.action_notification); + ArrayAdapter adapterAction = ArrayAdapter.createFromResource(Objects.requireNonNull(getActivity()), + R.array.action_notification, android.R.layout.simple_spinner_dropdown_item); + action_notification.setAdapter(adapterAction); + int positionNotificationAntion; + switch (sharedpreferences.getInt(Helper.SET_NOTIFICATION_ACTION, Helper.ACTION_ACTIVE)) { + case Helper.ACTION_ACTIVE: + positionNotificationAntion = 0; break; - case "unlisted": - set_toot_visibility.setImageResource(R.drawable.ic_lock_open); + case Helper.ACTION_SILENT: + positionNotificationAntion = 1; break; - case "private": - set_toot_visibility.setImageResource(R.drawable.ic_lock_outline); + default: + positionNotificationAntion = 0; + } + notificationCount = 0; + action_notification.setSelection(positionNotificationAntion); + action_notification.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + if (notificationCount > 0) { + SharedPreferences.Editor editor = sharedpreferences.edit(); + + switch (position) { + case 0: + editor.putInt(Helper.SET_NOTIFICATION_ACTION, Helper.ACTION_ACTIVE); + editor.apply(); + break; + case 1: + editor.putInt(Helper.SET_NOTIFICATION_ACTION, Helper.ACTION_SILENT); + editor.apply(); + break; + } + } else { + notificationCount++; + } + } + + @Override + public void onNothingSelected(AdapterView parent) { + + } + }); + + set_notif_follow.setChecked(notif_follow); + set_notif_follow_add.setChecked(notif_add); + set_notif_follow_mention.setChecked(notif_mention); + set_notif_follow_share.setChecked(notif_share); + set_notif_follow_poll.setChecked(notif_poll); + + + switchCompatWIFI.setChecked(notif_wifi); + switchCompatSilent.setChecked(notif_silent); + + + set_notif_follow.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_NOTIF_FOLLOW, set_notif_follow.isChecked()); + editor.apply(); + }); + set_notif_follow_add.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_NOTIF_ADD, set_notif_follow_add.isChecked()); + editor.apply(); + }); + set_notif_follow_mention.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_NOTIF_MENTION, set_notif_follow_mention.isChecked()); + editor.apply(); + }); + set_notif_follow_share.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_NOTIF_SHARE, set_notif_follow_share.isChecked()); + editor.apply(); + }); + set_notif_follow_poll.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_NOTIF_POLL, set_notif_follow_poll.isChecked()); + editor.apply(); + }); + + + switchCompatWIFI.setOnCheckedChangeListener((buttonView, isChecked) -> { + // Save the state here + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_WIFI_ONLY, isChecked); + editor.apply(); + + }); + + final Spinner led_colour_spinner = rootView.findViewById(R.id.led_colour_spinner); + final TextView ledLabel = rootView.findViewById(R.id.set_led_colour_label); + + switchCompatSilent.setOnCheckedChangeListener((buttonView, isChecked) -> { + // Save the state here + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_NOTIF_SILENT, isChecked); + editor.apply(); + + if (isChecked) { + ledLabel.setEnabled(true); + led_colour_spinner.setEnabled(true); + } else { + ledLabel.setEnabled(false); + for (View lol : led_colour_spinner.getTouchables()) { + lol.setEnabled(false); + } + } + }); + + if (sharedpreferences.getBoolean(Helper.SET_NOTIF_SILENT, false)) { + + ledLabel.setEnabled(true); + led_colour_spinner.setEnabled(true); + + ArrayAdapter adapterLEDColour = ArrayAdapter.createFromResource(Objects.requireNonNull(getActivity()), R.array.led_colours, android.R.layout.simple_spinner_dropdown_item); + led_colour_spinner.setAdapter(adapterLEDColour); + int positionSpinnerLEDColour = (sharedpreferences.getInt(Helper.SET_LED_COLOUR, Helper.LED_COLOUR)); + led_colour_spinner.setSelection(positionSpinnerLEDColour); + + ledCount = 0; + led_colour_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + if (ledCount > 0) { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putInt(Helper.SET_LED_COLOUR, position); + editor.apply(); + } else { + ledCount++; + } + + } + + @Override + public void onNothingSelected(AdapterView parent) { + } + }); + } else { + ledLabel.setEnabled(false); + for (View lol : led_colour_spinner.getTouchables()) { + lol.setEnabled(false); + } + } + + boolean allow_live_notifications = sharedpreferences.getBoolean(Helper.SET_ALLOW_STREAM + userId + instance, true); + TextView set_allow_live_notifications_title = rootView.findViewById(R.id.set_allow_live_notifications_title); + if (account != null) { + set_allow_live_notifications_title.setText(context.getString(R.string.set_allow_live_notifications, account.getAcct() + "@" + account.getInstance())); + } + final SwitchCompat set_allow_live_notifications = rootView.findViewById(R.id.set_allow_live_notifications); + set_allow_live_notifications.setChecked(allow_live_notifications); + set_allow_live_notifications.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_ALLOW_STREAM + userId + instance, set_allow_live_notifications.isChecked()); + editor.apply(); + if (set_allow_live_notifications.isChecked()) { + LiveNotificationDelayedService.totalAccount++; + } else { + LiveNotificationDelayedService.totalAccount--; + } + if (set_allow_live_notifications.isChecked()) { + LiveNotificationDelayedService.totalAccount++; + } else { + LiveNotificationDelayedService.totalAccount--; + } + Helper.startStreaming(context); + + }); + + final ImageButton set_allow_live_notifications_others = rootView.findViewById(R.id.set_allow_live_notifications_others); + set_allow_live_notifications_others.setOnClickListener(view -> { + Intent intent = new Intent(context, LiveNotificationSettingsAccountsActivity.class); + startActivity(intent); + }); + + + boolean notify = sharedpreferences.getBoolean(Helper.SET_NOTIFY, true); + final SwitchCompat switchCompatNotify = rootView.findViewById(R.id.set_notify); + switchCompatNotify.setChecked(notify); + final LinearLayout notification_container = rootView.findViewById(R.id.notification_container); + if (notify) { + notification_container.setVisibility(View.VISIBLE); + } else { + notification_container.setVisibility(View.GONE); + } + switchCompatNotify.setOnCheckedChangeListener((buttonView, isChecked) -> { + // Save the state here + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_NOTIFY, isChecked); + editor.apply(); + if (isChecked) { + notification_container.setVisibility(View.VISIBLE); + notification_container.setVisibility(View.VISIBLE); + Helper.startStreaming(context); + } else { + context.sendBroadcast(new Intent(context, StopLiveNotificationReceiver.class)); + context.sendBroadcast(new Intent(context, StopDelayedNotificationReceiver.class)); + ApplicationJob.cancelAllJob(NotificationsSyncJob.NOTIFICATION_REFRESH); + notification_container.setVisibility(View.GONE); + } + }); + + + //Live notification mode + final Spinner set_live_type = rootView.findViewById(R.id.set_live_type); + String[] labels = {context.getString(R.string.live_notif), context.getString(R.string.live_delayed), context.getString(R.string.no_live_notif)}; + ArrayAdapter adapterLive = new ArrayAdapter<>(Objects.requireNonNull(getActivity()), + android.R.layout.simple_spinner_dropdown_item, labels); + + LinearLayout live_notif_per_account = rootView.findViewById(R.id.live_notif_per_account); + set_live_type.setAdapter(adapterLive); + if (Helper.liveNotifType(context) == Helper.NOTIF_NONE) { + live_notif_per_account.setVisibility(View.GONE); + } + TextView set_live_type_indication = rootView.findViewById(R.id.set_live_type_indication); + switch (Helper.liveNotifType(context)) { + case Helper.NOTIF_LIVE: + set_live_type_indication.setText(R.string.live_notif_indication); break; - case "direct": - set_toot_visibility.setImageResource(R.drawable.ic_mail_outline); + case Helper.NOTIF_DELAYED: + set_live_type_indication.setText(R.string.set_live_type_indication); + break; + case Helper.NOTIF_NONE: + set_live_type_indication.setText(R.string.no_live_indication); break; } - } else { - toot_visibility_container.setVisibility(View.GONE); - } - - set_toot_visibility.setOnClickListener(v -> { - final SharedPreferences sharedpreferences12 = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - - AlertDialog.Builder dialog = new AlertDialog.Builder(context, style); - dialog.setTitle(R.string.toot_visibility_tilte); - final String[] stringArray = getResources().getStringArray(R.array.toot_visibility); - final ArrayAdapter arrayAdapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, stringArray); - dialog.setNegativeButton(R.string.cancel, (dialog1, position) -> dialog1.dismiss()); - - dialog.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() { + set_live_type.setSelection(Helper.liveNotifType(context)); + liveNotificationCount = 0; + set_live_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override - public void onClick(DialogInterface dialog, int position) { + public void onItemSelected(AdapterView parent, View view, int position, long id) { + if (liveNotificationCount > 0) { + SharedPreferences.Editor editor = sharedpreferences.edit(); + + context.sendBroadcast(new Intent(context, StopLiveNotificationReceiver.class)); + context.sendBroadcast(new Intent(context, StopDelayedNotificationReceiver.class)); + ApplicationJob.cancelAllJob(NotificationsSyncJob.NOTIFICATION_REFRESH); + switch (position) { + case Helper.NOTIF_LIVE: + editor.putBoolean(Helper.SET_LIVE_NOTIFICATIONS, true); + editor.putBoolean(Helper.SET_DELAYED_NOTIFICATIONS, false); + live_notif_per_account.setVisibility(View.VISIBLE); + editor.commit(); + set_live_type_indication.setText(R.string.live_notif_indication); + Helper.startStreaming(context); + break; + case Helper.NOTIF_DELAYED: + editor.putBoolean(Helper.SET_LIVE_NOTIFICATIONS, false); + editor.putBoolean(Helper.SET_DELAYED_NOTIFICATIONS, true); + live_notif_per_account.setVisibility(View.VISIBLE); + set_live_type_indication.setText(R.string.set_live_type_indication); + editor.commit(); + Helper.startStreaming(context); + break; + case Helper.NOTIF_NONE: + editor.putBoolean(Helper.SET_LIVE_NOTIFICATIONS, false); + editor.putBoolean(Helper.SET_DELAYED_NOTIFICATIONS, false); + editor.commit(); + set_live_type_indication.setText(R.string.no_live_indication); + live_notif_per_account.setVisibility(View.GONE); + NotificationsSyncJob.schedule(false); + break; + } + } else { + liveNotificationCount++; + } + } + + @Override + public void onNothingSelected(AdapterView parent) { + + } + }); + + + } else if (type == ADMIN) { + rootView = inflater.inflate(R.layout.fragment_settings_admin, container, false); + + boolean display_admin_menu = sharedpreferences.getBoolean(Helper.SET_DISPLAY_ADMIN_MENU + userId + instance, false); + + final SwitchCompat set_display_admin_menu = rootView.findViewById(R.id.set_display_admin_menu); + set_display_admin_menu.setChecked(display_admin_menu); + set_display_admin_menu.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_DISPLAY_ADMIN_MENU + userId + instance, set_display_admin_menu.isChecked()); + editor.apply(); + Bundle b = new Bundle(); + if (set_display_admin_menu.isChecked()) { + b.putString("menu", "show_admin"); + } else { + b.putString("menu", "hide_admin"); + } + Intent intentBC = new Intent(Helper.RECEIVE_HIDE_ITEM); + intentBC.putExtras(b); + LocalBroadcastManager.getInstance(context).sendBroadcast(intentBC); + }); + + boolean display_admin_statuses = sharedpreferences.getBoolean(Helper.SET_DISPLAY_ADMIN_STATUSES + userId + instance, false); + + final SwitchCompat set_display_admin_statuses = rootView.findViewById(R.id.set_display_admin_statuses); + set_display_admin_statuses.setChecked(display_admin_statuses); + set_display_admin_statuses.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_DISPLAY_ADMIN_STATUSES + userId + instance, set_display_admin_statuses.isChecked()); + editor.apply(); + }); + + } else if (type == INTERFACE) { + rootView = inflater.inflate(R.layout.fragment_settings_interface, container, false); + + + ImageButton btn_select_icon = rootView.findViewById(R.id.btn_select_icon); + btn_select_icon.setOnClickListener(v -> { + + AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, style); + View icon_selector = inflater.inflate(R.layout.dialog_icon_selector, new LinearLayout(context), false); + dialogBuilder.setView(icon_selector); + dialogBuilder.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()); + dialogBuilder.setCancelable(true); + AlertDialog icon_selector_dialog = dialogBuilder.create(); + icon_selector_dialog.show(); + + icon_selector.findViewById(R.id.icon_bubbles).setOnClickListener(v1 -> { + hideAllIcons(context); + setIcon(context, "Bubbles"); + SharedPreferences.Editor editor2 = sharedpreferences.edit(); + editor2.putString(Helper.LOGO_LAUNCHER, "bubbles"); + editor2.apply(); + BaseMainActivity.mLauncher = BUBBLES; + icon_selector_dialog.dismiss(); + }); + + icon_selector.findViewById(R.id.icon_fediverse).setOnClickListener(v1 -> { + hideAllIcons(context); + setIcon(context, "Fediverse"); + SharedPreferences.Editor editor2 = sharedpreferences.edit(); + editor2.putString(Helper.LOGO_LAUNCHER, "fediverse"); + editor2.apply(); + BaseMainActivity.mLauncher = FEDIVERSE; + icon_selector_dialog.dismiss(); + }); + + icon_selector.findViewById(R.id.icon_hero).setOnClickListener(v1 -> { + hideAllIcons(context); + setIcon(context, "Hero"); + SharedPreferences.Editor editor2 = sharedpreferences.edit(); + editor2.putString(Helper.LOGO_LAUNCHER, "hero"); + editor2.apply(); + BaseMainActivity.mLauncher = HERO; + icon_selector_dialog.dismiss(); + }); + + icon_selector.findViewById(R.id.icon_atom).setOnClickListener(v1 -> { + hideAllIcons(context); + setIcon(context, "Atom"); + SharedPreferences.Editor editor2 = sharedpreferences.edit(); + editor2.putString(Helper.LOGO_LAUNCHER, "atom"); + editor2.apply(); + BaseMainActivity.mLauncher = ATOM; + icon_selector_dialog.dismiss(); + }); + + icon_selector.findViewById(R.id.icon_braincrash).setOnClickListener(v1 -> { + hideAllIcons(context); + setIcon(context, "BrainCrash"); + SharedPreferences.Editor editor2 = sharedpreferences.edit(); + editor2.putString(Helper.LOGO_LAUNCHER, "braincrash"); + editor2.apply(); + BaseMainActivity.mLauncher = BRAINCRASH; + icon_selector_dialog.dismiss(); + }); + + icon_selector.findViewById(R.id.icon_mastalab).setOnClickListener(v1 -> { + hideAllIcons(context); + setIcon(context, "Mastalab"); + SharedPreferences.Editor editor2 = sharedpreferences.edit(); + editor2.putString(Helper.LOGO_LAUNCHER, "mastalab"); + editor2.apply(); + BaseMainActivity.mLauncher = MASTALAB; + icon_selector_dialog.dismiss(); + }); + + }); + + + //Translators + final Spinner translation_layout_spinner = rootView.findViewById(R.id.translation_layout_spinner); + + boolean trans_forced = sharedpreferences.getBoolean(Helper.SET_TRANS_FORCED, false); + final CheckBox set_trans_forced = rootView.findViewById(R.id.set_trans_forced); + set_trans_forced.setChecked(trans_forced); + set_trans_forced.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_TRANS_FORCED, set_trans_forced.isChecked()); + editor.apply(); + }); + + List translatorsList = Arrays.asList(getResources().getStringArray(R.array.settings_translation)); + ArrayList trans = new ArrayList<>(translatorsList); + trans.add(getString(R.string.no)); + + ArrayAdapter adapterTrans = new ArrayAdapter<>(getActivity(), + android.R.layout.simple_spinner_dropdown_item, trans); + translation_layout_spinner.setAdapter(adapterTrans); + int positionSpinnerTrans; + your_api_key = rootView.findViewById(R.id.translation_key); + switch (sharedpreferences.getInt(Helper.SET_TRANSLATOR, Helper.TRANS_YANDEX)) { + case Helper.TRANS_YANDEX: + positionSpinnerTrans = 0; + your_api_key.setVisibility(View.VISIBLE); + your_api_key.setText(sharedpreferences.getString(Helper.SET_YANDEX_API_KEY, "")); + break; + case Helper.TRANS_DEEPL: + positionSpinnerTrans = 1; + your_api_key.setVisibility(View.VISIBLE); + your_api_key.setText(sharedpreferences.getString(Helper.SET_DEEPL_API_KEY, "")); + break; + case Helper.TRANS_SYSTRAN: + positionSpinnerTrans = 2; + your_api_key.setVisibility(View.VISIBLE); + your_api_key.setText(sharedpreferences.getString(Helper.SET_SYSTRAN_API_KEY, "")); + break; + case Helper.TRANS_NONE: + positionSpinnerTrans = 3; + your_api_key.setVisibility(View.GONE); + break; + default: + your_api_key.setVisibility(View.VISIBLE); + positionSpinnerTrans = 0; + } + translation_layout_spinner.setSelection(positionSpinnerTrans); + countTrans = 0; + translation_layout_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + if (countTrans > 0) { + SharedPreferences.Editor editor = sharedpreferences.edit(); + switch (position) { + case 0: + your_api_key.setVisibility(View.VISIBLE); + editor.putInt(Helper.SET_TRANSLATOR, Helper.TRANS_YANDEX); + editor.commit(); + your_api_key.setText(sharedpreferences.getString(Helper.SET_YANDEX_API_KEY, "")); + + break; + case 1: + your_api_key.setVisibility(View.VISIBLE); + editor.putInt(Helper.SET_TRANSLATOR, Helper.TRANS_DEEPL); + editor.commit(); + your_api_key.setText(sharedpreferences.getString(Helper.SET_DEEPL_API_KEY, "")); + break; + case 2: + your_api_key.setVisibility(View.VISIBLE); + editor.putInt(Helper.SET_TRANSLATOR, Helper.TRANS_SYSTRAN); + editor.commit(); + your_api_key.setText(sharedpreferences.getString(Helper.SET_SYSTRAN_API_KEY, "")); + break; + case 3: + your_api_key.setVisibility(View.GONE); + set_trans_forced.isChecked(); + editor.putBoolean(Helper.SET_TRANS_FORCED, false); + editor.putInt(Helper.SET_TRANSLATOR, Helper.TRANS_NONE); + editor.commit(); + break; + } + } else { + countTrans++; + } + } + + @Override + public void onNothingSelected(AdapterView parent) { + + } + + }); + + + // Media Description Timeout + SeekBar medDescTimeoutSeekBar = rootView.findViewById(R.id.set_med_desc_timeout); + final TextView set_med_desc_timeout_value = rootView.findViewById(R.id.set_med_desc_timeout_value); + + medDescTimeoutSeekBar.setMax(30); + + int medDescTimeout = sharedpreferences.getInt(Helper.SET_MED_DESC_TIMEOUT, 3); + + medDescTimeoutSeekBar.setProgress(medDescTimeout); + set_med_desc_timeout_value.setText(String.valueOf(medDescTimeout)); + + medDescTimeoutSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { + @Override + public void onStopTrackingTouch(SeekBar seekBar) { + } + + @Override + public void onStartTrackingTouch(SeekBar seekBar) { + } + + @Override + public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { + + set_med_desc_timeout_value.setText(String.valueOf(progress)); + + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putInt(Helper.SET_MED_DESC_TIMEOUT, progress); + editor.apply(); + } + }); + + + // NSFW Timeout + SeekBar nsfwTimeoutSeekBar = rootView.findViewById(R.id.set_nsfw_timeout); + final TextView set_nsfw_timeout_value = rootView.findViewById(R.id.set_nsfw_timeout_value); + + nsfwTimeoutSeekBar.setMax(30); + + int nsfwTimeout = sharedpreferences.getInt(Helper.SET_NSFW_TIMEOUT, 5); + + nsfwTimeoutSeekBar.setProgress(nsfwTimeout); + set_nsfw_timeout_value.setText(String.valueOf(nsfwTimeout)); + + nsfwTimeoutSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { + @Override + public void onStopTrackingTouch(SeekBar seekBar) { + } + + @Override + public void onStartTrackingTouch(SeekBar seekBar) { + } + + @Override + public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { + + set_nsfw_timeout_value.setText(String.valueOf(progress)); + + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putInt(Helper.SET_NSFW_TIMEOUT, progress); + editor.apply(); + } + }); + + + final String targeted_folder = sharedpreferences.getString(Helper.SET_FOLDER_RECORD, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()); + + set_folder = rootView.findViewById(R.id.set_folder); + set_folder.setText(targeted_folder); + set_folder.setOnClickListener(view -> { + FileListerDialog fileListerDialog = FileListerDialog.createFileListerDialog(context, style); + fileListerDialog.setDefaultDir(targeted_folder); + fileListerDialog.setFileFilter(FileListerDialog.FILE_FILTER.DIRECTORY_ONLY); + fileListerDialog.setOnFileSelectedListener((file, path) -> { + if (path == null) + path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(); + final SharedPreferences sharedpreferences1 = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + SharedPreferences.Editor editor = sharedpreferences1.edit(); + editor.putString(Helper.SET_FOLDER_RECORD, path); + editor.apply(); + set_folder.setText(path); + }); + fileListerDialog.show(); + }); + + + Spinner set_mode = rootView.findViewById(R.id.set_mode); + String[] mode_labels = {context.getString(R.string.set_normal), context.getString(R.string.set_compact), context.getString(R.string.set_console)}; + ArrayAdapter adapterMode = new ArrayAdapter<>(Objects.requireNonNull(getActivity()), + android.R.layout.simple_spinner_dropdown_item, mode_labels); + set_mode.setAdapter(adapterMode); + boolean compact_mode = sharedpreferences.getBoolean(Helper.SET_COMPACT_MODE, false); + boolean console_mode = sharedpreferences.getBoolean(Helper.SET_CONSOLE_MODE, false); + + if (compact_mode) { + set_mode.setSelection(1); + } else if (console_mode) { + set_mode.setSelection(2); + } else { + set_mode.setSelection(0); + } + + set_mode.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + SharedPreferences.Editor editor = sharedpreferences.edit(); + switch (position) { + case 0: + editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_COMPACT_MODE, false); + editor.putBoolean(Helper.SET_CONSOLE_MODE, false); + editor.apply(); + break; + case 1: + editor.putBoolean(Helper.SET_COMPACT_MODE, true); + editor.putBoolean(Helper.SET_CONSOLE_MODE, false); + editor.apply(); + break; + case 2: + editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_COMPACT_MODE, false); + editor.putBoolean(Helper.SET_CONSOLE_MODE, true); + editor.apply(); + break; + } + } + + @Override + public void onNothingSelected(AdapterView parent) { + + } + }); + + + int truncate_toots_size = sharedpreferences.getInt(Helper.SET_TRUNCATE_TOOTS_SIZE, 0); + SeekBar set_truncate_size = rootView.findViewById(R.id.set_truncate_size); + set_truncate_size.setMax(20); + set_truncate_size.setProgress(truncate_toots_size); + TextView set_truncate_toots = rootView.findViewById(R.id.set_truncate_toots); + set_truncate_toots.setText(String.valueOf(truncate_toots_size)); + set_truncate_size.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { + @Override + public void onStopTrackingTouch(SeekBar seekBar) { + } + + @Override + public void onStartTrackingTouch(SeekBar seekBar) { + } + + @Override + public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { + set_truncate_toots.setText(String.valueOf(progress)); + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putInt(Helper.SET_TRUNCATE_TOOTS_SIZE, progress); + editor.apply(); + } + }); + + + int video_cache_size = sharedpreferences.getInt(Helper.SET_VIDEO_CACHE, Helper.DEFAULT_VIDEO_CACHE_MB); + SeekBar set_video_cache_size = rootView.findViewById(R.id.set_video_cache_size); + set_video_cache_size.setMax(5 * Helper.DEFAULT_VIDEO_CACHE_MB); + set_video_cache_size.setProgress(video_cache_size); + TextView set_video_cache = rootView.findViewById(R.id.set_video_cache); + set_video_cache.setText(String.valueOf(video_cache_size)); + set_video_cache_size.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { + @Override + public void onStopTrackingTouch(SeekBar seekBar) { + } + + @Override + public void onStartTrackingTouch(SeekBar seekBar) { + } + + @Override + public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { + set_video_cache.setText(String.valueOf(progress)); + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putInt(Helper.SET_VIDEO_CACHE, progress); + editor.apply(); + } + }); + + + boolean send_crash_reports = sharedpreferences.getBoolean(Helper.SET_SEND_CRASH_REPORTS, false); + final SwitchCompat set_enable_crash_report = rootView.findViewById(R.id.set_enable_crash_report); + set_enable_crash_report.setChecked(send_crash_reports); + + set_enable_crash_report.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_SEND_CRASH_REPORTS, set_enable_crash_report.isChecked()); + editor.apply(); + if (getActivity() != null) + getActivity().recreate(); + }); + + boolean unfollow_validation = sharedpreferences.getBoolean(Helper.SET_UNFOLLOW_VALIDATION, true); + final SwitchCompat set_unfollow_validation = rootView.findViewById(R.id.set_unfollow_validation); + set_unfollow_validation.setChecked(unfollow_validation); + + set_unfollow_validation.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_UNFOLLOW_VALIDATION, set_unfollow_validation.isChecked()); + editor.apply(); + }); + boolean display_timeline_in_list = sharedpreferences.getBoolean(Helper.SET_DISPLAY_TIMELINE_IN_LIST, false); + final SwitchCompat set_display_timeline_in_list = rootView.findViewById(R.id.set_display_timeline_in_list); + set_display_timeline_in_list.setChecked(display_timeline_in_list); + + set_display_timeline_in_list.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_DISPLAY_TIMELINE_IN_LIST, set_display_timeline_in_list.isChecked()); + editor.apply(); + Bundle b = new Bundle(); + if (set_display_timeline_in_list.isChecked()) { + b.putString("menu", "show_list_button"); + } else { + b.putString("menu", "hide_list_button"); + } + Intent intentBC = new Intent(Helper.RECEIVE_HIDE_ITEM); + intentBC.putExtras(b); + LocalBroadcastManager.getInstance(context).sendBroadcast(intentBC); + }); + + + your_api_key.addTextChangedListener(new TextWatcher() { + @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(); + int translatore = sharedpreferences.getInt(Helper.SET_TRANSLATOR, Helper.TRANS_YANDEX); + String store = null; + if (translatore == Helper.TRANS_YANDEX) + store = Helper.SET_YANDEX_API_KEY; + else if (translatore == Helper.TRANS_DEEPL) + store = Helper.SET_DEEPL_API_KEY; + else if (translatore == Helper.TRANS_SYSTRAN) + store = Helper.SET_SYSTRAN_API_KEY; + if (store != null) + if (s != null && s.length() > 0) + editor.putString(store, s.toString().trim()); + else + editor.putString(store, null); + editor.apply(); + } + }); + + + boolean auto_backup = sharedpreferences.getBoolean(Helper.SET_AUTO_BACKUP_STATUSES + userId + instance, false); + final SwitchCompat set_auto_backup = rootView.findViewById(R.id.set_auto_backup); + set_auto_backup.setChecked(auto_backup); + set_auto_backup.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_AUTO_BACKUP_STATUSES + userId + instance, set_auto_backup.isChecked()); + editor.apply(); + }); + + boolean clear_cache_exit = sharedpreferences.getBoolean(Helper.SET_CLEAR_CACHE_EXIT, false); + final SwitchCompat set_clear_cache_exit = rootView.findViewById(R.id.set_clear_cache_exit); + set_clear_cache_exit.setChecked(clear_cache_exit); + set_clear_cache_exit.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_CLEAR_CACHE_EXIT, set_clear_cache_exit.isChecked()); + editor.apply(); + }); + + boolean auto_backup_notifications = sharedpreferences.getBoolean(Helper.SET_AUTO_BACKUP_NOTIFICATIONS + userId + instance, false); + final SwitchCompat set_auto_backup_notifications = rootView.findViewById(R.id.set_auto_backup_notifications); + set_auto_backup_notifications.setChecked(auto_backup_notifications); + set_auto_backup_notifications.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_AUTO_BACKUP_NOTIFICATIONS + userId + instance, set_auto_backup_notifications.isChecked()); + editor.apply(); + }); + + TagsEditText set_featured_tags = rootView.findViewById(R.id.set_featured_tags); + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { + Set featuredTagsSet = sharedpreferences.getStringSet(Helper.SET_FEATURED_TAGS, null); + + + List tags = new ArrayList<>(); + if (featuredTagsSet != null) { + tags = new ArrayList<>(featuredTagsSet); + } + String[] tagsString = tags.toArray(new String[tags.size()]); + set_featured_tags.setTags(tagsString); + + set_featured_tags.setTagsListener(new TagsEditText.TagsEditListener() { + @Override + public void onTagsChanged(Collection collection) { + Set set = ImmutableSet.copyOf(collection); + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putStringSet(Helper.SET_FEATURED_TAGS, set); + editor.apply(); + } + + @Override + public void onEditingFinished() { + + } + }); + } else { + set_featured_tags.setVisibility(View.GONE); + } + + Spinner set_attachment_group = rootView.findViewById(R.id.set_attachment_group); + String[] attachment_labels = {context.getString(R.string.set_attachment_always), context.getString(R.string.set_attachment_wifi), context.getString(R.string.set_attachment_ask)}; + ArrayAdapter adapterAttachment = new ArrayAdapter<>(Objects.requireNonNull(getActivity()), + android.R.layout.simple_spinner_dropdown_item, attachment_labels); + set_attachment_group.setAdapter(adapterAttachment); + int attachmentAction = sharedpreferences.getInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ALWAYS); + switch (attachmentAction) { + case Helper.ATTACHMENT_ALWAYS: + set_attachment_group.setSelection(0, false); + break; + case Helper.ATTACHMENT_WIFI: + set_attachment_group.setSelection(1, false); + break; + case Helper.ATTACHMENT_ASK: + set_attachment_group.setSelection(2, false); + break; + } + + set_attachment_group.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + SharedPreferences.Editor editor = sharedpreferences.edit(); + switch (position) { + case 0: + editor.putInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ALWAYS); + editor.apply(); + break; + case 1: + editor.putInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_WIFI); + editor.apply(); + break; + case 2: + editor.putInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ASK); + editor.apply(); + break; + } + } + + @Override + public void onNothingSelected(AdapterView parent) { + + } + }); + + int videoMode = sharedpreferences.getInt(Helper.SET_VIDEO_MODE, Helper.VIDEO_MODE_DIRECT); + //Video mode + final Spinner video_mode_spinner = rootView.findViewById(R.id.set_video_mode); + ArrayAdapter video_mode_spinnerAdapter = ArrayAdapter.createFromResource(Objects.requireNonNull(getActivity()), + R.array.settings_video_mode, android.R.layout.simple_spinner_dropdown_item); + video_mode_spinner.setAdapter(video_mode_spinnerAdapter); + if (videoMode == Helper.VIDEO_MODE_TORRENT) + videoMode = Helper.VIDEO_MODE_DIRECT; + int positionVideoMode = 0; + if (videoMode == Helper.VIDEO_MODE_DIRECT) + positionVideoMode = 1; + videoSpinnerCount = 0; + video_mode_spinner.setSelection(positionVideoMode); + video_mode_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + if (videoSpinnerCount > 0) { + SharedPreferences.Editor editor = sharedpreferences.edit(); + switch (position) { + case 0: + editor.putInt(Helper.SET_VIDEO_MODE, Helper.VIDEO_MODE_WEBVIEW); + editor.apply(); + break; + case 1: + editor.putInt(Helper.SET_VIDEO_MODE, Helper.VIDEO_MODE_DIRECT); + editor.apply(); + break; + } + } else { + videoSpinnerCount++; + } + } + + @Override + public void onNothingSelected(AdapterView parent) { + + } + }); + + boolean patch_provider = sharedpreferences.getBoolean(Helper.SET_SECURITY_PROVIDER, true); + final SwitchCompat set_security_provider = rootView.findViewById(R.id.set_security_provider); + set_security_provider.setChecked(patch_provider); + + set_security_provider.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_SECURITY_PROVIDER, set_security_provider.isChecked()); + editor.apply(); + }); + } else if (type == COMPOSE) { + rootView = inflater.inflate(R.layout.fragment_settings_compose, container, false); + + + //Resize + final SwitchCompat set_resize_picture = rootView.findViewById(R.id.set_resize_picture); + boolean compress = sharedpreferences.getBoolean(Helper.SET_PICTURE_COMPRESSED, true); + set_resize_picture.setChecked(compress); + set_resize_picture.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_PICTURE_COMPRESSED, set_resize_picture.isChecked()); + editor.apply(); + }); + + + //Resize + final SwitchCompat set_resize_video = rootView.findViewById(R.id.set_resize_video); + boolean compressVideo = sharedpreferences.getBoolean(Helper.SET_VIDEO_COMPRESSED, true); + set_resize_video.setChecked(compressVideo); + set_resize_video.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_VIDEO_COMPRESSED, set_resize_video.isChecked()); + editor.apply(); + }); + + + int split_size_val = sharedpreferences.getInt(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS_SIZE + userId + instance, Helper.SPLIT_TOOT_SIZE); + + LinearLayout set_split_container = rootView.findViewById(R.id.set_split_container); + //split size + SeekBar split_size = rootView.findViewById(R.id.set_split_size); + final TextView split_text = rootView.findViewById(R.id.set_split_text); + + split_size.setProgress(0); + split_text.setText(String.valueOf(split_size_val)); + split_size.setMax(5); + split_size.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { + @Override + public void onStopTrackingTouch(SeekBar seekBar) { + } + + @Override + public void onStartTrackingTouch(SeekBar seekBar) { + } + + @Override + public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { + int newProgress = (progress + 1) * Helper.SPLIT_TOOT_SIZE; + split_text.setText(String.valueOf(newProgress)); + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putInt(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS_SIZE + userId + instance, newProgress); + editor.apply(); + } + }); + + boolean split_toot = sharedpreferences.getBoolean(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS + userId + instance, false); + if (!split_toot) { + set_split_container.setVisibility(View.GONE); + } + final SwitchCompat set_split_toot = rootView.findViewById(R.id.set_automatically_split_toot); + set_split_toot.setChecked(split_toot); + set_split_toot.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS + userId + instance, set_split_toot.isChecked()); + editor.apply(); + if (set_split_toot.isChecked()) { + set_split_container.setVisibility(View.VISIBLE); + } else { + set_split_container.setVisibility(View.GONE); + } + }); + + + LinearLayout toot_visibility_container = rootView.findViewById(R.id.toot_visibility_container); + + final ImageView set_toot_visibility = rootView.findViewById(R.id.set_toot_visibility); + + //Only displayed for non locked accounts + if (account != null) { + String defaultVisibility = account.isLocked() ? "private" : "public"; + String tootVisibility = sharedpreferences.getString(Helper.SET_TOOT_VISIBILITY + "@" + account.getAcct() + "@" + account.getInstance(), defaultVisibility); + switch (tootVisibility) { + case "public": + set_toot_visibility.setImageResource(R.drawable.ic_public); + break; + case "unlisted": + set_toot_visibility.setImageResource(R.drawable.ic_lock_open); + break; + case "private": + set_toot_visibility.setImageResource(R.drawable.ic_lock_outline); + break; + case "direct": + set_toot_visibility.setImageResource(R.drawable.ic_mail_outline); + break; + } + } else { + toot_visibility_container.setVisibility(View.GONE); + } + + set_toot_visibility.setOnClickListener(v -> { + final SharedPreferences sharedpreferences12 = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + + AlertDialog.Builder dialog = new AlertDialog.Builder(context, style); + dialog.setTitle(R.string.toot_visibility_tilte); + final String[] stringArray = getResources().getStringArray(R.array.toot_visibility); + final ArrayAdapter arrayAdapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, stringArray); + dialog.setNegativeButton(R.string.cancel, (dialog1, position) -> dialog1.dismiss()); + + dialog.setAdapter(arrayAdapter, (dialog12, position) -> { String visibility = "public"; switch (position) { @@ -1575,792 +1789,643 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); } - dialog.dismiss(); - } + dialog12.dismiss(); + }); + dialog.show(); }); - dialog.show(); - }); - boolean allow_live_notifications = sharedpreferences.getBoolean(Helper.SET_ALLOW_STREAM + userId + instance, true); - TextView set_allow_live_notifications_title = rootView.findViewById(R.id.set_allow_live_notifications_title); - if (account != null) { - set_allow_live_notifications_title.setText(context.getString(R.string.set_allow_live_notifications, account.getAcct() + "@" + account.getInstance())); - } - final SwitchCompat set_allow_live_notifications = rootView.findViewById(R.id.set_allow_live_notifications); - set_allow_live_notifications.setChecked(allow_live_notifications); - set_allow_live_notifications.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_ALLOW_STREAM + userId + instance, set_allow_live_notifications.isChecked()); - editor.apply(); - if (set_allow_live_notifications.isChecked()) { - LiveNotificationDelayedService.totalAccount++; - } else { - LiveNotificationDelayedService.totalAccount--; - } - if (set_allow_live_notifications.isChecked()) { - LiveNotificationDelayedService.totalAccount++; - } else { - LiveNotificationDelayedService.totalAccount--; - } - Helper.startStreaming(context); + boolean capitalize = sharedpreferences.getBoolean(Helper.SET_CAPITALIZE, true); + final SwitchCompat set_capitalize = rootView.findViewById(R.id.set_capitalize); + set_capitalize.setChecked(capitalize); - }); - - final ImageButton set_allow_live_notifications_others = rootView.findViewById(R.id.set_allow_live_notifications_others); - set_allow_live_notifications_others.setOnClickListener(view -> { - Intent intent = new Intent(context, LiveNotificationSettingsAccountsActivity.class); - startActivity(intent); - }); - - boolean trans_forced = sharedpreferences.getBoolean(Helper.SET_TRANS_FORCED, false); - final CheckBox set_trans_forced = rootView.findViewById(R.id.set_trans_forced); - set_trans_forced.setChecked(trans_forced); - set_trans_forced.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_TRANS_FORCED, set_trans_forced.isChecked()); - editor.apply(); - }); - - int split_size_val = sharedpreferences.getInt(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS_SIZE + userId + instance, Helper.SPLIT_TOOT_SIZE); - - LinearLayout set_split_container = rootView.findViewById(R.id.set_split_container); - //split size - SeekBar split_size = rootView.findViewById(R.id.set_split_size); - final TextView split_text = rootView.findViewById(R.id.set_split_text); - - split_size.setProgress(0); - split_text.setText(String.valueOf(split_size_val)); - split_size.setMax(5); - split_size.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - } - - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - int newProgress = (progress + 1) * Helper.SPLIT_TOOT_SIZE; - split_text.setText(String.valueOf(newProgress)); + set_capitalize.setOnClickListener(v -> { SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putInt(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS_SIZE + userId + instance, newProgress); + editor.putBoolean(Helper.SET_CAPITALIZE, set_capitalize.isChecked()); editor.apply(); - } - }); - - boolean split_toot = sharedpreferences.getBoolean(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS + userId + instance, false); - if (!split_toot) { - set_split_container.setVisibility(View.GONE); - } - final SwitchCompat set_split_toot = rootView.findViewById(R.id.set_automatically_split_toot); - set_split_toot.setChecked(split_toot); - set_split_toot.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS + userId + instance, set_split_toot.isChecked()); - editor.apply(); - if (set_split_toot.isChecked()) { - set_split_container.setVisibility(View.VISIBLE); - } else { - set_split_container.setVisibility(View.GONE); - } - }); - - //Translators - final Spinner translation_layout_spinner = rootView.findViewById(R.id.translation_layout_spinner); + }); - List translatorsList = Arrays.asList(getResources().getStringArray(R.array.settings_translation)); - ArrayList trans = new ArrayList<>(translatorsList); - trans.add(getString(R.string.no)); - - ArrayAdapter adapterTrans = new ArrayAdapter<>(getActivity(), - android.R.layout.simple_spinner_dropdown_item, trans); - translation_layout_spinner.setAdapter(adapterTrans); - int positionSpinnerTrans; - switch (sharedpreferences.getInt(Helper.SET_TRANSLATOR, Helper.TRANS_YANDEX)) { - case Helper.TRANS_YANDEX: - positionSpinnerTrans = 0; - your_api_key.setVisibility(View.VISIBLE); - your_api_key.setText(sharedpreferences.getString(Helper.SET_YANDEX_API_KEY, "")); - break; - case Helper.TRANS_DEEPL: - positionSpinnerTrans = 1; - your_api_key.setVisibility(View.VISIBLE); - your_api_key.setText(sharedpreferences.getString(Helper.SET_DEEPL_API_KEY, "")); - break; - case Helper.TRANS_SYSTRAN: - positionSpinnerTrans = 2; - your_api_key.setVisibility(View.VISIBLE); - your_api_key.setText(sharedpreferences.getString(Helper.SET_SYSTRAN_API_KEY, "")); - break; - case Helper.TRANS_NONE: - positionSpinnerTrans = 3; - your_api_key.setVisibility(View.GONE); - break; - default: - your_api_key.setVisibility(View.VISIBLE); - positionSpinnerTrans = 0; - } - translation_layout_spinner.setSelection(positionSpinnerTrans); - countTrans = 0; - translation_layout_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - if (countTrans > 0) { - SharedPreferences.Editor editor = sharedpreferences.edit(); - switch (position) { - case 0: - your_api_key.setVisibility(View.VISIBLE); - editor.putInt(Helper.SET_TRANSLATOR, Helper.TRANS_YANDEX); - editor.commit(); - your_api_key.setText(sharedpreferences.getString(Helper.SET_YANDEX_API_KEY, "")); - - break; - case 1: - your_api_key.setVisibility(View.VISIBLE); - editor.putInt(Helper.SET_TRANSLATOR, Helper.TRANS_DEEPL); - editor.commit(); - your_api_key.setText(sharedpreferences.getString(Helper.SET_DEEPL_API_KEY, "")); - break; - case 2: - your_api_key.setVisibility(View.VISIBLE); - editor.putInt(Helper.SET_TRANSLATOR, Helper.TRANS_SYSTRAN); - editor.commit(); - your_api_key.setText(sharedpreferences.getString(Helper.SET_SYSTRAN_API_KEY, "")); - break; - case 3: - your_api_key.setVisibility(View.GONE); - set_trans_forced.isChecked(); - editor.putBoolean(Helper.SET_TRANS_FORCED, false); - editor.putInt(Helper.SET_TRANSLATOR, Helper.TRANS_NONE); - editor.commit(); - break; - } - } else { - countTrans++; - } + if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { + LinearLayout set_wysiwyg_container = rootView.findViewById(R.id.set_wysiwyg_container); + set_wysiwyg_container.setVisibility(View.VISIBLE); } - @Override - public void onNothingSelected(AdapterView parent) { + boolean wysiwyg = sharedpreferences.getBoolean(Helper.SET_WYSIWYG, false); + final SwitchCompat set_wysiwyg = rootView.findViewById(R.id.set_wysiwyg); + set_wysiwyg.setChecked(wysiwyg); - } - - }); - - //Resize - final SwitchCompat set_resize_picture = rootView.findViewById(R.id.set_resize_picture); - boolean compress = sharedpreferences.getBoolean(Helper.SET_PICTURE_COMPRESSED, true); - set_resize_picture.setChecked(compress); - set_resize_picture.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_PICTURE_COMPRESSED, set_resize_picture.isChecked()); - editor.apply(); - }); - - - //Resize - final SwitchCompat set_resize_video = rootView.findViewById(R.id.set_resize_video); - boolean compressVideo = sharedpreferences.getBoolean(Helper.SET_VIDEO_COMPRESSED, true); - set_resize_video.setChecked(compressVideo); - set_resize_video.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_VIDEO_COMPRESSED, set_resize_video.isChecked()); - editor.apply(); - }); - - - boolean notif_follow = sharedpreferences.getBoolean(Helper.SET_NOTIF_FOLLOW, true); - boolean notif_add = sharedpreferences.getBoolean(Helper.SET_NOTIF_ADD, true); - boolean notif_mention = sharedpreferences.getBoolean(Helper.SET_NOTIF_MENTION, true); - boolean notif_share = sharedpreferences.getBoolean(Helper.SET_NOTIF_SHARE, true); - boolean notif_poll = sharedpreferences.getBoolean(Helper.SET_NOTIF_POLL, true); - - boolean notif_wifi = sharedpreferences.getBoolean(Helper.SET_WIFI_ONLY, false); - boolean notif_silent = sharedpreferences.getBoolean(Helper.SET_NOTIF_SILENT, false); - - - final String time_from = sharedpreferences.getString(Helper.SET_TIME_FROM, "07:00"); - final String time_to = sharedpreferences.getString(Helper.SET_TIME_TO, "22:00"); - - - final SwitchCompat set_notif_follow = rootView.findViewById(R.id.set_notif_follow); - final SwitchCompat set_notif_follow_add = rootView.findViewById(R.id.set_notif_follow_add); - final SwitchCompat set_notif_follow_mention = rootView.findViewById(R.id.set_notif_follow_mention); - final SwitchCompat set_notif_follow_share = rootView.findViewById(R.id.set_notif_follow_share); - final SwitchCompat set_notif_follow_poll = rootView.findViewById(R.id.set_notif_follow_poll); - - - final SwitchCompat switchCompatWIFI = rootView.findViewById(R.id.set_wifi_only); - final SwitchCompat switchCompatSilent = rootView.findViewById(R.id.set_silence); - - final Button settings_time_from = rootView.findViewById(R.id.settings_time_from); - final Button settings_time_to = rootView.findViewById(R.id.settings_time_to); - - final LinearLayout channels_container = rootView.findViewById(R.id.channels_container); - final Button sound_boost = rootView.findViewById(R.id.sound_boost); - final Button sound_fav = rootView.findViewById(R.id.sound_fav); - final Button sound_follow = rootView.findViewById(R.id.sound_follow); - final Button sound_mention = rootView.findViewById(R.id.sound_mention); - final Button sound_poll = rootView.findViewById(R.id.sound_poll); - final Button sound_backup = rootView.findViewById(R.id.sound_backup); - final Button sound_media = rootView.findViewById(R.id.sound_media); - final ImageButton set_hide_status_bar = rootView.findViewById(R.id.set_hide_status_bar); - - Button set_notif_sound = rootView.findViewById(R.id.set_notif_sound); - settings_time_from.setText(time_from); - settings_time_to.setText(time_to); - final LinearLayout set_hide_status_bar_container = rootView.findViewById(R.id.set_hide_status_bar_container); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - set_notif_sound.setVisibility(View.GONE); - channels_container.setVisibility(View.VISIBLE); - set_hide_status_bar_container.setVisibility(View.VISIBLE); - set_hide_status_bar.setOnClickListener(v -> { - Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS); - intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName()); - intent.putExtra(Settings.EXTRA_CHANNEL_ID, LiveNotificationDelayedService.CHANNEL_ID); - startActivity(intent); - }); - - - sound_boost.setOnClickListener(v -> { - Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS); - intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName()); - intent.putExtra(Settings.EXTRA_CHANNEL_ID, "channel_boost"); - startActivity(intent); - }); - - sound_fav.setOnClickListener(v -> { - Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS); - intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName()); - intent.putExtra(Settings.EXTRA_CHANNEL_ID, "channel_fav"); - startActivity(intent); - }); - - sound_follow.setOnClickListener(v -> { - Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS); - intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName()); - intent.putExtra(Settings.EXTRA_CHANNEL_ID, "channel_follow"); - startActivity(intent); - }); - - sound_mention.setOnClickListener(v -> { - Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS); - intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName()); - intent.putExtra(Settings.EXTRA_CHANNEL_ID, "channel_mention"); - startActivity(intent); - }); - - sound_poll.setOnClickListener(v -> { - Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS); - intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName()); - intent.putExtra(Settings.EXTRA_CHANNEL_ID, "channel_poll"); - startActivity(intent); - }); - - sound_backup.setOnClickListener(v -> { - Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS); - intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName()); - intent.putExtra(Settings.EXTRA_CHANNEL_ID, "channel_backup"); - startActivity(intent); - }); - - sound_media.setOnClickListener(v -> { - Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS); - intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName()); - intent.putExtra(Settings.EXTRA_CHANNEL_ID, "channel_store"); - startActivity(intent); - }); - } else { - set_notif_sound.setVisibility(View.VISIBLE); - channels_container.setVisibility(View.GONE); - set_notif_sound.setOnClickListener(v -> { - Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER); - intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION); - intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, context.getString(R.string.select_sound)); - intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, (Uri) null); - startActivityForResult(intent, ACTIVITY_CHOOSE_SOUND); - }); - } - - - boolean enable_time_slot = sharedpreferences.getBoolean(Helper.SET_ENABLE_TIME_SLOT, true); - final SwitchCompat set_enable_time_slot = rootView.findViewById(R.id.set_enable_time_slot); - set_enable_time_slot.setChecked(enable_time_slot); - - set_enable_time_slot.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_ENABLE_TIME_SLOT, set_enable_time_slot.isChecked()); - editor.apply(); - }); - - - settings_time_from.setOnClickListener(v -> { - String[] datetime = time_from.split(":"); - TimePickerDialog timePickerDialog = new TimePickerDialog(getActivity(), style, (view, hourOfDay, minute) -> { + set_wysiwyg.setOnClickListener(v -> { SharedPreferences.Editor editor = sharedpreferences.edit(); - String hours = (String.valueOf(hourOfDay).length() == 1) ? "0" + hourOfDay : String.valueOf(hourOfDay); - String minutes = (String.valueOf(minute).length() == 1) ? "0" + minute : String.valueOf(minute); - String newDate = hours + ":" + minutes; - if (Helper.compareDate(context, newDate, false)) { - editor.putString(Helper.SET_TIME_FROM, newDate); - editor.apply(); - settings_time_from.setText(newDate); - } else { - String ateRef = sharedpreferences.getString(Helper.SET_TIME_TO, "22:00"); - Toasty.error(context, context.getString(R.string.settings_time_lower, ateRef), Toast.LENGTH_LONG).show(); - } - }, Integer.parseInt(datetime[0]), Integer.parseInt(datetime[1]), true); - timePickerDialog.setTitle(context.getString(R.string.settings_hour_init)); - timePickerDialog.show(); - }); + editor.putBoolean(Helper.SET_WYSIWYG, set_wysiwyg.isChecked()); + editor.apply(); + }); - settings_time_to.setOnClickListener(v -> { - String[] datetime = time_to.split(":"); - TimePickerDialog timePickerDialog = new TimePickerDialog(getActivity(), style, (view, hourOfDay, minute) -> { + + // Custom Sharing + final EditText edit_custom_sharing_url = rootView.findViewById(R.id.custom_sharing_url); + boolean custom_sharing = sharedpreferences.getBoolean(Helper.SET_CUSTOM_SHARING, false); + final SwitchCompat set_custom_sharing = rootView.findViewById(R.id.set_custom_sharing); + set_custom_sharing.setChecked(custom_sharing); + if (custom_sharing) + edit_custom_sharing_url.setVisibility(View.VISIBLE); + else + edit_custom_sharing_url.setVisibility(View.GONE); + set_custom_sharing.setOnClickListener(v -> { SharedPreferences.Editor editor = sharedpreferences.edit(); - String hours = (String.valueOf(hourOfDay).length() == 1) ? "0" + hourOfDay : String.valueOf(hourOfDay); - String minutes = (String.valueOf(minute).length() == 1) ? "0" + minute : String.valueOf(minute); - String newDate = hours + ":" + minutes; - if (Helper.compareDate(context, newDate, true)) { - editor.putString(Helper.SET_TIME_TO, newDate); - editor.apply(); - settings_time_to.setText(newDate); - } else { - String ateRef = sharedpreferences.getString(Helper.SET_TIME_FROM, "07:00"); - Toasty.error(context, context.getString(R.string.settings_time_greater, ateRef), Toast.LENGTH_LONG).show(); + editor.putBoolean(Helper.SET_CUSTOM_SHARING, set_custom_sharing.isChecked()); + editor.apply(); + if (set_custom_sharing.isChecked()) + edit_custom_sharing_url.setVisibility(View.VISIBLE); + else + edit_custom_sharing_url.setVisibility(View.GONE); + }); + + // forward tags in replies + boolean forward_tags = sharedpreferences.getBoolean(Helper.SET_FORWARD_TAGS_IN_REPLY, false); + final SwitchCompat set_forward_tags = rootView.findViewById(R.id.set_forward_tags); + set_forward_tags.setChecked(forward_tags); + set_forward_tags.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_FORWARD_TAGS_IN_REPLY, set_forward_tags.isChecked()); + editor.apply(); + }); + + String custom_sharing_url = sharedpreferences.getString(Helper.SET_CUSTOM_SHARING_URL, ""); + if (custom_sharing_url.equals("")) { + custom_sharing_url = "http://cs.example.net/add?token=umVe1zurZk47ihElSOQcBG05KUSA2v-GSet4_fFnJ4M&url=${url}&title=${title}&source=${source}&id=${id}&description=${description}&keywords=${keywords}&creator=${creator}&thumbnailurl=${thumbnailurl}"; + } + edit_custom_sharing_url.setText(custom_sharing_url); + + + edit_custom_sharing_url.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } - }, Integer.parseInt(datetime[0]), Integer.parseInt(datetime[1]), true); - timePickerDialog.setTitle(context.getString(R.string.settings_hour_end)); - timePickerDialog.show(); - }); + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { - final Spinner action_notification = rootView.findViewById(R.id.action_notification); - ArrayAdapter adapterAction = ArrayAdapter.createFromResource(Objects.requireNonNull(getActivity()), - R.array.action_notification, android.R.layout.simple_spinner_dropdown_item); - action_notification.setAdapter(adapterAction); - int positionNotificationAntion; - switch (sharedpreferences.getInt(Helper.SET_NOTIFICATION_ACTION, Helper.ACTION_ACTIVE)) { - case Helper.ACTION_ACTIVE: - positionNotificationAntion = 0; - break; - case Helper.ACTION_SILENT: - positionNotificationAntion = 1; - break; - default: - positionNotificationAntion = 0; - } - notificationCount = 0; - action_notification.setSelection(positionNotificationAntion); - action_notification.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - if (notificationCount > 0) { + } + + @Override + public void afterTextChanged(Editable s) { SharedPreferences.Editor editor = sharedpreferences.edit(); - - switch (position) { - case 0: - editor.putInt(Helper.SET_NOTIFICATION_ACTION, Helper.ACTION_ACTIVE); - editor.apply(); - break; - case 1: - editor.putInt(Helper.SET_NOTIFICATION_ACTION, Helper.ACTION_SILENT); - editor.apply(); - break; - } - } else { - notificationCount++; + editor.putString(Helper.SET_CUSTOM_SHARING_URL, s.toString().trim()); + editor.apply(); } - } - - @Override - public void onNothingSelected(AdapterView parent) { - - } - }); - - set_notif_follow.setChecked(notif_follow); - set_notif_follow_add.setChecked(notif_add); - set_notif_follow_mention.setChecked(notif_mention); - set_notif_follow_share.setChecked(notif_share); - set_notif_follow_poll.setChecked(notif_poll); + }); - switchCompatWIFI.setChecked(notif_wifi); - switchCompatSilent.setChecked(notif_silent); + // retrieve metadata if URL from external apps when composing + boolean should_retrieve_metadata = sharedpreferences.getBoolean(Helper.SET_RETRIEVE_METADATA_IF_URL_FROM_EXTERAL, true); + final SwitchCompat set_retrieve_metadata = rootView.findViewById(R.id.set_retrieve_metadata_share_from_extras); + set_retrieve_metadata.setChecked(should_retrieve_metadata); + + set_retrieve_metadata.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_RETRIEVE_METADATA_IF_URL_FROM_EXTERAL, set_retrieve_metadata.isChecked()); + editor.apply(); + }); + + boolean share_details = sharedpreferences.getBoolean(Helper.SET_SHARE_DETAILS, true); + final SwitchCompat set_share_details = rootView.findViewById(R.id.set_share_details); + set_share_details.setChecked(share_details); + + set_share_details.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_SHARE_DETAILS, set_share_details.isChecked()); + editor.apply(); + }); + + int upload_img_max_retry_times = sharedpreferences.getInt(Helper.MAX_UPLOAD_IMG_RETRY_TIMES, 3); + final SeekBar max_times_bar = rootView.findViewById(R.id.max_upload_image_retry_times); + final TextView max_times_value = rootView.findViewById(R.id.max_upload_image_retry_times_value); + max_times_bar.setProgress(upload_img_max_retry_times); + max_times_value.setText(String.valueOf(upload_img_max_retry_times)); + max_times_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { + @Override + public void onStartTrackingTouch(SeekBar seekBar) { + } + + @Override + public void onStopTrackingTouch(SeekBar seekBar) { + } + + @Override + public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { + max_times_value.setText(String.valueOf(progress)); + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putInt(Helper.MAX_UPLOAD_IMG_RETRY_TIMES, progress); + editor.apply(); + } + }); + + boolean photo_editor = sharedpreferences.getBoolean(Helper.SET_PHOTO_EDITOR, true); + final SwitchCompat set_photo_editor = rootView.findViewById(R.id.set_photo_editor); + set_photo_editor.setChecked(photo_editor); + + set_photo_editor.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_PHOTO_EDITOR, set_photo_editor.isChecked()); + editor.apply(); + }); + + boolean display_emoji = sharedpreferences.getBoolean(Helper.SET_DISPLAY_EMOJI, false); + final SwitchCompat set_display_emoji = rootView.findViewById(R.id.set_display_emoji); + set_display_emoji.setChecked(display_emoji); + + set_display_emoji.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_DISPLAY_EMOJI, set_display_emoji.isChecked()); + editor.apply(); + }); - set_notif_follow.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_NOTIF_FOLLOW, set_notif_follow.isChecked()); - editor.apply(); - }); - set_notif_follow_add.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_NOTIF_ADD, set_notif_follow_add.isChecked()); - editor.apply(); - }); - set_notif_follow_mention.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_NOTIF_MENTION, set_notif_follow_mention.isChecked()); - editor.apply(); - }); - set_notif_follow_share.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_NOTIF_SHARE, set_notif_follow_share.isChecked()); - editor.apply(); - }); - set_notif_follow_poll.setOnClickListener(v -> { - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_NOTIF_POLL, set_notif_follow_poll.isChecked()); - editor.apply(); - }); + boolean auto_store = sharedpreferences.getBoolean(Helper.SET_AUTO_STORE, true); + + final SwitchCompat set_auto_store = rootView.findViewById(R.id.set_auto_store); + set_auto_store.setChecked(auto_store); + set_auto_store.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_AUTO_STORE, set_auto_store.isChecked()); + editor.apply(); + }); + + boolean show_media_urls = sharedpreferences.getBoolean(Helper.SET_MEDIA_URLS, false); + final SwitchCompat set_auto_add_media_url = rootView.findViewById(R.id.set_auto_add_media_url); + set_auto_add_media_url.setChecked(show_media_urls); + + set_auto_add_media_url.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_MEDIA_URLS, set_auto_add_media_url.isChecked()); + editor.apply(); + }); - switchCompatWIFI.setOnCheckedChangeListener((buttonView, isChecked) -> { - // Save the state here - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_WIFI_ONLY, isChecked); - editor.apply(); + } else if (type == PRIVACY) { + rootView = inflater.inflate(R.layout.fragment_settings_privacy, container, false); - }); - final Spinner led_colour_spinner = rootView.findViewById(R.id.led_colour_spinner); - final TextView ledLabel = rootView.findViewById(R.id.set_led_colour_label); - - switchCompatSilent.setOnCheckedChangeListener((buttonView, isChecked) -> { - // Save the state here - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putBoolean(Helper.SET_NOTIF_SILENT, isChecked); - editor.apply(); - - if (isChecked) { - ledLabel.setEnabled(true); - led_colour_spinner.setEnabled(true); + final SwitchCompat set_embedded_browser = rootView.findViewById(R.id.set_embedded_browser); + final LinearLayout set_javascript_container = rootView.findViewById(R.id.set_javascript_container); + final SwitchCompat set_custom_tabs = rootView.findViewById(R.id.set_custom_tabs); + final LinearLayout custom_tabs_container = rootView.findViewById(R.id.custom_tabs_container); + final SwitchCompat set_javascript = rootView.findViewById(R.id.set_javascript); + boolean javascript = sharedpreferences.getBoolean(Helper.SET_JAVASCRIPT, true); + boolean embedded_browser = sharedpreferences.getBoolean(Helper.SET_EMBEDDED_BROWSER, true); + boolean custom_tabs = sharedpreferences.getBoolean(Helper.SET_CUSTOM_TABS, true); + if (!embedded_browser) { + set_javascript_container.setVisibility(View.GONE); + custom_tabs_container.setVisibility(View.VISIBLE); } else { - ledLabel.setEnabled(false); - for (View lol : led_colour_spinner.getTouchables()) { - lol.setEnabled(false); - } + set_javascript_container.setVisibility(View.VISIBLE); + custom_tabs_container.setVisibility(View.GONE); } - }); + set_embedded_browser.setChecked(embedded_browser); + set_embedded_browser.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_EMBEDDED_BROWSER, set_embedded_browser.isChecked()); + editor.apply(); + if (!set_embedded_browser.isChecked()) { + set_javascript_container.setVisibility(View.GONE); + custom_tabs_container.setVisibility(View.VISIBLE); + } else { + set_javascript_container.setVisibility(View.VISIBLE); + custom_tabs_container.setVisibility(View.GONE); + } + }); - if (sharedpreferences.getBoolean(Helper.SET_NOTIF_SILENT, false)) { + set_javascript.setChecked(javascript); + set_javascript.setOnCheckedChangeListener((buttonView, isChecked) -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_JAVASCRIPT, isChecked); + editor.apply(); + }); - ledLabel.setEnabled(true); - led_colour_spinner.setEnabled(true); + set_custom_tabs.setChecked(custom_tabs); + set_custom_tabs.setOnCheckedChangeListener((buttonView, isChecked) -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_CUSTOM_TABS, isChecked); + editor.apply(); + }); - ArrayAdapter adapterLEDColour = ArrayAdapter.createFromResource(Objects.requireNonNull(getActivity()), R.array.led_colours, android.R.layout.simple_spinner_dropdown_item); - led_colour_spinner.setAdapter(adapterLEDColour); - int positionSpinnerLEDColour = (sharedpreferences.getInt(Helper.SET_LED_COLOUR, Helper.LED_COLOUR)); - led_colour_spinner.setSelection(positionSpinnerLEDColour); + final LinearLayout set_cookies_container = rootView.findViewById(R.id.set_cookies_container); + final SwitchCompat set_cookies = rootView.findViewById(R.id.set_cookies); + boolean cookies = sharedpreferences.getBoolean(Helper.SET_COOKIES, false); - ledCount = 0; - led_colour_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + set_cookies.setChecked(cookies); + set_cookies.setOnCheckedChangeListener((buttonView, isChecked) -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_COOKIES, isChecked); + editor.apply(); + }); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + set_cookies_container.setVisibility(View.VISIBLE); + } else { + set_cookies_container.setVisibility(View.GONE); + } + + Button update_tracking_domains = rootView.findViewById(R.id.update_tracking_domains); + update_tracking_domains.setOnClickListener(v -> + new DownloadTrackingDomainsAsyncTask(Objects.requireNonNull(getActivity()), update_tracking_domains).execute() + ); + + TextView set_invidious_host = rootView.findViewById(R.id.set_invidious_host); + + + boolean invidious = sharedpreferences.getBoolean(Helper.SET_INVIDIOUS, false); + final SwitchCompat set_invidious = rootView.findViewById(R.id.set_invidious); + set_invidious.setChecked(invidious); + + set_invidious.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_INVIDIOUS, set_invidious.isChecked()); + editor.apply(); + if (set_invidious.isChecked()) { + set_invidious_host.setVisibility(View.VISIBLE); + } else { + set_invidious_host.setVisibility(View.GONE); + } + }); + if (invidious) { + set_invidious_host.setVisibility(View.VISIBLE); + } else { + set_invidious_host.setVisibility(View.GONE); + } + + String invidiousHost = sharedpreferences.getString(Helper.SET_INVIDIOUS_HOST, null); + if (invidiousHost != null) { + set_invidious_host.setText(invidiousHost); + } + set_invidious_host.addTextChangedListener(new TextWatcher() { + @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(); + if (s.toString().trim().length() > 0) { + editor.putString(Helper.SET_INVIDIOUS_HOST, s.toString().toLowerCase().trim()); + } else { + editor.putString(Helper.SET_INVIDIOUS_HOST, null); + } + editor.apply(); + } + }); + + + TextView set_user_agent = rootView.findViewById(R.id.set_user_agent); + String user_agent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, Helper.USER_AGENT); + + set_user_agent.setText(user_agent); + set_user_agent.addTextChangedListener(new TextWatcher() { + @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(); + if (s.toString().trim().length() > 0) { + editor.putString(Helper.SET_CUSTOM_USER_AGENT, s.toString().toLowerCase().trim()); + } else { + editor.putString(Helper.SET_CUSTOM_USER_AGENT, null); + } + editor.apply(); + } + }); + + + final SwitchCompat set_utm_parameters = rootView.findViewById(R.id.set_utm_parameters); + boolean utm_parameters = sharedpreferences.getBoolean(Helper.SET_FILTER_UTM, true); + set_utm_parameters.setChecked(utm_parameters); + + set_utm_parameters.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_FILTER_UTM, set_utm_parameters.isChecked()); + editor.apply(); + }); + + TextView set_nitter_host = rootView.findViewById(R.id.set_nitter_host); + boolean nitter = sharedpreferences.getBoolean(Helper.SET_NITTER, false); + final SwitchCompat set_nitter = rootView.findViewById(R.id.set_nitter); + set_nitter.setChecked(nitter); + + set_nitter.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_NITTER, set_nitter.isChecked()); + editor.apply(); + if (set_nitter.isChecked()) { + set_nitter_host.setVisibility(View.VISIBLE); + } else { + set_nitter_host.setVisibility(View.GONE); + } + }); + if (nitter) { + set_nitter_host.setVisibility(View.VISIBLE); + } else { + set_nitter_host.setVisibility(View.GONE); + } + + String nitterHost = sharedpreferences.getString(Helper.SET_NITTER_HOST, null); + if (nitterHost != null) { + set_nitter_host.setText(nitterHost); + } + set_nitter_host.addTextChangedListener(new TextWatcher() { + @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(); + if (s.toString().trim().length() > 0) { + editor.putString(Helper.SET_NITTER_HOST, s.toString().toLowerCase().trim()); + } else { + editor.putString(Helper.SET_NITTER_HOST, null); + } + editor.apply(); + } + }); + + + TextView set_bibliogram_host = rootView.findViewById(R.id.set_bibliogram_host); + boolean bibliogram = sharedpreferences.getBoolean(Helper.SET_BIBLIOGRAM, false); + final SwitchCompat set_bibliogram = rootView.findViewById(R.id.set_bibliogram); + set_bibliogram.setChecked(bibliogram); + + set_bibliogram.setOnClickListener(v -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(Helper.SET_BIBLIOGRAM, set_bibliogram.isChecked()); + editor.apply(); + if (set_bibliogram.isChecked()) { + set_bibliogram_host.setVisibility(View.VISIBLE); + } else { + set_bibliogram_host.setVisibility(View.GONE); + } + }); + if (bibliogram) { + set_bibliogram_host.setVisibility(View.VISIBLE); + } else { + set_bibliogram_host.setVisibility(View.GONE); + } + + String bibliogramHost = sharedpreferences.getString(Helper.SET_BIBLIOGRAM_HOST, null); + if (bibliogramHost != null) { + set_bibliogram_host.setText(bibliogramHost); + } + set_bibliogram_host.addTextChangedListener(new TextWatcher() { + @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(); + if (s.toString().trim().length() > 0) { + editor.putString(Helper.SET_BIBLIOGRAM_HOST, s.toString().toLowerCase().trim()); + } else { + editor.putString(Helper.SET_BIBLIOGRAM_HOST, null); + } + editor.apply(); + } + }); + + } else if (type == MENU) { + rootView = inflater.inflate(R.layout.fragment_settings_menu, container, false); + + SwitchCompat nav_news = rootView.findViewById(R.id.nav_news); + SwitchCompat nav_trends = rootView.findViewById(R.id.nav_trends); + SwitchCompat nav_list = rootView.findViewById(R.id.nav_list); + SwitchCompat nav_scheduled = rootView.findViewById(R.id.nav_scheduled); + SwitchCompat nav_archive = rootView.findViewById(R.id.nav_archive); + SwitchCompat nav_archive_notifications = rootView.findViewById(R.id.nav_archive_notifications); + SwitchCompat nav_peertube = rootView.findViewById(R.id.nav_peertube); + SwitchCompat nav_filters = rootView.findViewById(R.id.nav_filters); + SwitchCompat nav_who_to_follow = rootView.findViewById(R.id.nav_who_to_follow); + SwitchCompat nav_blocked = rootView.findViewById(R.id.nav_blocked); + SwitchCompat nav_muted = rootView.findViewById(R.id.nav_muted); + SwitchCompat nav_blocked_domains = rootView.findViewById(R.id.nav_blocked_domains); + SwitchCompat nav_how_to = rootView.findViewById(R.id.nav_how_to); + Button validate = rootView.findViewById(R.id.validate); + + MainMenuItem mainMenu = new MainMenuDAO(context, db).getMainMenu(); + if (mainMenu == null) { + mainMenu = new MainMenuItem(); + } + nav_news.setChecked(mainMenu.isNav_news()); + nav_trends.setChecked(mainMenu.isNav_trends()); + nav_list.setChecked(mainMenu.isNav_list()); + nav_scheduled.setChecked(mainMenu.isNav_scheduled()); + nav_archive.setChecked(mainMenu.isNav_archive()); + nav_archive_notifications.setChecked(mainMenu.isNav_archive_notifications()); + nav_peertube.setChecked(mainMenu.isNav_peertube()); + nav_filters.setChecked(mainMenu.isNav_filters()); + nav_who_to_follow.setChecked(mainMenu.isNav_how_to_follow()); + nav_blocked.setChecked(mainMenu.isNav_blocked()); + nav_muted.setChecked(mainMenu.isNav_muted()); + nav_blocked_domains.setChecked(mainMenu.isNav_blocked_domains()); + nav_how_to.setChecked(mainMenu.isNav_howto()); + + + validate.setOnClickListener(view -> { + MainMenuItem mainMenuItem = new MainMenuItem(); + mainMenuItem.setNav_news(nav_news.isChecked()); + mainMenuItem.setNav_trends(nav_trends.isChecked()); + mainMenuItem.setNav_list(nav_list.isChecked()); + mainMenuItem.setNav_scheduled(nav_scheduled.isChecked()); + mainMenuItem.setNav_archive(nav_archive.isChecked()); + mainMenuItem.setNav_archive_notifications(nav_archive_notifications.isChecked()); + mainMenuItem.setNav_peertube(nav_peertube.isChecked()); + mainMenuItem.setNav_filters(nav_filters.isChecked()); + mainMenuItem.setNav_how_to_follow(nav_who_to_follow.isChecked()); + mainMenuItem.setNav_blocked(nav_blocked.isChecked()); + mainMenuItem.setNav_muted(nav_muted.isChecked()); + mainMenuItem.setNav_blocked_domains(nav_blocked_domains.isChecked()); + mainMenuItem.setNav_howto(nav_how_to.isChecked()); + MainMenuItem mainMenuItem1 = new MainMenuDAO(context, db).getMainMenu(); + + if (mainMenuItem1 != null) { + new MainMenuDAO(context, db).updateMenu(mainMenuItem); + } else { + new MainMenuDAO(context, db).insertMenu(mainMenuItem); + } + Intent mainActivity = new Intent(context, MainActivity.class); + mainActivity.putExtra(Helper.INTENT_ACTION, Helper.REDRAW_MENU); + startActivity(mainActivity); + }); + + } else if (type == LANGUAGE) { + rootView = inflater.inflate(R.layout.fragment_settings_language, container, false); + + Button about_translation = rootView.findViewById(R.id.about_translation); + + + about_translation.setOnClickListener(v -> { + Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://crowdin.com/project/mastalab")); + startActivity(browserIntent); + }); + + ExpandableHeightListView lv_translator_manager = rootView.findViewById(R.id.lv_translator_manager); + + lv_translator_manager.setExpanded(true); + translatorManager = new AccountSearchDevAdapter(translators); + lv_translator_manager.setAdapter(translatorManager); + + if (type == LANGUAGE) { + asyncTask = new RetrieveRemoteDataAsyncTask(context, "ButterflyOfFire", "mstdn.fr", ContentSettingsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + } + + String currentLanguage = sharedpreferences.getString(Helper.SET_DEFAULT_LOCALE_NEW, Helper.localeToStringStorage(Locale.getDefault())); + final Spinner set_change_locale = rootView.findViewById(R.id.set_change_locale); + ArrayAdapter adapterLocale = new ArrayAdapter<>(Objects.requireNonNull(getActivity()), + android.R.layout.simple_spinner_dropdown_item, Helper.getLocales(context)); + + set_change_locale.setAdapter(adapterLocale); + + int positionSpinnerLanguage = Helper.languageSpinnerPosition(context); + set_change_locale.setSelection(positionSpinnerLanguage); + countLanguage = 0; + set_change_locale.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @SuppressLint("ApplySharedPref") @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { - if (ledCount > 0) { + if (countLanguage > 0) { SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putInt(Helper.SET_LED_COLOUR, position); - editor.apply(); - } else { - ledCount++; - } + switch (position) { + case 0: + editor.remove(Helper.SET_DEFAULT_LOCALE_NEW); + editor.commit(); + break; + case 1: + editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "en"); + editor.commit(); + break; + case 2: + editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "fr"); + editor.commit(); + break; + case 3: + editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "de"); + editor.commit(); + break; + case 4: + editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "it"); + editor.commit(); + break; + case 5: + editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "ja"); + editor.commit(); + break; + case 6: + editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "zh-TW"); + editor.commit(); + break; + case 7: + editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "zh-CN"); + editor.commit(); + break; + case 8: + editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "eu"); + editor.commit(); + break; + case 9: + editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "ar"); + editor.commit(); + break; + case 10: + editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "nl"); + editor.commit(); + break; + case 11: + editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "gl"); + editor.commit(); + break; + case 12: + editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "el"); + editor.commit(); + break; + case 13: + editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "pt"); + editor.commit(); + break; + case 14: + editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "es"); + editor.commit(); + break; + case 15: + editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "pl"); + editor.commit(); + break; + case 16: + editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "sr"); + editor.commit(); + break; + case 17: + editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "uk"); + editor.commit(); + break; + case 18: + editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "ru"); + editor.commit(); + break; + case 19: + editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "no"); + editor.commit(); + break; + case 20: + editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "kab"); + editor.commit(); + break; + case 21: + editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "ca"); + editor.commit(); + break; + } + PackageManager packageManager = context.getPackageManager(); + Intent intent = packageManager.getLaunchIntentForPackage(context.getPackageName()); + assert intent != null; + ComponentName componentName = intent.getComponent(); + Intent mainIntent = Intent.makeRestartActivityTask(componentName); + startActivity(mainIntent); + Runtime.getRuntime().exit(0); + } else { + countLanguage++; + } } @Override public void onNothingSelected(AdapterView parent) { + } }); - } else { - ledLabel.setEnabled(false); - for (View lol : led_colour_spinner.getTouchables()) { - lol.setEnabled(false); - } } - - SwitchCompat nav_news = rootView.findViewById(R.id.nav_news); - SwitchCompat nav_trends = rootView.findViewById(R.id.nav_trends); - SwitchCompat nav_list = rootView.findViewById(R.id.nav_list); - SwitchCompat nav_scheduled = rootView.findViewById(R.id.nav_scheduled); - SwitchCompat nav_archive = rootView.findViewById(R.id.nav_archive); - SwitchCompat nav_archive_notifications = rootView.findViewById(R.id.nav_archive_notifications); - SwitchCompat nav_peertube = rootView.findViewById(R.id.nav_peertube); - SwitchCompat nav_filters = rootView.findViewById(R.id.nav_filters); - SwitchCompat nav_who_to_follow = rootView.findViewById(R.id.nav_who_to_follow); - SwitchCompat nav_blocked = rootView.findViewById(R.id.nav_blocked); - SwitchCompat nav_muted = rootView.findViewById(R.id.nav_muted); - SwitchCompat nav_blocked_domains = rootView.findViewById(R.id.nav_blocked_domains); - SwitchCompat nav_how_to = rootView.findViewById(R.id.nav_how_to); - Button validate = rootView.findViewById(R.id.validate); - - MainMenuItem mainMenu = new MainMenuDAO(context, db).getMainMenu(); - if (mainMenu == null) { - mainMenu = new MainMenuItem(); - } - nav_news.setChecked(mainMenu.isNav_news()); - nav_trends.setChecked(mainMenu.isNav_trends()); - nav_list.setChecked(mainMenu.isNav_list()); - nav_scheduled.setChecked(mainMenu.isNav_scheduled()); - nav_archive.setChecked(mainMenu.isNav_archive()); - nav_archive_notifications.setChecked(mainMenu.isNav_archive_notifications()); - nav_peertube.setChecked(mainMenu.isNav_peertube()); - nav_filters.setChecked(mainMenu.isNav_filters()); - nav_who_to_follow.setChecked(mainMenu.isNav_how_to_follow()); - nav_blocked.setChecked(mainMenu.isNav_blocked()); - nav_muted.setChecked(mainMenu.isNav_muted()); - nav_blocked_domains.setChecked(mainMenu.isNav_blocked_domains()); - nav_how_to.setChecked(mainMenu.isNav_howto()); - - - validate.setOnClickListener(view -> { - MainMenuItem mainMenuItem = new MainMenuItem(); - mainMenuItem.setNav_news(nav_news.isChecked()); - mainMenuItem.setNav_trends(nav_trends.isChecked()); - mainMenuItem.setNav_list(nav_list.isChecked()); - mainMenuItem.setNav_scheduled(nav_scheduled.isChecked()); - mainMenuItem.setNav_archive(nav_archive.isChecked()); - mainMenuItem.setNav_archive_notifications(nav_archive_notifications.isChecked()); - mainMenuItem.setNav_peertube(nav_peertube.isChecked()); - mainMenuItem.setNav_filters(nav_filters.isChecked()); - mainMenuItem.setNav_how_to_follow(nav_who_to_follow.isChecked()); - mainMenuItem.setNav_blocked(nav_blocked.isChecked()); - mainMenuItem.setNav_muted(nav_muted.isChecked()); - mainMenuItem.setNav_blocked_domains(nav_blocked_domains.isChecked()); - mainMenuItem.setNav_howto(nav_how_to.isChecked()); - MainMenuItem mainMenuItem1 = new MainMenuDAO(context, db).getMainMenu(); - - if (mainMenuItem1 != null) { - new MainMenuDAO(context, db).updateMenu(mainMenuItem); - } else { - new MainMenuDAO(context, db).insertMenu(mainMenuItem); - } - Intent mainActivity = new Intent(context, MainActivity.class); - mainActivity.putExtra(Helper.INTENT_ACTION, Helper.REDRAW_MENU); - startActivity(mainActivity); - }); - - - Button about_translation = rootView.findViewById(R.id.about_translation); - - - about_translation.setOnClickListener(v -> { - Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://crowdin.com/project/mastalab")); - startActivity(browserIntent); - }); - - ExpandableHeightListView lv_translator_manager = rootView.findViewById(R.id.lv_translator_manager); - - lv_translator_manager.setExpanded(true); - translatorManager = new AccountSearchDevAdapter(translators); - lv_translator_manager.setAdapter(translatorManager); - - if (type == LANGUAGE) { - asyncTask = new RetrieveRemoteDataAsyncTask(context, "ButterflyOfFire", "mstdn.fr", ContentSettingsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } - - String currentLanguage = sharedpreferences.getString(Helper.SET_DEFAULT_LOCALE_NEW, Helper.localeToStringStorage(Locale.getDefault())); - final Spinner set_change_locale = rootView.findViewById(R.id.set_change_locale); - ArrayAdapter adapterLocale = new ArrayAdapter<>(Objects.requireNonNull(getActivity()), - android.R.layout.simple_spinner_dropdown_item, Helper.getLocales(context)); - - set_change_locale.setAdapter(adapterLocale); - - int positionSpinnerLanguage = Helper.languageSpinnerPosition(context); - set_change_locale.setSelection(positionSpinnerLanguage); - countLanguage = 0; - set_change_locale.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - if (countLanguage > 0) { - SharedPreferences.Editor editor = sharedpreferences.edit(); - switch (position) { - case 0: - editor.remove(Helper.SET_DEFAULT_LOCALE_NEW); - editor.commit(); - break; - case 1: - editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "en"); - editor.commit(); - break; - case 2: - editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "fr"); - editor.commit(); - break; - case 3: - editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "de"); - editor.commit(); - break; - case 4: - editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "it"); - editor.commit(); - break; - case 5: - editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "ja"); - editor.commit(); - break; - case 6: - editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "zh-TW"); - editor.commit(); - break; - case 7: - editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "zh-CN"); - editor.commit(); - break; - case 8: - editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "eu"); - editor.commit(); - break; - case 9: - editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "ar"); - editor.commit(); - break; - case 10: - editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "nl"); - editor.commit(); - break; - case 11: - editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "gl"); - editor.commit(); - break; - case 12: - editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "el"); - editor.commit(); - break; - case 13: - editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "pt"); - editor.commit(); - break; - case 14: - editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "es"); - editor.commit(); - break; - case 15: - editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "pl"); - editor.commit(); - break; - case 16: - editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "sr"); - editor.commit(); - break; - case 17: - editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "uk"); - editor.commit(); - break; - case 18: - editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "ru"); - editor.commit(); - break; - case 19: - editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "no"); - editor.commit(); - break; - case 20: - editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "kab"); - editor.commit(); - break; - case 21: - editor.putString(Helper.SET_DEFAULT_LOCALE_NEW, "ca"); - editor.commit(); - break; - } - - PackageManager packageManager = context.getPackageManager(); - Intent intent = packageManager.getLaunchIntentForPackage(context.getPackageName()); - assert intent != null; - ComponentName componentName = intent.getComponent(); - Intent mainIntent = Intent.makeRestartActivityTask(componentName); - startActivity(mainIntent); - Runtime.getRuntime().exit(0); - } else { - countLanguage++; - } - } - - @Override - public void onNothingSelected(AdapterView parent) { - - } - }); - - ImageButton btn_select_icon = rootView.findViewById(R.id.btn_select_icon); - btn_select_icon.setOnClickListener(v -> { - - AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, style); - View icon_selector = inflater.inflate(R.layout.dialog_icon_selector, new LinearLayout(context), false); - dialogBuilder.setView(icon_selector); - dialogBuilder.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()); - dialogBuilder.setCancelable(true); - AlertDialog icon_selector_dialog = dialogBuilder.create(); - icon_selector_dialog.show(); - - icon_selector.findViewById(R.id.icon_bubbles).setOnClickListener(v1 -> { - hideAllIcons(context); - setIcon(context, "Bubbles"); - SharedPreferences.Editor editor2 = sharedpreferences.edit(); - editor2.putString(Helper.LOGO_LAUNCHER, "bubbles"); - editor2.apply(); - BaseMainActivity.mLauncher = BUBBLES; - icon_selector_dialog.dismiss(); - }); - - icon_selector.findViewById(R.id.icon_fediverse).setOnClickListener(v1 -> { - hideAllIcons(context); - setIcon(context, "Fediverse"); - SharedPreferences.Editor editor2 = sharedpreferences.edit(); - editor2.putString(Helper.LOGO_LAUNCHER, "fediverse"); - editor2.apply(); - BaseMainActivity.mLauncher = FEDIVERSE; - icon_selector_dialog.dismiss(); - }); - - icon_selector.findViewById(R.id.icon_hero).setOnClickListener(v1 -> { - hideAllIcons(context); - setIcon(context, "Hero"); - SharedPreferences.Editor editor2 = sharedpreferences.edit(); - editor2.putString(Helper.LOGO_LAUNCHER, "hero"); - editor2.apply(); - BaseMainActivity.mLauncher = HERO; - icon_selector_dialog.dismiss(); - }); - - icon_selector.findViewById(R.id.icon_atom).setOnClickListener(v1 -> { - hideAllIcons(context); - setIcon(context, "Atom"); - SharedPreferences.Editor editor2 = sharedpreferences.edit(); - editor2.putString(Helper.LOGO_LAUNCHER, "atom"); - editor2.apply(); - BaseMainActivity.mLauncher = ATOM; - icon_selector_dialog.dismiss(); - }); - - icon_selector.findViewById(R.id.icon_braincrash).setOnClickListener(v1 -> { - hideAllIcons(context); - setIcon(context, "BrainCrash"); - SharedPreferences.Editor editor2 = sharedpreferences.edit(); - editor2.putString(Helper.LOGO_LAUNCHER, "braincrash"); - editor2.apply(); - BaseMainActivity.mLauncher = BRAINCRASH; - icon_selector_dialog.dismiss(); - }); - - icon_selector.findViewById(R.id.icon_mastalab).setOnClickListener(v1 -> { - hideAllIcons(context); - setIcon(context, "Mastalab"); - SharedPreferences.Editor editor2 = sharedpreferences.edit(); - editor2.putString(Helper.LOGO_LAUNCHER, "mastalab"); - editor2.apply(); - BaseMainActivity.mLauncher = MASTALAB; - icon_selector_dialog.dismiss(); - }); - - }); - return rootView; } diff --git a/app/src/main/java/app/fedilab/android/fragments/DisplayAdminReportsFragment.java b/app/src/main/java/app/fedilab/android/fragments/DisplayAdminReportsFragment.java index c08cb9cb7..27b0878d4 100644 --- a/app/src/main/java/app/fedilab/android/fragments/DisplayAdminReportsFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/DisplayAdminReportsFragment.java @@ -14,10 +14,9 @@ package app.fedilab.android.fragments; * You should have received a copy of the GNU General Public License along with Fedilab; if not, * see . */ -import android.app.AlertDialog; import android.content.Context; -import android.content.DialogInterface; import android.content.Intent; +import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.view.LayoutInflater; @@ -27,24 +26,27 @@ import android.widget.RelativeLayout; import android.widget.Toast; import androidx.annotation.NonNull; +import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.DividerItemDecoration; 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; import app.fedilab.android.R; import app.fedilab.android.activities.LoginActivity; import app.fedilab.android.asynctasks.PostAdminActionAsyncTask; -import app.fedilab.android.asynctasks.RetrieveAccountsAsyncTask; import app.fedilab.android.client.API; import app.fedilab.android.client.APIResponse; import app.fedilab.android.client.Entities.AdminAction; import app.fedilab.android.client.Entities.Report; import app.fedilab.android.drawers.ReportsListAdapter; +import app.fedilab.android.helper.Helper; import app.fedilab.android.interfaces.OnAdminActionInterface; import es.dmoral.toasty.Toasty; @@ -59,9 +61,7 @@ public class DisplayAdminReportsFragment extends Fragment implements OnAdminActi private Context context; private AsyncTask asyncTask; private ReportsListAdapter reportsListAdapter; - private String max_id; private List reports; - private RetrieveAccountsAsyncTask.Type type; private RelativeLayout mainLoader, nextElementLoader, textviewNoAction; private boolean firstLoad; private SwipeRefreshLayout swipeRefreshLayout; @@ -82,7 +82,6 @@ public class DisplayAdminReportsFragment extends Fragment implements OnAdminActi if (bundle != null) { unresolved = bundle.getBoolean("unresolved", true); } - max_id = null; firstLoad = true; flag_loading = true; swiped = false; @@ -109,7 +108,7 @@ public class DisplayAdminReportsFragment extends Fragment implements OnAdminActi mLayoutManager = new LinearLayoutManager(context); lv_reports.setLayoutManager(mLayoutManager); lv_reports.addOnScrollListener(new RecyclerView.OnScrollListener() { - public void onScrolled(RecyclerView recyclerView, int dx, int dy) { + public void onScrolled(@NotNull RecyclerView recyclerView, int dx, int dy) { if (dy > 0) { int visibleItemCount = mLayoutManager.getChildCount(); int totalItemCount = mLayoutManager.getItemCount(); @@ -129,18 +128,14 @@ public class DisplayAdminReportsFragment extends Fragment implements OnAdminActi } }); - swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { - @Override - public void onRefresh() { - max_id = null; - reports = new ArrayList<>(); - firstLoad = true; - flag_loading = true; - swiped = true; - AdminAction adminAction = new AdminAction(); - adminAction.setUnresolved(unresolved); - asyncTask = new PostAdminActionAsyncTask(context, API.adminAction.GET_REPORTS, null, adminAction, DisplayAdminReportsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } + swipeRefreshLayout.setOnRefreshListener(() -> { + reports = new ArrayList<>(); + firstLoad = true; + flag_loading = true; + swiped = true; + AdminAction adminAction = new AdminAction(); + adminAction.setUnresolved(unresolved); + asyncTask = new PostAdminActionAsyncTask(context, API.adminAction.GET_REPORTS, null, adminAction, DisplayAdminReportsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); }); AdminAction adminAction = new AdminAction(); @@ -155,15 +150,8 @@ public class DisplayAdminReportsFragment extends Fragment implements OnAdminActi } - /** - * Refresh report in list - */ - public void refreshFilter() { - reportsListAdapter.notifyDataSetChanged(); - } - @Override - public void onAttach(Context context) { + public void onAttach(@NotNull Context context) { super.onAttach(context); this.context = context; } @@ -191,22 +179,24 @@ public class DisplayAdminReportsFragment extends Fragment implements OnAdminActi //Admin right not granted through the API? if (apiResponse.getError().getStatusCode() == 403) { AlertDialog.Builder builderInner; - builderInner = new AlertDialog.Builder(context, R.style.AppThemeDark); + SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); + int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); + int style; + if (theme == Helper.THEME_DARK) { + style = R.style.DialogDark; + } else if (theme == Helper.THEME_BLACK) { + style = R.style.DialogBlack; + } else { + style = R.style.Dialog; + } + builderInner = new AlertDialog.Builder(context, style); builderInner.setTitle(R.string.reconnect_account); builderInner.setMessage(R.string.reconnect_account_message); - builderInner.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - } - }); - builderInner.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - Intent intent = new Intent(context, LoginActivity.class); - intent.putExtra("admin", true); - context.startActivity(intent); - } + builderInner.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()); + builderInner.setPositiveButton(R.string.validate, (dialog, which) -> { + Intent intent = new Intent(context, LoginActivity.class); + intent.putExtra("admin", true); + context.startActivity(intent); }); builderInner.show(); } else { @@ -226,8 +216,6 @@ public class DisplayAdminReportsFragment extends Fragment implements OnAdminActi else textviewNoAction.setVisibility(View.GONE); - max_id = apiResponse.getMax_id(); - if (swiped) { reportsListAdapter = new ReportsListAdapter(this.reports); lv_reports.setAdapter(reportsListAdapter); 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 36e6e4313..e54d28ee8 100644 --- a/app/src/main/java/app/fedilab/android/fragments/MediaSliderFragment.java +++ b/app/src/main/java/app/fedilab/android/fragments/MediaSliderFragment.java @@ -20,6 +20,7 @@ import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.graphics.Bitmap; +import android.graphics.Color; import android.graphics.drawable.Drawable; import android.media.MediaPlayer; import android.net.Uri; @@ -51,11 +52,16 @@ import com.github.chrisbanes.photoview.PhotoView; import com.google.android.exoplayer2.ExoPlayerFactory; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.SimpleExoPlayer; -import com.google.android.exoplayer2.source.ExtractorMediaSource; -import com.google.android.exoplayer2.ui.SimpleExoPlayerView; +import com.google.android.exoplayer2.source.ProgressiveMediaSource; +import com.google.android.exoplayer2.ui.PlayerView; import com.google.android.exoplayer2.upstream.DataSource; import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory; import com.google.android.exoplayer2.util.Util; +import com.r0adkll.slidr.Slidr; +import com.r0adkll.slidr.model.SlidrConfig; +import com.r0adkll.slidr.model.SlidrInterface; +import com.r0adkll.slidr.model.SlidrListener; +import com.r0adkll.slidr.model.SlidrPosition; import org.jetbrains.annotations.NotNull; @@ -70,6 +76,7 @@ import app.fedilab.android.R; import app.fedilab.android.activities.SlideMediaActivity; import app.fedilab.android.client.Entities.Attachment; import app.fedilab.android.client.TLSSocketFactory; +import app.fedilab.android.helper.CacheDataSourceFactory; import app.fedilab.android.helper.Helper; import app.fedilab.android.webview.CustomWebview; import app.fedilab.android.webview.MastalabWebChromeClient; @@ -105,6 +112,9 @@ public class MediaSliderFragment extends Fragment implements MediaPlayer.OnCompl private ImageButton playView; private GLAudioVisualizationView visualizerView; private View rootView; + private SlidrInterface slidrInterface; + private boolean swipeEnabled; + private int bgColor; public MediaSliderFragment() { } @@ -118,8 +128,10 @@ public class MediaSliderFragment extends Fragment implements MediaPlayer.OnCompl if (bundle != null) { attachment = bundle.getParcelable("attachment"); - } + bgColor = bundle.getInt("bgcolor", R.color.black); + } + swipeEnabled = true; message_ready = rootView.findViewById(R.id.message_ready); RelativeLayout content_audio = rootView.findViewById(R.id.content_audio); @@ -132,7 +144,7 @@ public class MediaSliderFragment extends Fragment implements MediaPlayer.OnCompl ImageView next = rootView.findViewById(R.id.media_next); imageView = rootView.findViewById(R.id.media_picture); - SimpleExoPlayerView videoView = rootView.findViewById(R.id.media_video); + PlayerView videoView = rootView.findViewById(R.id.media_video); if (theme == Helper.THEME_BLACK) { changeDrawableColor(context, prev, R.color.dark_icon); changeDrawableColor(context, next, R.color.dark_icon); @@ -152,9 +164,9 @@ public class MediaSliderFragment extends Fragment implements MediaPlayer.OnCompl if (!((SlideMediaActivity) context).getFullScreen()) { ((SlideMediaActivity) context).setFullscreen(true); } - ((SlideMediaActivity) context).enableSliding(false); + enableSliding(false); } else { - ((SlideMediaActivity) context).enableSliding(true); + enableSliding(true); } }); ProgressBar pbar_inf = rootView.findViewById(R.id.pbar_inf); @@ -171,6 +183,11 @@ public class MediaSliderFragment extends Fragment implements MediaPlayer.OnCompl attachment.setType(type); } + if (bgColor != -1) { + RelativeLayout media_fragment_container = rootView.findViewById(R.id.media_fragment_container); + media_fragment_container.setBackgroundColor(bgColor); + } + switch (type.toLowerCase()) { case "image": pbar_inf.setScaleY(1f); @@ -236,10 +253,20 @@ public class MediaSliderFragment extends Fragment implements MediaPlayer.OnCompl } videoView.setVisibility(View.VISIBLE); Uri uri = Uri.parse(url); - DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(context, - Util.getUserAgent(context, "Fedilab"), null); - ExtractorMediaSource videoSource = new ExtractorMediaSource.Factory(dataSourceFactory) - .createMediaSource(uri); + + String userAgent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, Helper.USER_AGENT); + int video_cache = sharedpreferences.getInt(Helper.SET_VIDEO_CACHE, Helper.DEFAULT_VIDEO_CACHE_MB); + ProgressiveMediaSource videoSource; + if (video_cache == 0) { + DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(context, + Util.getUserAgent(context, userAgent), null); + videoSource = new ProgressiveMediaSource.Factory(dataSourceFactory) + .createMediaSource(uri); + } else { + CacheDataSourceFactory cacheDataSourceFactory = new CacheDataSourceFactory(context); + videoSource = new ProgressiveMediaSource.Factory(cacheDataSourceFactory) + .createMediaSource(uri); + } player = ExoPlayerFactory.newSimpleInstance(context); if (type.toLowerCase().equals("gifv")) player.setRepeatMode(Player.REPEAT_MODE_ONE); @@ -278,10 +305,8 @@ public class MediaSliderFragment extends Fragment implements MediaPlayer.OnCompl webview_video.setWebChromeClient(mastalabWebChromeClient); 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) { - webview_video.getSettings().setUserAgentString(user_agent); - } + String user_agent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, Helper.USER_AGENT); + webview_video.getSettings().setUserAgentString(user_agent); webview_video.getSettings().setMediaPlaybackRequiresUserGesture(false); webview_video.setWebViewClient(new MastalabWebViewClient((Activity) context)); webview_video.loadUrl(attachment.getUrl()); @@ -453,6 +478,10 @@ public class MediaSliderFragment extends Fragment implements MediaPlayer.OnCompl } } catch (Exception ignored) { } + if (timer != null) { + timer.cancel(); + timer = null; + } super.onDestroy(); } @@ -475,8 +504,49 @@ public class MediaSliderFragment extends Fragment implements MediaPlayer.OnCompl visualizerView.onResume(); } catch (Exception ignored) { } + if (slidrInterface == null && rootView != null) { + slidrInterface = Slidr.replace(rootView.findViewById(R.id.media_fragment_container), new SlidrConfig.Builder().sensitivity(1f) + .scrimColor(Color.BLACK) + .scrimStartAlpha(0.8f) + .scrimEndAlpha(0f) + .position(SlidrPosition.VERTICAL) + .velocityThreshold(2400) + .distanceThreshold(0.25f) + .edgeSize(0.18f) + .listener(new SlidrListener() { + @Override + public void onSlideStateChanged(int state) { + + } + + @Override + public void onSlideChange(float percent) { + ((SlideMediaActivity) context).setFullscreen(true); + } + + @Override + public void onSlideOpened() { + + } + + @Override + public boolean onSlideClosed() { + return false; + } + }) + .build()); + } } + private void enableSliding(boolean enable) { + if (enable && !swipeEnabled) { + slidrInterface.unlock(); + swipeEnabled = true; + } else if (!enable && swipeEnabled) { + slidrInterface.lock(); + swipeEnabled = false; + } + } @Override public void onCompletion(MediaPlayer mp) { diff --git a/app/src/main/java/app/fedilab/android/helper/CacheDataSourceFactory.java b/app/src/main/java/app/fedilab/android/helper/CacheDataSourceFactory.java new file mode 100644 index 000000000..a28cde7bc --- /dev/null +++ b/app/src/main/java/app/fedilab/android/helper/CacheDataSourceFactory.java @@ -0,0 +1,56 @@ +package app.fedilab.android.helper; + +import android.content.Context; +import android.content.SharedPreferences; + +import com.google.android.exoplayer2.database.ExoDatabaseProvider; +import com.google.android.exoplayer2.upstream.DataSource; +import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter; +import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory; +import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory; +import com.google.android.exoplayer2.upstream.FileDataSource; +import com.google.android.exoplayer2.upstream.cache.CacheDataSink; +import com.google.android.exoplayer2.upstream.cache.CacheDataSource; +import com.google.android.exoplayer2.upstream.cache.LeastRecentlyUsedCacheEvictor; +import com.google.android.exoplayer2.upstream.cache.SimpleCache; + +import java.io.File; + + +public class CacheDataSourceFactory implements DataSource.Factory { + private static SimpleCache sDownloadCache; + private final Context context; + private final DefaultDataSourceFactory defaultDatasourceFactory; + private final long maxFileSize; + + public CacheDataSourceFactory(Context context) { + super(); + this.context = context; + this.maxFileSize = 5 * 1024 * 1024; + SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + String userAgent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, Helper.USER_AGENT); + DefaultBandwidthMeter.Builder bandwidthMeterBuilder = new DefaultBandwidthMeter.Builder(context); + DefaultBandwidthMeter bandwidthMeter = bandwidthMeterBuilder.build(); + defaultDatasourceFactory = new DefaultDataSourceFactory(this.context, + bandwidthMeter, + new DefaultHttpDataSourceFactory(userAgent, bandwidthMeter)); + } + + public static SimpleCache getInstance(Context context) { + SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + int video_cache = sharedpreferences.getInt(Helper.SET_VIDEO_CACHE, Helper.DEFAULT_VIDEO_CACHE_MB); + LeastRecentlyUsedCacheEvictor evictor = new LeastRecentlyUsedCacheEvictor(video_cache * 1024 * 1024); + ExoDatabaseProvider exoDatabaseProvider = new ExoDatabaseProvider(context); + if (sDownloadCache == null) + sDownloadCache = new SimpleCache(new File(context.getCacheDir(), "media"), evictor, exoDatabaseProvider); + return sDownloadCache; + } + + @Override + public DataSource createDataSource() { + SimpleCache simpleCache = getInstance(context); + return new CacheDataSource(simpleCache, defaultDatasourceFactory.createDataSource(), + new FileDataSource(), new CacheDataSink(simpleCache, maxFileSize), + CacheDataSource.FLAG_BLOCK_ON_CACHE | CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR, null); + } +} \ No newline at end of file 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 ceeae75c7..d0ede0a82 100644 --- a/app/src/main/java/app/fedilab/android/helper/Helper.java +++ b/app/src/main/java/app/fedilab/android/helper/Helper.java @@ -320,6 +320,7 @@ public class Helper { public static final int TOOTS_PER_PAGE = 40; public static final int ACCOUNTS_PER_PAGE = 40; public static final int NOTIFICATIONS_PER_PAGE = 30; + public static final int DEFAULT_VIDEO_CACHE_MB = 100; public static final String SET_ATTACHMENT_ACTION = "set_attachment_action"; public static final String SET_TOOT_PER_PAGE = "set_toot_per_page"; public static final String SET_THEME = "set_theme"; @@ -435,6 +436,10 @@ public class Helper { public static final String SET_NITTER_HOST = "set_nitter_host"; public static final String DEFAULT_NITTER_HOST = "nitter.net"; + public static final String SET_BIBLIOGRAM = "set_bibliogram"; + public static final String SET_BIBLIOGRAM_HOST = "set_bibliogram_host"; + public static final String DEFAULT_BIBLIOGRAM_HOST = "bibliogram.art"; + public static final String SET_NOTIF_VALIDATION = "set_share_validation"; public static final String SET_NOTIF_VALIDATION_FAV = "set_share_validation_fav"; public static final String SET_WIFI_ONLY = "set_wifi_only"; @@ -462,6 +467,7 @@ public class Helper { public static final String SET_SECURITY_PROVIDER = "set_security_provider"; public static final String SET_ALLOW_STREAM = "set_allow_stream"; public static final String SET_CUSTOM_USER_AGENT = "set_custom_user_agent"; + public static final String SET_VIDEO_CACHE = "set_video_cache"; //End points public static final String EP_AUTHORIZE = "/oauth/authorize"; @@ -512,6 +518,8 @@ public class Helper { public static final Pattern twitterPattern = Pattern.compile("((@[\\w]+)@twitter\\.com)"); public static final Pattern youtubePattern = Pattern.compile("(www\\.|m\\.)?(youtube\\.com|youtu\\.be|youtube-nocookie\\.com)/(((?!([\"'<])).)*)"); public static final Pattern nitterPattern = Pattern.compile("(mobile\\.|www\\.)?twitter.com([\\w-/]+)"); + public static final Pattern bibliogramPattern = Pattern.compile("(m\\.|www\\.)?instagram.com(/p/[\\w-/]+)"); + public static final Pattern ouichesPattern = Pattern.compile("https://ouich\\.es/tag/(\\w+)"); public static final Pattern xmppPattern = Pattern.compile("xmpp:[-a-zA-Z0-9+$&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"); //Default values public final static int DEFAULT_VIDEO_WIDTH = 640; @@ -1321,9 +1329,9 @@ public class Helper { if (url.startsWith("/")) { url = "https://" + account.getInstance() + account.getAvatar(); } - if( isValidContextForGlide(activity)) { + if (isValidContextForGlide(activity)) { if (!url.equals("null")) { - if( url.contains(".gif")) { + if (url.contains(".gif")) { Glide.with(navigationView.getContext()) .asGif() .load(url) @@ -1339,7 +1347,7 @@ public class Helper { } }); - }else{ + } else { Glide.with(navigationView.getContext()) .asDrawable() .load(url) @@ -1749,14 +1757,14 @@ public class Helper { String avatarUrl = !disableGif ? accountChoice.getAvatar() : accountChoice.getAvatar_static(); - if( avatarUrl.contains(".gif")) { + if (avatarUrl.contains(".gif")) { Glide.with(finalIcon.getContext()) .asGif() .load(avatarUrl) .thumbnail(0.1f) .apply(new RequestOptions().transform(new CenterCrop(), new RoundedCorners(270))) .into(finalIcon); - }else{ + } else { Glide.with(activity) .asDrawable() .apply(new RequestOptions().transform(new CenterCrop(), new RoundedCorners(270))) @@ -1819,17 +1827,17 @@ public class Helper { if (!accountChoice.getAvatar().startsWith("http")) accountChoice.setAvatar("https://" + accountChoice.getInstance() + accountChoice.getAvatar()); ImageView itemIconAcc = new ImageView(activity); - if (isValidContextForGlide(activity) ) { + if (isValidContextForGlide(activity)) { try { String avatarUrl = !disableGif ? accountChoice.getAvatar() : accountChoice.getAvatar_static(); - if( avatarUrl.contains(".gif")) { + if (avatarUrl.contains(".gif")) { Glide.with(itemIconAcc.getContext()) .asGif() .load(avatarUrl) .thumbnail(0.1f) .apply(new RequestOptions().transform(new CenterCrop(), new RoundedCorners(270))) .into(itemIconAcc); - }else{ + } else { Glide.with(activity) .asDrawable() .apply(new RequestOptions().transform(new CenterCrop(), new RoundedCorners(270))) @@ -2262,10 +2270,8 @@ public class Helper { webView.getSettings().setLoadsImagesAutomatically(true); webView.getSettings().setSupportMultipleWindows(false); webView.getSettings().setMediaPlaybackRequiresUserGesture(true); - String user_agent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, null); - if (user_agent != null) { - webView.getSettings().setUserAgentString(user_agent); - } + String user_agent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, Helper.USER_AGENT); + webView.getSettings().setUserAgentString(user_agent); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { boolean cookies = sharedpreferences.getBoolean(Helper.SET_COOKIES, false); CookieManager cookieManager = CookieManager.getInstance(); @@ -2993,7 +2999,7 @@ public class Helper { } try { assert url != null; - if (disableGif || (!url.endsWith(".gif") && account.getAvatar_static().compareTo(account.getAvatar()) == 0)) { + if (social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE || disableGif || (!url.endsWith(".gif") && account.getAvatar_static().compareTo(account.getAvatar()) == 0)) { Glide.with(imageView.getContext()) .asDrawable() .load(url) diff --git a/app/src/main/java/app/fedilab/android/helper/ThemeHelper.java b/app/src/main/java/app/fedilab/android/helper/ThemeHelper.java index db63cad09..cd796f346 100644 --- a/app/src/main/java/app/fedilab/android/helper/ThemeHelper.java +++ b/app/src/main/java/app/fedilab/android/helper/ThemeHelper.java @@ -1,21 +1,26 @@ package app.fedilab.android.helper; - +/* Copyright 2019 Thomas Schneider + * + * This file is a part of Fedilab + * + * This program is free software; you can redistribute it and/or modify it under the terms of the + * GNU General Public License as published by the Free Software Foundation; either version 3 of the + * License, or (at your option) any later version. + * + * Fedilab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even + * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General + * Public License for more details. + * + * You should have received a copy of the GNU General Public License along with Fedilab; if not, + * see . */ import android.content.Context; -import android.content.SharedPreferences; import android.content.res.Resources; import android.util.TypedValue; -import static android.content.Context.MODE_PRIVATE; public class ThemeHelper { - - public static void changeTheme(Context context, int theme) { - final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); - - } - public static int getAttColor(Context context, int attColor) { TypedValue typedValue = new TypedValue(); Resources.Theme theme = context.getTheme(); diff --git a/app/src/main/java/app/fedilab/android/imageeditor/ColorPickerAdapter.java b/app/src/main/java/app/fedilab/android/imageeditor/ColorPickerAdapter.java index 7356faf95..36ca2c91f 100644 --- a/app/src/main/java/app/fedilab/android/imageeditor/ColorPickerAdapter.java +++ b/app/src/main/java/app/fedilab/android/imageeditor/ColorPickerAdapter.java @@ -15,6 +15,8 @@ import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.RecyclerView; +import org.jetbrains.annotations.NotNull; + import java.util.ArrayList; import java.util.List; @@ -31,7 +33,7 @@ public class ColorPickerAdapter extends RecyclerView.Adapter colorPickerColors; private OnColorPickerClickListener onColorPickerClickListener; - ColorPickerAdapter(@NonNull Context context, @NonNull List colorPickerColors) { + private ColorPickerAdapter(@NonNull Context context, @NonNull List colorPickerColors) { this.context = context; this.inflater = LayoutInflater.from(context); this.colorPickerColors = colorPickerColors; @@ -43,7 +45,7 @@ public class ColorPickerAdapter extends RecyclerView.Adapter getDefaultColors(Context context) { + private static List getDefaultColors(Context context) { ArrayList colorPickerColors = new ArrayList<>(); colorPickerColors.add(ContextCompat.getColor(context, R.color.blue_color_picker)); colorPickerColors.add(ContextCompat.getColor(context, R.color.brown_color_picker)); @@ -60,8 +62,9 @@ public class ColorPickerAdapter extends RecyclerView.Adapter { + if (onColorPickerClickListener != null) + onColorPickerClickListener.onColorPickerClickListener(colorPickerColors.get(getAdapterPosition())); }); } } diff --git a/app/src/main/java/app/fedilab/android/imageeditor/EmojiBSFragment.java b/app/src/main/java/app/fedilab/android/imageeditor/EmojiBSFragment.java index 894875914..af3f0c49d 100644 --- a/app/src/main/java/app/fedilab/android/imageeditor/EmojiBSFragment.java +++ b/app/src/main/java/app/fedilab/android/imageeditor/EmojiBSFragment.java @@ -18,6 +18,7 @@ import com.google.android.material.bottomsheet.BottomSheetDialogFragment; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; +import java.util.Objects; import app.fedilab.android.R; import ja.burhanrashid52.photoeditor.PhotoEditor; @@ -46,7 +47,7 @@ public class EmojiBSFragment extends BottomSheetDialogFragment { @SuppressLint("RestrictedApi") @Override - public void setupDialog(Dialog dialog, int style) { + public void setupDialog(@NotNull Dialog dialog, int style) { super.setupDialog(dialog, style); View contentView = View.inflate(getContext(), R.layout.fragment_bottom_sticker_emoji_dialog, null); dialog.setContentView(contentView); @@ -75,7 +76,7 @@ public class EmojiBSFragment extends BottomSheetDialogFragment { public class EmojiAdapter extends RecyclerView.Adapter { - ArrayList emojisList = PhotoEditor.getEmojis(getActivity()); + ArrayList emojisList = PhotoEditor.getEmojis(Objects.requireNonNull(getActivity())); @NotNull @Override @@ -101,14 +102,11 @@ public class EmojiBSFragment extends BottomSheetDialogFragment { super(itemView); txtEmoji = itemView.findViewById(R.id.txtEmoji); - itemView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (mEmojiListener != null) { - mEmojiListener.onEmojiClick(emojisList.get(getLayoutPosition())); - } - dismiss(); + itemView.setOnClickListener(v -> { + if (mEmojiListener != null) { + mEmojiListener.onEmojiClick(emojisList.get(getLayoutPosition())); } + dismiss(); }); } } diff --git a/app/src/main/java/app/fedilab/android/imageeditor/PropertiesBSFragment.java b/app/src/main/java/app/fedilab/android/imageeditor/PropertiesBSFragment.java index 0142c03ac..5a7d48087 100644 --- a/app/src/main/java/app/fedilab/android/imageeditor/PropertiesBSFragment.java +++ b/app/src/main/java/app/fedilab/android/imageeditor/PropertiesBSFragment.java @@ -51,13 +51,10 @@ public class PropertiesBSFragment extends BottomSheetDialogFragment implements S rvColor.setLayoutManager(layoutManager); rvColor.setHasFixedSize(true); ColorPickerAdapter colorPickerAdapter = new ColorPickerAdapter(Objects.requireNonNull(getActivity())); - colorPickerAdapter.setOnColorPickerClickListener(new ColorPickerAdapter.OnColorPickerClickListener() { - @Override - public void onColorPickerClickListener(int colorCode) { - if (mProperties != null) { - dismiss(); - mProperties.onColorChanged(colorCode); - } + colorPickerAdapter.setOnColorPickerClickListener(colorCode -> { + if (mProperties != null) { + dismiss(); + mProperties.onColorChanged(colorCode); } }); rvColor.setAdapter(colorPickerAdapter); diff --git a/app/src/main/java/app/fedilab/android/imageeditor/StickerBSFragment.java b/app/src/main/java/app/fedilab/android/imageeditor/StickerBSFragment.java index e87a1ab37..a2f71520e 100644 --- a/app/src/main/java/app/fedilab/android/imageeditor/StickerBSFragment.java +++ b/app/src/main/java/app/fedilab/android/imageeditor/StickerBSFragment.java @@ -51,7 +51,7 @@ public class StickerBSFragment extends BottomSheetDialogFragment { @SuppressLint("RestrictedApi") @Override - public void setupDialog(Dialog dialog, int style) { + public void setupDialog(@NotNull Dialog dialog, int style) { super.setupDialog(dialog, style); View contentView = View.inflate(getContext(), R.layout.fragment_bottom_sticker_emoji_dialog, null); dialog.setContentView(contentView); @@ -76,6 +76,7 @@ public class StickerBSFragment extends BottomSheetDialogFragment { } + @SuppressWarnings("unused") private String convertEmoji(String emoji) { String returnedEmoji = ""; try { @@ -137,16 +138,13 @@ public class StickerBSFragment extends BottomSheetDialogFragment { super(itemView); imgSticker = itemView.findViewById(R.id.imgSticker); - itemView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (mStickerListener != null) { - mStickerListener.onStickerClick( - BitmapFactory.decodeResource(getResources(), - stickerList[getLayoutPosition()])); - } - dismiss(); + itemView.setOnClickListener(v -> { + if (mStickerListener != null) { + mStickerListener.onStickerClick( + BitmapFactory.decodeResource(getResources(), + stickerList[getLayoutPosition()])); } + dismiss(); }); } } diff --git a/app/src/main/java/app/fedilab/android/imageeditor/TextEditorDialogFragment.java b/app/src/main/java/app/fedilab/android/imageeditor/TextEditorDialogFragment.java index e65dcd382..e366618a7 100644 --- a/app/src/main/java/app/fedilab/android/imageeditor/TextEditorDialogFragment.java +++ b/app/src/main/java/app/fedilab/android/imageeditor/TextEditorDialogFragment.java @@ -32,10 +32,9 @@ import app.fedilab.android.R; public class TextEditorDialogFragment extends DialogFragment { public static final String TAG = TextEditorDialogFragment.class.getSimpleName(); - public static final String EXTRA_INPUT_TEXT = "extra_input_text"; - public static final String EXTRA_COLOR_CODE = "extra_color_code"; + private static final String EXTRA_INPUT_TEXT = "extra_input_text"; + private static final String EXTRA_COLOR_CODE = "extra_color_code"; private EditText mAddTextEditText; - private TextView mAddTextDoneTextView; private InputMethodManager mInputMethodManager; private int mColorCode; private TextEditor mTextEditor; @@ -64,7 +63,7 @@ public class TextEditorDialogFragment extends DialogFragment { super.onStart(); Dialog dialog = getDialog(); //Make dialog full screen with transparent background - if (dialog != null) { + if (dialog != null && dialog.getWindow() != null) { int width = ViewGroup.LayoutParams.MATCH_PARENT; int height = ViewGroup.LayoutParams.MATCH_PARENT; dialog.getWindow().setLayout(width, height); @@ -82,41 +81,39 @@ public class TextEditorDialogFragment extends DialogFragment { public void onViewCreated(@NotNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mAddTextEditText = view.findViewById(R.id.add_text_edit_text); - mInputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); - mAddTextDoneTextView = view.findViewById(R.id.add_text_done_tv); + if (getActivity() != null) { + mInputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); + TextView mAddTextDoneTextView = view.findViewById(R.id.add_text_done_tv); - //Setup the color picker for text color - RecyclerView addTextColorPickerRecyclerView = view.findViewById(R.id.add_text_color_picker_recycler_view); - LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false); - addTextColorPickerRecyclerView.setLayoutManager(layoutManager); - addTextColorPickerRecyclerView.setHasFixedSize(true); - ColorPickerAdapter colorPickerAdapter = new ColorPickerAdapter(getActivity()); - //This listener will change the text color when clicked on any color from picker - colorPickerAdapter.setOnColorPickerClickListener(new ColorPickerAdapter.OnColorPickerClickListener() { - @Override - public void onColorPickerClickListener(int colorCode) { + + //Setup the color picker for text color + RecyclerView addTextColorPickerRecyclerView = view.findViewById(R.id.add_text_color_picker_recycler_view); + LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false); + addTextColorPickerRecyclerView.setLayoutManager(layoutManager); + addTextColorPickerRecyclerView.setHasFixedSize(true); + ColorPickerAdapter colorPickerAdapter = new ColorPickerAdapter(getActivity()); + //This listener will change the text color when clicked on any color from picker + colorPickerAdapter.setOnColorPickerClickListener(colorCode -> { mColorCode = colorCode; mAddTextEditText.setTextColor(colorCode); - } - }); - addTextColorPickerRecyclerView.setAdapter(colorPickerAdapter); - mAddTextEditText.setText(getArguments().getString(EXTRA_INPUT_TEXT)); - mColorCode = getArguments().getInt(EXTRA_COLOR_CODE); - mAddTextEditText.setTextColor(mColorCode); - mInputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); + }); + addTextColorPickerRecyclerView.setAdapter(colorPickerAdapter); + assert getArguments() != null; + mAddTextEditText.setText(getArguments().getString(EXTRA_INPUT_TEXT)); + mColorCode = getArguments().getInt(EXTRA_COLOR_CODE); + mAddTextEditText.setTextColor(mColorCode); + mInputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); - //Make a callback on activity when user is done with text editing - mAddTextDoneTextView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - mInputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); + //Make a callback on activity when user is done with text editing + mAddTextDoneTextView.setOnClickListener(view1 -> { + mInputMethodManager.hideSoftInputFromWindow(view1.getWindowToken(), 0); dismiss(); String inputText = mAddTextEditText.getText().toString(); if (!TextUtils.isEmpty(inputText) && mTextEditor != null) { mTextEditor.onDone(inputText, mColorCode); } - } - }); + }); + } } diff --git a/app/src/main/java/app/fedilab/android/imageeditor/tools/EditingToolsAdapter.java b/app/src/main/java/app/fedilab/android/imageeditor/tools/EditingToolsAdapter.java index 81f110251..0ee63e63a 100644 --- a/app/src/main/java/app/fedilab/android/imageeditor/tools/EditingToolsAdapter.java +++ b/app/src/main/java/app/fedilab/android/imageeditor/tools/EditingToolsAdapter.java @@ -59,7 +59,7 @@ public class EditingToolsAdapter extends RecyclerView.Adapter mOnItemSelected.onToolSelected(mToolList.get(getLayoutPosition()).mToolType)); } } } \ No newline at end of file diff --git a/app/src/main/java/app/fedilab/android/services/BackupNotificationInDataBaseService.java b/app/src/main/java/app/fedilab/android/services/BackupNotificationInDataBaseService.java index 60da93afc..16bfdb9a1 100644 --- a/app/src/main/java/app/fedilab/android/services/BackupNotificationInDataBaseService.java +++ b/app/src/main/java/app/fedilab/android/services/BackupNotificationInDataBaseService.java @@ -93,21 +93,15 @@ public class BackupNotificationInDataBaseService extends IntentService { } boolean finalToastMessage = toastMessage; if (instanceRunning == 0) { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - if (finalToastMessage) { - Toasty.info(BackupNotificationInDataBaseService.this, getString(R.string.data_export_start), Toast.LENGTH_LONG).show(); - } + new Handler(Looper.getMainLooper()).post(() -> { + if (finalToastMessage) { + Toasty.info(BackupNotificationInDataBaseService.this, getString(R.string.data_export_start), Toast.LENGTH_LONG).show(); } }); } else { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - if (finalToastMessage) { - Toasty.info(BackupNotificationInDataBaseService.this, getString(R.string.data_export_running), Toast.LENGTH_LONG).show(); - } + new Handler(Looper.getMainLooper()).post(() -> { + if (finalToastMessage) { + Toasty.info(BackupNotificationInDataBaseService.this, getString(R.string.data_export_running), Toast.LENGTH_LONG).show(); } }); return; @@ -161,12 +155,9 @@ public class BackupNotificationInDataBaseService extends IntentService { e.printStackTrace(); message = getString(R.string.data_export_error, account.getAcct()); final String finalMessage = message; - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - if (finalToastMessage) { - Toasty.error(BackupNotificationInDataBaseService.this, finalMessage, Toast.LENGTH_LONG).show(); - } + new Handler(Looper.getMainLooper()).post(() -> { + if (finalToastMessage) { + Toasty.error(BackupNotificationInDataBaseService.this, finalMessage, Toast.LENGTH_LONG).show(); } }); } diff --git a/app/src/main/java/app/fedilab/android/services/BackupStatusInDataBaseService.java b/app/src/main/java/app/fedilab/android/services/BackupStatusInDataBaseService.java index 33d57bfc7..cf8e756e7 100644 --- a/app/src/main/java/app/fedilab/android/services/BackupStatusInDataBaseService.java +++ b/app/src/main/java/app/fedilab/android/services/BackupStatusInDataBaseService.java @@ -94,21 +94,15 @@ public class BackupStatusInDataBaseService extends IntentService { } boolean finalToastMessage = toastMessage; if (instanceRunning == 0) { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - if (finalToastMessage) { - Toasty.info(BackupStatusInDataBaseService.this, getString(R.string.data_export_start), Toast.LENGTH_LONG).show(); - } + new Handler(Looper.getMainLooper()).post(() -> { + if (finalToastMessage) { + Toasty.info(BackupStatusInDataBaseService.this, getString(R.string.data_export_start), Toast.LENGTH_LONG).show(); } }); } else { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - if (finalToastMessage) { - Toasty.info(BackupStatusInDataBaseService.this, getString(R.string.data_export_running), Toast.LENGTH_LONG).show(); - } + new Handler(Looper.getMainLooper()).post(() -> { + if (finalToastMessage) { + Toasty.info(BackupStatusInDataBaseService.this, getString(R.string.data_export_running), Toast.LENGTH_LONG).show(); } }); return; @@ -159,12 +153,9 @@ public class BackupStatusInDataBaseService extends IntentService { e.printStackTrace(); message = getString(R.string.data_export_error, account.getAcct()); final String finalMessage = message; - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - if (finalToastMessage) { - Toasty.error(BackupStatusInDataBaseService.this, finalMessage, Toast.LENGTH_LONG).show(); - } + new Handler(Looper.getMainLooper()).post(() -> { + if (finalToastMessage) { + Toasty.error(BackupStatusInDataBaseService.this, finalMessage, Toast.LENGTH_LONG).show(); } }); } diff --git a/app/src/main/java/app/fedilab/android/services/BackupStatusService.java b/app/src/main/java/app/fedilab/android/services/BackupStatusService.java index 271bdf276..901b42dbd 100644 --- a/app/src/main/java/app/fedilab/android/services/BackupStatusService.java +++ b/app/src/main/java/app/fedilab/android/services/BackupStatusService.java @@ -86,19 +86,9 @@ public class BackupStatusService extends IntentService { @Override protected void onHandleIntent(@Nullable Intent intent) { if (instanceRunning == 0) { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - Toasty.info(BackupStatusService.this, getString(R.string.data_export_start), Toast.LENGTH_LONG).show(); - } - }); + new Handler(Looper.getMainLooper()).post(() -> Toasty.info(BackupStatusService.this, getString(R.string.data_export_start), Toast.LENGTH_LONG).show()); } else { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - Toasty.info(BackupStatusService.this, getString(R.string.data_export_running), Toast.LENGTH_LONG).show(); - } - }); + new Handler(Looper.getMainLooper()).post(() -> Toasty.info(BackupStatusService.this, getString(R.string.data_export_running), Toast.LENGTH_LONG).show()); return; } instanceRunning++; @@ -164,7 +154,6 @@ public class BackupStatusService extends IntentService { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) content = Html.fromHtml(status.getContent(), Html.FROM_HTML_MODE_LEGACY).toString(); else - //noinspection deprecation content = Html.fromHtml(status.getContent()).toString(); builder.append("\"").append(content.replace("\"", "'").replace("\n", " ")).append("\"").append(','); builder.append("\"").append(Helper.shortDateTime(BackupStatusService.this, status.getCreated_at())).append("\"").append(','); @@ -198,12 +187,7 @@ public class BackupStatusService extends IntentService { e.printStackTrace(); message = getString(R.string.data_export_error, account.getAcct()); final String finalMessage = message; - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - Toasty.error(BackupStatusService.this, finalMessage, Toast.LENGTH_LONG).show(); - } - }); + new Handler(Looper.getMainLooper()).post(() -> Toasty.error(BackupStatusService.this, finalMessage, Toast.LENGTH_LONG).show()); } instanceRunning--; 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 0dbdf4c72..ccb999462 100644 --- a/app/src/main/java/app/fedilab/android/services/LiveNotificationDelayedService.java +++ b/app/src/main/java/app/fedilab/android/services/LiveNotificationDelayedService.java @@ -126,7 +126,11 @@ public class LiveNotificationDelayedService extends Service { .setContentTitle(getString(R.string.top_notification)) .setSmallIcon(getNotificationIcon(LiveNotificationDelayedService.this)) .setContentText(getString(R.string.top_notification_message, String.valueOf(totalAccount), String.valueOf(eventsCount))).build(); - startForeground(1, notification); + if( notification != null) { + startForeground(1, notification); + }else{ + return; + } } @@ -210,6 +214,7 @@ public class LiveNotificationDelayedService extends Service { private void startThread(Account accountStream, String key) { Thread thread = new Thread() { + @SuppressWarnings("ConstantConditions") @Override public void run() { while (fetch) { @@ -236,6 +241,7 @@ public class LiveNotificationDelayedService extends Service { } + @SuppressWarnings("ConstantConditions") private void taks(Account account) { String key = account.getUsername() + "@" + account.getInstance(); APIResponse apiResponse; @@ -313,7 +319,11 @@ public class LiveNotificationDelayedService extends Service { .setSmallIcon(getNotificationIcon(LiveNotificationDelayedService.this)) .setContentText(getString(R.string.top_notification_message, String.valueOf(totalAccount), String.valueOf(eventsCount))).build(); - startForeground(1, notificationChannel); + if( notificationChannel != null) { + startForeground(1, notificationChannel); + }else{ + return; + } } event = Helper.EventStreaming.NOTIFICATION; @@ -433,39 +443,36 @@ public class LiveNotificationDelayedService extends Service { final String finalMessage = message; Handler mainHandler = new Handler(Looper.getMainLooper()); Helper.NotifType finalNotifType = notifType; - Runnable myRunnable = new Runnable() { - @Override - public void run() { - if (finalMessage != null) { - Glide.with(LiveNotificationDelayedService.this) - .asBitmap() - .load(notification.getAccount().getAvatar()) - .listener(new RequestListener() { - @Override - public boolean onResourceReady(Bitmap resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) { - return false; - } + Runnable myRunnable = () -> { + if (finalMessage != null) { + Glide.with(LiveNotificationDelayedService.this) + .asBitmap() + .load(notification.getAccount().getAvatar()) + .listener(new RequestListener() { + @Override + public boolean onResourceReady(Bitmap resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) { + return false; + } - @Override - public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) { - Helper.notify_user(LiveNotificationDelayedService.this, account, intent, BitmapFactory.decodeResource(getResources(), - getMainLogo(LiveNotificationDelayedService.this)), finalNotifType, "@" + notification.getAccount().getAcct(), finalMessage); - return false; - } - }) - .into(new CustomTarget() { - @Override - public void onResourceReady(@NonNull Bitmap resource, Transition transition) { + @Override + public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) { + Helper.notify_user(LiveNotificationDelayedService.this, account, intent, BitmapFactory.decodeResource(getResources(), + getMainLogo(LiveNotificationDelayedService.this)), finalNotifType, "@" + notification.getAccount().getAcct(), finalMessage); + return false; + } + }) + .into(new CustomTarget() { + @Override + public void onResourceReady(@NonNull Bitmap resource, Transition transition) { - Helper.notify_user(LiveNotificationDelayedService.this, account, intent, resource, finalNotifType, "@" + notification.getAccount().getAcct(), finalMessage); - } + Helper.notify_user(LiveNotificationDelayedService.this, account, intent, resource, finalNotifType, "@" + notification.getAccount().getAcct(), finalMessage); + } - @Override - public void onLoadCleared(@Nullable Drawable placeholder) { + @Override + public void onLoadCleared(@Nullable Drawable placeholder) { - } - }); - } + } + }); } }; mainHandler.post(myRunnable); 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 7e3c26c68..a7d1cfa65 100644 --- a/app/src/main/java/app/fedilab/android/services/LiveNotificationService.java +++ b/app/src/main/java/app/fedilab/android/services/LiveNotificationService.java @@ -140,7 +140,11 @@ public class LiveNotificationService extends Service implements NetworkStateRece .setSmallIcon(getNotificationIcon(LiveNotificationService.this)) .setContentText(getString(R.string.top_notification_message, String.valueOf(totalAccount), String.valueOf(eventsCount))).build(); - startForeground(1, notification); + if( notification != null) { + startForeground(1, notification); + }else{ + return; + } } if (!notify) { stopSelf(); @@ -172,6 +176,8 @@ public class LiveNotificationService extends Service implements NetworkStateRece public int onStartCommand(Intent intent, int flags, int startId) { final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); boolean notify = sharedpreferences.getBoolean(Helper.SET_NOTIFY, true); + + if (!notify || intent == null || intent.getBooleanExtra("stop", false)) { totalAccount = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { @@ -197,7 +203,6 @@ public class LiveNotificationService extends Service implements NetworkStateRece for (Thread t : Thread.getAllStackTraces().keySet()) { if (t.getName().startsWith("notif_live_")) { t.interrupt(); - t = null; } } Thread.currentThread().interrupt(); @@ -299,213 +304,205 @@ public class LiveNotificationService extends Service implements NetworkStateRece if (response == null) return; final Notification notification; - String dataId; Bundle b = new Bundle(); boolean canSendBroadCast = true; Helper.EventStreaming event; final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); try { - switch (response.get("event").toString()) { - case "notification": - eventsCount++; - if (Build.VERSION.SDK_INT >= 26) { - channel = new NotificationChannel(CHANNEL_ID, - "Live notifications", - NotificationManager.IMPORTANCE_DEFAULT); - ((NotificationManager) Objects.requireNonNull(getSystemService(Context.NOTIFICATION_SERVICE))).createNotificationChannel(channel); - android.app.Notification notificationChannel = new NotificationCompat.Builder(this, CHANNEL_ID) - .setContentTitle(getString(R.string.top_notification)) - .setSmallIcon(getNotificationIcon(LiveNotificationService.this)) - .setContentText(getString(R.string.top_notification_message, String.valueOf(totalAccount), String.valueOf(eventsCount))).build(); - + if ("notification".equals(response.get("event").toString())) { + eventsCount++; + if (Build.VERSION.SDK_INT >= 26) { + channel = new NotificationChannel(CHANNEL_ID, + "Live notifications", + NotificationManager.IMPORTANCE_DEFAULT); + ((NotificationManager) Objects.requireNonNull(getSystemService(Context.NOTIFICATION_SERVICE))).createNotificationChannel(channel); + android.app.Notification notificationChannel = new NotificationCompat.Builder(this, CHANNEL_ID) + .setContentTitle(getString(R.string.top_notification)) + .setSmallIcon(getNotificationIcon(LiveNotificationService.this)) + .setContentText(getString(R.string.top_notification_message, String.valueOf(totalAccount), String.valueOf(eventsCount))).build(); + if( notificationChannel != null) { startForeground(1, notificationChannel); + }else{ + return; } + } - event = Helper.EventStreaming.NOTIFICATION; - notification = API.parseNotificationResponse(LiveNotificationService.this, new JSONObject(response.get("payload").toString())); - b.putParcelable("data", notification); - boolean liveNotifications = sharedpreferences.getBoolean(Helper.SET_LIVE_NOTIFICATIONS, true); - boolean canNotify = Helper.canNotify(LiveNotificationService.this); - boolean notify = sharedpreferences.getBoolean(Helper.SET_NOTIFY, true); - String targeted_account = null; - Helper.NotifType notifType = Helper.NotifType.MENTION; - boolean activityRunning = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("isMainActivityRunning", false); - String key = account.getAcct() + "@" + account.getInstance(); - if (lastNotification.containsKey(key) && notification.getId().compareTo(Objects.requireNonNull(lastNotification.get(key))) <= 0) { - canNotify = false; - } - String lastNotif = sharedpreferences.getString(Helper.LAST_NOTIFICATION_MAX_ID + account.getId() + account.getInstance(), null); - if (notification.getId().compareTo(Objects.requireNonNull(lastNotif)) <= 0) { - canNotify = false; - } - boolean allowStream = sharedpreferences.getBoolean(Helper.SET_ALLOW_STREAM + account.getId() + account.getInstance(), true); - if (!allowStream) { - canNotify = false; - } + event = Helper.EventStreaming.NOTIFICATION; + notification = API.parseNotificationResponse(LiveNotificationService.this, new JSONObject(response.get("payload").toString())); + b.putParcelable("data", notification); + boolean liveNotifications = sharedpreferences.getBoolean(Helper.SET_LIVE_NOTIFICATIONS, true); + boolean canNotify = Helper.canNotify(LiveNotificationService.this); + boolean notify = sharedpreferences.getBoolean(Helper.SET_NOTIFY, true); + String targeted_account = null; + Helper.NotifType notifType = Helper.NotifType.MENTION; + boolean activityRunning = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("isMainActivityRunning", false); + String key = account.getAcct() + "@" + account.getInstance(); + if (lastNotification.containsKey(key) && notification.getId().compareTo(Objects.requireNonNull(lastNotification.get(key))) <= 0) { + canNotify = false; + } + String lastNotif = sharedpreferences.getString(Helper.LAST_NOTIFICATION_MAX_ID + account.getId() + account.getInstance(), null); + if (notification.getId().compareTo(Objects.requireNonNull(lastNotif)) <= 0) { + canNotify = false; + } + boolean allowStream = sharedpreferences.getBoolean(Helper.SET_ALLOW_STREAM + account.getId() + account.getInstance(), true); + if (!allowStream) { + canNotify = false; + } - if ((userId == null || !userId.equals(account.getId()) || !activityRunning) && liveNotifications && canNotify && notify) { - lastNotification.put(key, notification.getId()); - boolean notif_follow = sharedpreferences.getBoolean(Helper.SET_NOTIF_FOLLOW, true); - boolean notif_add = sharedpreferences.getBoolean(Helper.SET_NOTIF_ADD, true); - boolean notif_mention = sharedpreferences.getBoolean(Helper.SET_NOTIF_MENTION, true); - boolean notif_share = sharedpreferences.getBoolean(Helper.SET_NOTIF_SHARE, true); - boolean notif_poll = sharedpreferences.getBoolean(Helper.SET_NOTIF_POLL, true); - boolean somethingToPush = (notif_follow || notif_add || notif_mention || notif_share || notif_poll); - String message = null; - if (somethingToPush) { - switch (notification.getType()) { - case "mention": - notifType = Helper.NotifType.MENTION; - if (notif_mention) { - if (notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) - message = String.format("%s %s", notification.getAccount().getDisplay_name(), getString(R.string.notif_mention)); - else - message = String.format("@%s %s", notification.getAccount().getAcct(), getString(R.string.notif_mention)); - if (notification.getStatus() != null) { - if (notification.getStatus().getSpoiler_text() != null && notification.getStatus().getSpoiler_text().length() > 0) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) - message = "\n" + new SpannableString(Html.fromHtml(notification.getStatus().getSpoiler_text(), FROM_HTML_MODE_LEGACY)); - else - message = "\n" + new SpannableString(Html.fromHtml(notification.getStatus().getSpoiler_text())); - } else { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) - message = "\n" + new SpannableString(Html.fromHtml(notification.getStatus().getContent(), FROM_HTML_MODE_LEGACY)); - else - message = "\n" + new SpannableString(Html.fromHtml(notification.getStatus().getContent())); - } + if ((userId == null || !userId.equals(account.getId()) || !activityRunning) && liveNotifications && canNotify && notify) { + lastNotification.put(key, notification.getId()); + boolean notif_follow = sharedpreferences.getBoolean(Helper.SET_NOTIF_FOLLOW, true); + boolean notif_add = sharedpreferences.getBoolean(Helper.SET_NOTIF_ADD, true); + boolean notif_mention = sharedpreferences.getBoolean(Helper.SET_NOTIF_MENTION, true); + boolean notif_share = sharedpreferences.getBoolean(Helper.SET_NOTIF_SHARE, true); + boolean notif_poll = sharedpreferences.getBoolean(Helper.SET_NOTIF_POLL, true); + boolean somethingToPush = (notif_follow || notif_add || notif_mention || notif_share || notif_poll); + String message = null; + if (somethingToPush) { + switch (notification.getType()) { + case "mention": + notifType = Helper.NotifType.MENTION; + if (notif_mention) { + if (notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) + message = String.format("%s %s", notification.getAccount().getDisplay_name(), getString(R.string.notif_mention)); + else + message = String.format("@%s %s", notification.getAccount().getAcct(), getString(R.string.notif_mention)); + if (notification.getStatus() != null) { + if (notification.getStatus().getSpoiler_text() != null && notification.getStatus().getSpoiler_text().length() > 0) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) + message = "\n" + new SpannableString(Html.fromHtml(notification.getStatus().getSpoiler_text(), FROM_HTML_MODE_LEGACY)); + else + message = "\n" + new SpannableString(Html.fromHtml(notification.getStatus().getSpoiler_text())); + } else { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) + message = "\n" + new SpannableString(Html.fromHtml(notification.getStatus().getContent(), FROM_HTML_MODE_LEGACY)); + else + message = "\n" + new SpannableString(Html.fromHtml(notification.getStatus().getContent())); } - } else { - canSendBroadCast = false; } - break; - case "reblog": - notifType = Helper.NotifType.BOOST; - if (notif_share) { - if (notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) - message = String.format("%s %s", notification.getAccount().getDisplay_name(), getString(R.string.notif_reblog)); - else - message = String.format("@%s %s", notification.getAccount().getAcct(), getString(R.string.notif_reblog)); - } else { - canSendBroadCast = false; - } - break; - case "favourite": - notifType = Helper.NotifType.FAV; - if (notif_add) { - if (notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) - message = String.format("%s %s", notification.getAccount().getDisplay_name(), getString(R.string.notif_favourite)); - else - message = String.format("@%s %s", notification.getAccount().getAcct(), getString(R.string.notif_favourite)); - } else { - canSendBroadCast = false; - } - break; - case "follow_request": - notifType = Helper.NotifType.FOLLLOW; - if (notif_follow) { - if (notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) - message = String.format("%s %s", notification.getAccount().getDisplay_name(), getString(R.string.notif_follow_request)); - else - message = String.format("@%s %s", notification.getAccount().getAcct(), getString(R.string.notif_follow_request)); - targeted_account = notification.getAccount().getId(); - } else { - canSendBroadCast = false; - } - break; - case "follow": - notifType = Helper.NotifType.FOLLLOW; - if (notif_follow) { - if (notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) - message = String.format("%s %s", notification.getAccount().getDisplay_name(), getString(R.string.notif_follow)); - else - message = String.format("@%s %s", notification.getAccount().getAcct(), getString(R.string.notif_follow)); - targeted_account = notification.getAccount().getId(); - } else { - canSendBroadCast = false; - } - break; - case "poll": - notifType = Helper.NotifType.POLL; - if (notif_poll) { - if (notification.getAccount().getId() != null && notification.getAccount().getId().equals(userId)) - message = getString(R.string.notif_poll_self); - else - message = getString(R.string.notif_poll); - } else { - canSendBroadCast = false; - } - break; - default: - } - //Some others notification - final Intent intent = new Intent(LiveNotificationService.this, MainActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); - intent.putExtra(Helper.INTENT_ACTION, Helper.NOTIFICATION_INTENT); - intent.putExtra(Helper.PREF_KEY_ID, account.getId()); - intent.putExtra(Helper.PREF_INSTANCE, account.getInstance()); - if (targeted_account != null) { - intent.putExtra(Helper.INTENT_TARGETED_ACCOUNT, targeted_account); - } - final String finalMessage = message; - Handler mainHandler = new Handler(Looper.getMainLooper()); - Helper.NotifType finalNotifType = notifType; - Runnable myRunnable = () -> { - if (finalMessage != null) { - Glide.with(LiveNotificationService.this) - .asBitmap() - .load(notification.getAccount().getAvatar()) - .listener(new RequestListener() { - @Override - public boolean onResourceReady(Bitmap resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) { - return false; - } - - @Override - public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) { - assert e != null; - Helper.notify_user(LiveNotificationService.this, account, intent, BitmapFactory.decodeResource(getResources(), - getMainLogo(LiveNotificationService.this)), finalNotifType, "@" + notification.getAccount().getAcct(), finalMessage); - return false; - } - }) - .into(new CustomTarget() { - @Override - public void onResourceReady(@NonNull Bitmap resource, Transition transition) { - Helper.notify_user(LiveNotificationService.this, account, intent, resource, finalNotifType, "@" + notification.getAccount().getAcct(), finalMessage); - } - - @Override - public void onLoadCleared(@Nullable Drawable placeholder) { - - } - }); + } else { + canSendBroadCast = false; } - }; - mainHandler.post(myRunnable); + break; + case "reblog": + notifType = Helper.NotifType.BOOST; + if (notif_share) { + if (notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) + message = String.format("%s %s", notification.getAccount().getDisplay_name(), getString(R.string.notif_reblog)); + else + message = String.format("@%s %s", notification.getAccount().getAcct(), getString(R.string.notif_reblog)); + } else { + canSendBroadCast = false; + } + break; + case "favourite": + notifType = Helper.NotifType.FAV; + if (notif_add) { + if (notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) + message = String.format("%s %s", notification.getAccount().getDisplay_name(), getString(R.string.notif_favourite)); + else + message = String.format("@%s %s", notification.getAccount().getAcct(), getString(R.string.notif_favourite)); + } else { + canSendBroadCast = false; + } + break; + case "follow_request": + notifType = Helper.NotifType.FOLLLOW; + if (notif_follow) { + if (notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) + message = String.format("%s %s", notification.getAccount().getDisplay_name(), getString(R.string.notif_follow_request)); + else + message = String.format("@%s %s", notification.getAccount().getAcct(), getString(R.string.notif_follow_request)); + targeted_account = notification.getAccount().getId(); + } else { + canSendBroadCast = false; + } + break; + case "follow": + notifType = Helper.NotifType.FOLLLOW; + if (notif_follow) { + if (notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0) + message = String.format("%s %s", notification.getAccount().getDisplay_name(), getString(R.string.notif_follow)); + else + message = String.format("@%s %s", notification.getAccount().getAcct(), getString(R.string.notif_follow)); + targeted_account = notification.getAccount().getId(); + } else { + canSendBroadCast = false; + } + break; + case "poll": + notifType = Helper.NotifType.POLL; + if (notif_poll) { + if (notification.getAccount().getId() != null && notification.getAccount().getId().equals(userId)) + message = getString(R.string.notif_poll_self); + else + message = getString(R.string.notif_poll); + } else { + canSendBroadCast = false; + } + break; + default: } - } + //Some others notification + final Intent intent = new Intent(LiveNotificationService.this, MainActivity.class); + intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); + intent.putExtra(Helper.INTENT_ACTION, Helper.NOTIFICATION_INTENT); + intent.putExtra(Helper.PREF_KEY_ID, account.getId()); + intent.putExtra(Helper.PREF_INSTANCE, account.getInstance()); + if (targeted_account != null) { + intent.putExtra(Helper.INTENT_TARGETED_ACCOUNT, targeted_account); + } + final String finalMessage = message; + Handler mainHandler = new Handler(Looper.getMainLooper()); + Helper.NotifType finalNotifType = notifType; + Runnable myRunnable = () -> { + if (finalMessage != null) { + Glide.with(LiveNotificationService.this) + .asBitmap() + .load(notification.getAccount().getAvatar()) + .listener(new RequestListener() { + @Override + public boolean onResourceReady(Bitmap resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) { + return false; + } - if (canSendBroadCast) { - b.putString("userIdService", account.getId()); - Intent intentBC = new Intent(Helper.RECEIVE_DATA); - intentBC.putExtra("eventStreaming", event); - intentBC.putExtras(b); - b.putParcelable("data", notification); - LocalBroadcastManager.getInstance(LiveNotificationService.this).sendBroadcast(intentBC); - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putString(Helper.LAST_NOTIFICATION_MAX_ID + account.getId() + account.getInstance(), notification.getId()); - editor.apply(); + @Override + public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) { + assert e != null; + Helper.notify_user(LiveNotificationService.this, account, intent, BitmapFactory.decodeResource(getResources(), + getMainLogo(LiveNotificationService.this)), finalNotifType, "@" + notification.getAccount().getAcct(), finalMessage); + return false; + } + }) + .into(new CustomTarget() { + @Override + public void onResourceReady(@NonNull Bitmap resource, Transition transition) { + Helper.notify_user(LiveNotificationService.this, account, intent, resource, finalNotifType, "@" + notification.getAccount().getAcct(), finalMessage); + } + + @Override + public void onLoadCleared(@Nullable Drawable placeholder) { + + } + }); + } + }; + mainHandler.post(myRunnable); } - break; - case "delete": - event = Helper.EventStreaming.DELETE; - try { - dataId = response.getString("id"); - b.putString("dataId", dataId); - } catch (JSONException ignored) { - } - break; + } + + if (canSendBroadCast) { + b.putString("userIdService", account.getId()); + Intent intentBC = new Intent(Helper.RECEIVE_DATA); + intentBC.putExtra("eventStreaming", event); + intentBC.putExtras(b); + b.putParcelable("data", notification); + LocalBroadcastManager.getInstance(LiveNotificationService.this).sendBroadcast(intentBC); + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putString(Helper.LAST_NOTIFICATION_MAX_ID + account.getId() + account.getInstance(), notification.getId()); + editor.apply(); + } } } catch (Exception ignored) { } @@ -521,7 +518,6 @@ public class LiveNotificationService extends Service implements NetworkStateRece for (Thread t : Thread.getAllStackTraces().keySet()) { if (t.getName().startsWith("notif_live_")) { t.interrupt(); - t = null; } } Thread.currentThread().interrupt(); 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 03b2aef6a..2ff960735 100644 --- a/app/src/main/java/app/fedilab/android/services/StreamingFederatedTimelineService.java +++ b/app/src/main/java/app/fedilab/android/services/StreamingFederatedTimelineService.java @@ -29,7 +29,6 @@ import androidx.localbroadcastmanager.content.LocalBroadcastManager; import com.koushikdutta.async.http.AsyncHttpClient; import com.koushikdutta.async.http.AsyncHttpRequest; import com.koushikdutta.async.http.Headers; -import com.koushikdutta.async.http.WebSocket; import org.json.JSONException; import org.json.JSONObject; @@ -37,8 +36,6 @@ import org.json.JSONObject; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; -import javax.net.ssl.HttpsURLConnection; - import app.fedilab.android.client.API; import app.fedilab.android.client.Entities.Account; import app.fedilab.android.client.Entities.Status; @@ -55,7 +52,6 @@ import app.fedilab.android.sqlite.Sqlite; public class StreamingFederatedTimelineService extends IntentService { - private static HttpsURLConnection httpsURLConnection; static { Helper.installProvider(); @@ -116,34 +112,27 @@ public class StreamingFederatedTimelineService extends IntentService { try { AsyncHttpClient.getDefaultInstance().getSSLSocketMiddleware().setSSLContext(new TLSSocketFactory(accountStream.getInstance()).getSSLContext()); AsyncHttpClient.getDefaultInstance().getSSLSocketMiddleware().setConnectAllAddresses(true); - } catch (KeyManagementException e) { - e.printStackTrace(); - } catch (NoSuchAlgorithmException e) { + } catch (KeyManagementException | NoSuchAlgorithmException e) { e.printStackTrace(); } } - AsyncHttpClient.getDefaultInstance().websocket("wss://" + accountStream.getInstance() + "/api/v1/streaming/?stream=public&access_token=" + accountStream.getToken(), "wss", new AsyncHttpClient.WebSocketConnectCallback() { - @Override - public void onCompleted(Exception ex, WebSocket webSocket) { - if (ex != null) { - ex.printStackTrace(); + AsyncHttpClient.getDefaultInstance().websocket("wss://" + accountStream.getInstance() + "/api/v1/streaming/?stream=public&access_token=" + accountStream.getToken(), "wss", (ex, webSocket) -> { + if (ex != null) { + ex.printStackTrace(); + return; + } + webSocket.setStringCallback(s -> { + if (!sharedpreferences.getBoolean(Helper.SHOULD_CONTINUE_STREAMING_FEDERATED + finalAccountStream.getId() + finalAccountStream.getInstance(), true)) { + stopSelf(); return; } - webSocket.setStringCallback(new WebSocket.StringCallback() { - public void onStringAvailable(String s) { - if (!sharedpreferences.getBoolean(Helper.SHOULD_CONTINUE_STREAMING_FEDERATED + finalAccountStream.getId() + finalAccountStream.getInstance(), true)) { - stopSelf(); - return; - } - try { - JSONObject eventJson = new JSONObject(s); + try { + JSONObject eventJson = new JSONObject(s); - onRetrieveStreaming(finalAccountStream, eventJson); - } catch (JSONException ignored) { - } - } - }); - } + onRetrieveStreaming(finalAccountStream, eventJson); + } catch (JSONException ignored) { + } + }); }); } } 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 a263b904a..858727ffa 100644 --- a/app/src/main/java/app/fedilab/android/services/StreamingHomeTimelineService.java +++ b/app/src/main/java/app/fedilab/android/services/StreamingHomeTimelineService.java @@ -29,7 +29,6 @@ import androidx.localbroadcastmanager.content.LocalBroadcastManager; import com.koushikdutta.async.http.AsyncHttpClient; import com.koushikdutta.async.http.AsyncHttpRequest; import com.koushikdutta.async.http.Headers; -import com.koushikdutta.async.http.WebSocket; import org.json.JSONException; import org.json.JSONObject; @@ -37,8 +36,6 @@ import org.json.JSONObject; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; -import javax.net.ssl.HttpsURLConnection; - import app.fedilab.android.client.API; import app.fedilab.android.client.Entities.Account; import app.fedilab.android.client.Entities.Status; @@ -55,7 +52,6 @@ import app.fedilab.android.sqlite.Sqlite; public class StreamingHomeTimelineService extends IntentService { - private static HttpsURLConnection httpsURLConnection; static { Helper.installProvider(); @@ -116,34 +112,27 @@ public class StreamingHomeTimelineService extends IntentService { try { AsyncHttpClient.getDefaultInstance().getSSLSocketMiddleware().setSSLContext(new TLSSocketFactory(accountStream.getInstance()).getSSLContext()); AsyncHttpClient.getDefaultInstance().getSSLSocketMiddleware().setConnectAllAddresses(true); - } catch (KeyManagementException e) { - e.printStackTrace(); - } catch (NoSuchAlgorithmException e) { + } catch (KeyManagementException | NoSuchAlgorithmException e) { e.printStackTrace(); } } - AsyncHttpClient.getDefaultInstance().websocket("wss://" + accountStream.getInstance() + "/api/v1/streaming/?stream=user&access_token=" + accountStream.getToken(), "wss", new AsyncHttpClient.WebSocketConnectCallback() { - @Override - public void onCompleted(Exception ex, WebSocket webSocket) { - if (ex != null) { - ex.printStackTrace(); + AsyncHttpClient.getDefaultInstance().websocket("wss://" + accountStream.getInstance() + "/api/v1/streaming/?stream=user&access_token=" + accountStream.getToken(), "wss", (ex, webSocket) -> { + if (ex != null) { + ex.printStackTrace(); + return; + } + webSocket.setStringCallback(s -> { + if (!sharedpreferences.getBoolean(Helper.SHOULD_CONTINUE_STREAMING_HOME + finalAccountStream.getId() + finalAccountStream.getInstance(), true)) { + stopSelf(); return; } - webSocket.setStringCallback(new WebSocket.StringCallback() { - public void onStringAvailable(String s) { - if (!sharedpreferences.getBoolean(Helper.SHOULD_CONTINUE_STREAMING_HOME + finalAccountStream.getId() + finalAccountStream.getInstance(), true)) { - stopSelf(); - return; - } - try { - JSONObject eventJson = new JSONObject(s); + try { + JSONObject eventJson = new JSONObject(s); - onRetrieveStreaming(finalAccountStream, eventJson); - } catch (JSONException ignored) { - } - } - }); - } + onRetrieveStreaming(finalAccountStream, eventJson); + } catch (JSONException ignored) { + } + }); }); } } 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 4cd1be065..ae9a2f7ea 100644 --- a/app/src/main/java/app/fedilab/android/services/StreamingLocalTimelineService.java +++ b/app/src/main/java/app/fedilab/android/services/StreamingLocalTimelineService.java @@ -29,7 +29,6 @@ import androidx.localbroadcastmanager.content.LocalBroadcastManager; import com.koushikdutta.async.http.AsyncHttpClient; import com.koushikdutta.async.http.AsyncHttpRequest; import com.koushikdutta.async.http.Headers; -import com.koushikdutta.async.http.WebSocket; import org.json.JSONException; import org.json.JSONObject; @@ -37,8 +36,6 @@ import org.json.JSONObject; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; -import javax.net.ssl.HttpsURLConnection; - import app.fedilab.android.client.API; import app.fedilab.android.client.Entities.Account; import app.fedilab.android.client.Entities.Status; @@ -55,7 +52,6 @@ import app.fedilab.android.sqlite.Sqlite; public class StreamingLocalTimelineService extends IntentService { - private static HttpsURLConnection httpsURLConnection; static { Helper.installProvider(); @@ -117,33 +113,26 @@ public class StreamingLocalTimelineService extends IntentService { try { AsyncHttpClient.getDefaultInstance().getSSLSocketMiddleware().setSSLContext(new TLSSocketFactory(accountStream.getInstance()).getSSLContext()); AsyncHttpClient.getDefaultInstance().getSSLSocketMiddleware().setConnectAllAddresses(true); - } catch (KeyManagementException e) { - e.printStackTrace(); - } catch (NoSuchAlgorithmException e) { + } catch (KeyManagementException | NoSuchAlgorithmException e) { e.printStackTrace(); } } - AsyncHttpClient.getDefaultInstance().websocket("wss://" + accountStream.getInstance() + "/api/v1/streaming/?stream=public:local&access_token=" + accountStream.getToken(), "wss", new AsyncHttpClient.WebSocketConnectCallback() { - @Override - public void onCompleted(Exception ex, WebSocket webSocket) { - if (ex != null) { - ex.printStackTrace(); + AsyncHttpClient.getDefaultInstance().websocket("wss://" + accountStream.getInstance() + "/api/v1/streaming/?stream=public:local&access_token=" + accountStream.getToken(), "wss", (ex, webSocket) -> { + if (ex != null) { + ex.printStackTrace(); + return; + } + webSocket.setStringCallback(s -> { + if (!sharedpreferences.getBoolean(Helper.SHOULD_CONTINUE_STREAMING_LOCAL + finalAccountStream.getId() + finalAccountStream.getInstance(), true)) { + stopSelf(); return; } - webSocket.setStringCallback(new WebSocket.StringCallback() { - public void onStringAvailable(String s) { - if (!sharedpreferences.getBoolean(Helper.SHOULD_CONTINUE_STREAMING_LOCAL + finalAccountStream.getId() + finalAccountStream.getInstance(), true)) { - stopSelf(); - return; - } - try { - JSONObject eventJson = new JSONObject(s); - onRetrieveStreaming(finalAccountStream, eventJson); - } catch (JSONException ignored) { - } - } - }); - } + try { + JSONObject eventJson = new JSONObject(s); + onRetrieveStreaming(finalAccountStream, eventJson); + } catch (JSONException ignored) { + } + }); }); } } diff --git a/app/src/main/java/app/fedilab/android/sqlite/DomainBlockDAO.java b/app/src/main/java/app/fedilab/android/sqlite/DomainBlockDAO.java index 6a1ab654d..15d2bddbd 100644 --- a/app/src/main/java/app/fedilab/android/sqlite/DomainBlockDAO.java +++ b/app/src/main/java/app/fedilab/android/sqlite/DomainBlockDAO.java @@ -51,7 +51,8 @@ public class DomainBlockDAO { values.put(Sqlite.COL_DOMAIN, domain); try { db.insert(Sqlite.TABLE_TRACKING_BLOCK, null, values); - } catch (Exception ignored) {} + } catch (Exception ignored) { + } } /** diff --git a/app/src/main/res/layout-sw600dp/activity_show_account.xml b/app/src/main/res/layout-sw600dp/activity_show_account.xml index 489d971be..49de64803 100644 --- a/app/src/main/res/layout-sw600dp/activity_show_account.xml +++ b/app/src/main/res/layout-sw600dp/activity_show_account.xml @@ -172,7 +172,7 @@ android:id="@+id/account_dn" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:maxLines="1" + android:singleLine="true" android:textAppearance="@style/TextAppearance.AppCompat.Body1" android:textColor="?colorAccent" android:textSize="16sp" /> @@ -181,7 +181,7 @@ android:id="@+id/account_un" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:maxLines="1" + android:singleLine="true" android:textSize="14sp" /> @@ -279,7 +279,7 @@ android:layout_marginStart="3dp" android:layout_marginEnd="3dp" android:background="@drawable/blue_border" - android:maxLines="1" + android:singleLine="true" android:visibility="gone" android:textColor="@color/mastodonC4" /> @@ -290,7 +290,7 @@ android:layout_marginStart="3dp" android:layout_marginEnd="3dp" android:background="@drawable/green_border" - android:maxLines="1" + android:singleLine="true" android:text="@string/followed_by" android:textColor="@color/verified_text" android:visibility="gone" /> @@ -302,7 +302,7 @@ android:layout_marginStart="3dp" android:layout_marginEnd="3dp" android:background="@drawable/blue_border" - android:maxLines="1" + android:singleLine="true" android:text="@string/request_sent" android:textColor="@color/mastodonC4" android:visibility="gone" /> @@ -521,7 +521,7 @@ android:layout_marginStart="5dp" android:layout_marginLeft="5dp" android:layout_weight="1" - android:maxLines="1" + android:singleLine="true" android:textSize="14sp" /> @@ -57,7 +57,7 @@ android:id="@+id/account_un" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:maxLines="1" + android:singleLine="true" android:textSize="14sp" /> @@ -66,7 +66,7 @@ android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" - android:maxLines="1" + android:singleLine="true" android:textSize="16sp" android:visibility="gone" /> @@ -93,7 +93,7 @@ diff --git a/app/src/main/res/layout/activity_admin_report.xml b/app/src/main/res/layout/activity_admin_report.xml index c29f3e869..401da93af 100644 --- a/app/src/main/res/layout/activity_admin_report.xml +++ b/app/src/main/res/layout/activity_admin_report.xml @@ -344,9 +344,9 @@ android:id="@+id/comment" android:layout_width="match_parent" android:layout_height="wrap_content" + android:importantForAutofill="no" android:minLines="3" - app:layout_constraintTop_toBottomOf="@id/comment_label" - android:importantForAutofill="no" /> + app:layout_constraintTop_toBottomOf="@id/comment_label" /> + android:minLines="1" /> diff --git a/app/src/main/res/layout/activity_edit_profile.xml b/app/src/main/res/layout/activity_edit_profile.xml index 415401a84..d4ed179f7 100644 --- a/app/src/main/res/layout/activity_edit_profile.xml +++ b/app/src/main/res/layout/activity_edit_profile.xml @@ -56,7 +56,7 @@ android:layout_height="wrap_content" android:layout_marginTop="10dp" android:inputType="textPersonName" - android:maxLines="1" /> + android:singleLine="true" />