From f23a0fb5d8aec436e1952aac3a48e34db0c90d31 Mon Sep 17 00:00:00 2001 From: bemusementpark Date: Wed, 10 Jul 2024 16:49:41 +0930 Subject: [PATCH] Remove static preferences methods --- .../loki/messenger/HomeActivityTests.kt | 6 +- .../network/loki/messenger/LibSessionTests.kt | 8 +- .../securesms/ApplicationContext.java | 27 +- .../securesms/BaseActionBarActivity.java | 7 +- .../thoughtcrime/securesms/BaseActivity.java | 13 +- .../securesms/PassphrasePromptActivity.java | 13 +- .../PassphraseRequiredActionBarActivity.java | 8 +- .../securesms/components/ComposeText.java | 9 +- .../components/CustomDefaultPreference.java | 10 +- .../components/camera/CameraView.java | 6 +- .../components/emoji/EmojiTextView.java | 6 +- .../securesms/contacts/ContactAccessor.java | 4 +- .../start/home/StartConversationFragment.kt | 4 +- .../invitefriend/InviteFriendFragment.kt | 4 +- .../v2/ConversationReactionOverlay.kt | 7 +- .../v2/dialogs/LinkPreviewDialog.kt | 4 +- .../conversation/v2/input_bar/InputBar.kt | 8 +- .../menus/ConversationActionModeCallback.kt | 3 +- .../v2/menus/ConversationMenuHelper.kt | 6 +- .../v2/messages/EmojiReactionsView.kt | 5 +- .../conversation/v2/messages/QuoteView.kt | 4 +- .../v2/utilities/MentionUtilities.kt | 4 +- .../v2/utilities/ResendMessageUtilities.kt | 3 +- .../crypto/AttachmentSecretProvider.java | 64 +- .../crypto/BiometricSecretProvider.kt | 8 +- .../crypto/DatabaseSecretProvider.java | 50 +- .../securesms/database/GroupDatabase.java | 5 +- .../securesms/database/LokiAPIDatabase.kt | 6 +- .../securesms/database/LokiUserDatabase.kt | 6 +- .../securesms/database/MessagingDatabase.java | 1 - .../securesms/database/MmsDatabase.kt | 7 +- .../securesms/database/MmsSmsDatabase.java | 10 +- .../securesms/database/SmsDatabase.java | 3 +- .../securesms/database/Storage.kt | 30 +- .../securesms/database/ThreadDatabase.java | 3 +- .../database/helpers/SQLCipherOpenHelper.java | 5 +- .../securesms/dependencies/AppModule.kt | 1 + .../securesms/dependencies/ConfigFactory.kt | 4 +- .../securesms/dependencies/DatabaseModule.kt | 7 +- .../dependencies/SessionUtilModule.kt | 4 +- .../securesms/giph/ui/GiphyActivity.java | 3 +- ...olbarTextSecurePreferencesPersistence.java | 28 - ...ToolbarTextSecurePreferencesPersistence.kt | 9 + .../securesms/giph/ui/GiphyFragment.java | 4 +- .../securesms/groups/CreateGroupFragment.kt | 4 +- .../groups/EditClosedGroupActivity.kt | 6 +- .../groups/EditClosedGroupMembersAdapter.kt | 4 +- .../securesms/groups/GroupManager.java | 2 +- .../securesms/home/HomeActivity.kt | 3 +- .../securesms/logging/LogSecretProvider.java | 13 +- .../securesms/mediasend/Camera1Fragment.java | 6 +- .../mediasend/MediaSendFragment.java | 6 +- .../securesms/mms/SignalGlideModule.java | 2 +- .../AbstractNotificationBuilder.java | 7 +- .../notifications/BackgroundPollWorker.kt | 5 +- .../notifications/DefaultMessageNotifier.java | 25 +- .../notifications/MarkReadReceiver.kt | 13 +- .../MultipleRecipientNotificationBuilder.java | 3 +- .../notifications/NotificationChannels.java | 21 +- .../PendingMessageNotificationBuilder.java | 3 +- .../SingleRecipientNotificationBuilder.java | 3 +- .../securesms/notifications/TokenManager.kt | 8 +- .../onboarding/landing/LandingActivity.kt | 2 +- .../preferences/CallToggleListener.kt | 16 +- .../NotificationsPreferenceFragment.kt | 5 +- .../PrivacySettingsPreferenceFragment.kt | 15 +- .../securesms/preferences/QRCodeActivity.kt | 4 +- .../securesms/preferences/SettingsActivity.kt | 10 +- .../securesms/preferences/Util.kt | 6 +- .../securesms/providers/BlobProvider.java | 4 +- .../scribbles/ImageEditorFragment.java | 4 +- .../securesms/search/SearchRepository.java | 4 +- .../service/ExpiringMessageManager.kt | 10 +- .../securesms/service/KeyCachingService.java | 32 +- .../service/PanicResponderListener.java | 5 +- .../service/UpdateApkReadyListener.java | 5 +- .../sskenvironment/ProfileManager.kt | 4 +- .../sskenvironment/ReadReceiptManager.kt | 4 +- .../TypingStatusRepository.java | 5 +- .../ui/color/ColorsFromPreferences.kt | 1 + .../securesms/util/AttachmentUtil.java | 7 +- .../util/ConfigurationMessageUtilities.kt | 6 +- .../securesms/util/VersionTracker.kt | 8 +- .../messaging/MessagingModuleConfiguration.kt | 18 +- .../jobs/RetrieveProfileAvatarJob.kt | 11 +- .../messaging/jobs/TrimThreadJob.kt | 4 +- .../messages/control/ConfigurationMessage.kt | 6 +- .../messaging/open_groups/OpenGroupApi.kt | 6 +- .../MessageSenderClosedGroupHandler.kt | 3 +- .../ReceivedMessageHandler.kt | 21 +- .../notifications/PushRegistryV1.kt | 13 +- .../libsession/utilities/ProfileKeyUtil.java | 9 +- .../utilities/ProfilePictureUtilities.kt | 5 +- .../utilities/TextSecurePreferences.kt | 853 ++++-------------- .../org/session/libsession/utilities/Util.kt | 5 +- .../utilities/recipients/Recipient.java | 4 +- .../recipients/RecipientProvider.java | 11 +- 97 files changed, 597 insertions(+), 1090 deletions(-) delete mode 100644 app/src/main/java/org/thoughtcrime/securesms/giph/ui/GiphyActivityToolbarTextSecurePreferencesPersistence.java create mode 100644 app/src/main/java/org/thoughtcrime/securesms/giph/ui/GiphyActivityToolbarTextSecurePreferencesPersistence.kt diff --git a/app/src/androidTest/java/network/loki/messenger/HomeActivityTests.kt b/app/src/androidTest/java/network/loki/messenger/HomeActivityTests.kt index 6fb3888ff2..f1889c9217 100644 --- a/app/src/androidTest/java/network/loki/messenger/HomeActivityTests.kt +++ b/app/src/androidTest/java/network/loki/messenger/HomeActivityTests.kt @@ -100,7 +100,7 @@ class HomeActivityTests { // PN select if (hasViewedSeed) { // has viewed seed is set to false after register activity - TextSecurePreferences.setHasViewedSeed(InstrumentationRegistry.getInstrumentation().targetContext, true) + context.prefs.setHasViewedSeed(InstrumentationRegistry.getInstrumentation().targetContext, true) } // allow notification permission PermissionGranter.allowPermissionsIfNeeded(Manifest.permission.POST_NOTIFICATIONS) @@ -149,7 +149,7 @@ class HomeActivityTests { fun testChat_withSelf() { setupLoggedInState() goToMyChat() - TextSecurePreferences.setLinkPreviewsEnabled(context, true) + context.prefs.setLinkPreviewsEnabled(context, true) sendMessage("howdy") sendMessage("test") // tests url rewriter doesn't crash @@ -161,7 +161,7 @@ class HomeActivityTests { fun testChat_displaysCorrectUrl() { setupLoggedInState() goToMyChat() - TextSecurePreferences.setLinkPreviewsEnabled(InstrumentationRegistry.getInstrumentation().targetContext, true) + context.prefs.setLinkPreviewsEnabled(InstrumentationRegistry.getInstrumentation().targetContext, true) // given the link url text val url = "https://www.ámazon.com" sendMessage(url, LinkPreview(url, "amazon", Optional.absent())) diff --git a/app/src/androidTest/java/network/loki/messenger/LibSessionTests.kt b/app/src/androidTest/java/network/loki/messenger/LibSessionTests.kt index 54470569e1..9cc76ce7d5 100644 --- a/app/src/androidTest/java/network/loki/messenger/LibSessionTests.kt +++ b/app/src/androidTest/java/network/loki/messenger/LibSessionTests.kt @@ -90,10 +90,10 @@ class LibSessionTests { val kp = KeyPairUtilities.generate(newBytes) KeyPairUtilities.store(context, kp.seed, kp.ed25519KeyPair, kp.x25519KeyPair) val registrationID = KeyHelper.generateRegistrationId(false) - TextSecurePreferences.setLocalRegistrationId(context, registrationID) - TextSecurePreferences.setLocalNumber(context, kp.x25519KeyPair.hexEncodedPublicKey) - TextSecurePreferences.setRestorationTime(context, 0) - TextSecurePreferences.setHasViewedSeed(context, false) + context.prefs.setLocalRegistrationId(context, registrationID) + context.prefs.setLocalNumber(context, kp.x25519KeyPair.hexEncodedPublicKey) + context.prefs.setRestorationTime(context, 0) + context.prefs.setHasViewedSeed(context, false) } @Test diff --git a/app/src/main/java/org/thoughtcrime/securesms/ApplicationContext.java b/app/src/main/java/org/thoughtcrime/securesms/ApplicationContext.java index bbf494cce3..53b9700db6 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/ApplicationContext.java +++ b/app/src/main/java/org/thoughtcrime/securesms/ApplicationContext.java @@ -110,7 +110,6 @@ import javax.inject.Inject; import dagger.hilt.EntryPoints; import dagger.hilt.android.HiltAndroidApp; import kotlin.Unit; -import kotlinx.coroutines.Job; import network.loki.messenger.BuildConfig; import network.loki.messenger.libsession_util.ConfigBase; import network.loki.messenger.libsession_util.UserProfile; @@ -152,20 +151,11 @@ public class ApplicationContext extends Application implements DefaultLifecycleO @Inject ConfigFactory configFactory; @Inject LastSentTimestampCache lastSentTimestampCache; CallMessageProcessor callMessageProcessor; - MessagingModuleConfiguration messagingModuleConfiguration; private volatile boolean isAppVisible; public boolean newAccount = false; - @Override - public Object getSystemService(String name) { - if (MessagingModuleConfiguration.MESSAGING_MODULE_SERVICE.equals(name)) { - return messagingModuleConfiguration; - } - return super.getSystemService(name); - } - public static ApplicationContext getInstance(Context context) { return (ApplicationContext) context.getApplicationContext(); } @@ -214,9 +204,8 @@ public class ApplicationContext extends Application implements DefaultLifecycleO TextSecurePreferences.setPushSuffix(BuildConfig.PUSH_KEY_SUFFIX); DatabaseModule.init(this); - MessagingModuleConfiguration.configure(this); super.onCreate(); - messagingModuleConfiguration = new MessagingModuleConfiguration( + MessagingModuleConfiguration.shared = new MessagingModuleConfiguration( this, storage, device, @@ -431,12 +420,12 @@ public class ApplicationContext extends Application implements DefaultLifecycleO @Override protected void attachBaseContext(Context base) { initializeLocaleParser(); - super.attachBaseContext(DynamicLanguageContextWrapper.updateContext(base, TextSecurePreferences.getLanguage(base))); + super.attachBaseContext(DynamicLanguageContextWrapper.updateContext(base, new TextSecurePreferences(base).getLanguage())); } private static class ProviderInitializationException extends RuntimeException { } private void setUpPollingIfNeeded() { - String userPublicKey = TextSecurePreferences.getLocalNumber(this); + String userPublicKey = textSecurePreferences.getLocalNumber(); if (userPublicKey == null) return; if (poller != null) { poller.setUserPublicKey(userPublicKey); @@ -463,15 +452,15 @@ public class ApplicationContext extends Application implements DefaultLifecycleO private void resubmitProfilePictureIfNeeded() { // Files expire on the file server after a while, so we simply re-upload the user's profile picture // at a certain interval to ensure it's always available. - String userPublicKey = TextSecurePreferences.getLocalNumber(this); + String userPublicKey = textSecurePreferences.getLocalNumber(); if (userPublicKey == null) return; long now = new Date().getTime(); - long lastProfilePictureUpload = TextSecurePreferences.getLastProfilePictureUpload(this); + long lastProfilePictureUpload = textSecurePreferences.getLastProfilePictureUpload(); if (now - lastProfilePictureUpload <= 14 * 24 * 60 * 60 * 1000) return; ThreadUtils.queue(() -> { // Don't generate a new profile key here; we do that when the user changes their profile picture Log.d("Loki-Avatar", "Uploading Avatar Started"); - String encodedProfileKey = TextSecurePreferences.getProfileKey(ApplicationContext.this); + String encodedProfileKey = textSecurePreferences.getProfileKey(); try { // Read the file into a byte array InputStream inputStream = AvatarHelper.getInputStreamFor(ApplicationContext.this, Address.fromSerialized(userPublicKey)); @@ -486,7 +475,7 @@ public class ApplicationContext extends Application implements DefaultLifecycleO // Re-upload it ProfilePictureUtilities.INSTANCE.upload(profilePicture, encodedProfileKey, ApplicationContext.this).success(unit -> { // Update the last profile picture upload date - TextSecurePreferences.setLastProfilePictureUpload(ApplicationContext.this, new Date().getTime()); + textSecurePreferences.setLastProfilePictureUpload(new Date().getTime()); Log.d("Loki-Avatar", "Uploading Avatar Finished"); return Unit.INSTANCE; }); @@ -518,7 +507,7 @@ public class ApplicationContext extends Application implements DefaultLifecycleO */ @SuppressLint("ApplySharedPref") public boolean clearAllData() { - TextSecurePreferences.clearAll(this); + getPrefs().clearAll(); getSharedPreferences(PREFERENCES_NAME, 0).edit().clear().commit(); if (!deleteDatabase(SQLCipherOpenHelper.DATABASE_NAME)) { Log.d("Loki", "Failed to delete database."); diff --git a/app/src/main/java/org/thoughtcrime/securesms/BaseActionBarActivity.java b/app/src/main/java/org/thoughtcrime/securesms/BaseActionBarActivity.java index a99fe83430..ef1bb3fae7 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/BaseActionBarActivity.java +++ b/app/src/main/java/org/thoughtcrime/securesms/BaseActionBarActivity.java @@ -16,6 +16,7 @@ import androidx.annotation.StyleRes; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.session.libsession.utilities.TextSecurePreferences; import org.session.libsession.utilities.dynamiclanguage.DynamicLanguageActivityHelper; import org.session.libsession.utilities.dynamiclanguage.DynamicLanguageContextWrapper; @@ -97,7 +98,7 @@ public abstract class BaseActionBarActivity extends AppCompatActivity { protected void onResume() { super.onResume(); initializeScreenshotSecurity(true); - DynamicLanguageActivityHelper.recreateIfNotInCorrectLanguage(this, TextSecurePreferences.getLanguage(this)); + DynamicLanguageActivityHelper.recreateIfNotInCorrectLanguage(this, MessagingModuleConfiguration.getShared().getPrefs().getLanguage()); String name = getResources().getString(R.string.app_name); Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground); int color = getResources().getColor(R.color.app_icon_background); @@ -130,7 +131,7 @@ public abstract class BaseActionBarActivity extends AppCompatActivity { if (!isResume) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE); } else { - if (TextSecurePreferences.isScreenSecurityEnabled(this)) { + if (MessagingModuleConfiguration.getShared().getPrefs().isScreenSecurityEnabled()) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE); } else { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE); @@ -140,6 +141,6 @@ public abstract class BaseActionBarActivity extends AppCompatActivity { @Override protected void attachBaseContext(Context newBase) { - super.attachBaseContext(DynamicLanguageContextWrapper.updateContext(newBase, TextSecurePreferences.getLanguage(newBase))); + super.attachBaseContext(DynamicLanguageContextWrapper.updateContext(newBase, MessagingModuleConfiguration.getShared().getPrefs().getLanguage())); } } diff --git a/app/src/main/java/org/thoughtcrime/securesms/BaseActivity.java b/app/src/main/java/org/thoughtcrime/securesms/BaseActivity.java index d5286698cd..e2897686c4 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/BaseActivity.java +++ b/app/src/main/java/org/thoughtcrime/securesms/BaseActivity.java @@ -4,13 +4,10 @@ import android.app.ActivityManager; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; -import android.os.Build; -import android.os.Build.VERSION; -import android.os.Build.VERSION_CODES; -import androidx.annotation.NonNull; -import androidx.fragment.app.FragmentActivity; -import android.view.KeyEvent; +import androidx.fragment.app.FragmentActivity; + +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.session.libsession.utilities.TextSecurePreferences; import org.session.libsession.utilities.dynamiclanguage.DynamicLanguageActivityHelper; import org.session.libsession.utilities.dynamiclanguage.DynamicLanguageContextWrapper; @@ -21,7 +18,7 @@ public abstract class BaseActivity extends FragmentActivity { @Override protected void onResume() { super.onResume(); - DynamicLanguageActivityHelper.recreateIfNotInCorrectLanguage(this, TextSecurePreferences.getLanguage(this)); + DynamicLanguageActivityHelper.recreateIfNotInCorrectLanguage(this, MessagingModuleConfiguration.getShared().getPrefs().getLanguage()); String name = getResources().getString(R.string.app_name); Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground); int color = getResources().getColor(R.color.app_icon_background); @@ -30,6 +27,6 @@ public abstract class BaseActivity extends FragmentActivity { @Override protected void attachBaseContext(Context newBase) { - super.attachBaseContext(DynamicLanguageContextWrapper.updateContext(newBase, TextSecurePreferences.getLanguage(newBase))); + super.attachBaseContext(DynamicLanguageContextWrapper.updateContext(newBase, MessagingModuleConfiguration.getShared().getPrefs().getLanguage())); } } diff --git a/app/src/main/java/org/thoughtcrime/securesms/PassphrasePromptActivity.java b/app/src/main/java/org/thoughtcrime/securesms/PassphrasePromptActivity.java index afc993df8a..8b51a52fe8 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/PassphrasePromptActivity.java +++ b/app/src/main/java/org/thoughtcrime/securesms/PassphrasePromptActivity.java @@ -39,14 +39,13 @@ import android.widget.ImageView; import androidx.core.hardware.fingerprint.FingerprintManagerCompat; import androidx.core.os.CancellationSignal; -import org.session.libsession.utilities.TextSecurePreferences; +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.session.libsignal.utilities.Log; import org.thoughtcrime.securesms.components.AnimatingToggle; import org.thoughtcrime.securesms.crypto.BiometricSecretProvider; import org.thoughtcrime.securesms.service.KeyCachingService; import org.thoughtcrime.securesms.util.AnimationCompleteListener; -import java.security.InvalidKeyException; import java.security.Signature; import network.loki.messenger.R; @@ -103,7 +102,7 @@ public class PassphrasePromptActivity extends BaseActionBarActivity { setLockTypeVisibility(); - if (TextSecurePreferences.isScreenLockEnabled(this) && !authenticated && !failure) { + if (MessagingModuleConfiguration.getShared().getPrefs().isScreenLockEnabled() && !authenticated && !failure) { resumeScreenLock(); } @@ -114,7 +113,7 @@ public class PassphrasePromptActivity extends BaseActionBarActivity { public void onPause() { super.onPause(); - if (TextSecurePreferences.isScreenLockEnabled(this)) { + if (MessagingModuleConfiguration.getShared().getPrefs().isScreenLockEnabled()) { pauseScreenLock(); } } @@ -176,7 +175,7 @@ public class PassphrasePromptActivity extends BaseActionBarActivity { } private void setLockTypeVisibility() { - if (TextSecurePreferences.isScreenLockEnabled(this)) { + if (MessagingModuleConfiguration.getShared().getPrefs().isScreenLockEnabled()) { if (fingerprintManager.isHardwareDetected() && fingerprintManager.hasEnrolledFingerprints()) { fingerprintPrompt.setVisibility(View.VISIBLE); lockScreenButton.setVisibility(View.GONE); @@ -197,8 +196,8 @@ public class PassphrasePromptActivity extends BaseActionBarActivity { if (!keyguardManager.isKeyguardSecure()) { Log.w(TAG ,"Keyguard not secure..."); - TextSecurePreferences.setScreenLockEnabled(getApplicationContext(), false); - TextSecurePreferences.setScreenLockTimeout(getApplicationContext(), 0); + MessagingModuleConfiguration.getShared().getPrefs().setScreenLockEnabled(false); + MessagingModuleConfiguration.getShared().getPrefs().setScreenLockTimeout(0); handleAuthenticated(); return; } diff --git a/app/src/main/java/org/thoughtcrime/securesms/PassphraseRequiredActionBarActivity.java b/app/src/main/java/org/thoughtcrime/securesms/PassphraseRequiredActionBarActivity.java index dbe7c4a433..cd2b5a776d 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/PassphraseRequiredActionBarActivity.java +++ b/app/src/main/java/org/thoughtcrime/securesms/PassphraseRequiredActionBarActivity.java @@ -12,7 +12,7 @@ import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; -import org.session.libsession.utilities.TextSecurePreferences; +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.session.libsignal.utilities.Log; import org.thoughtcrime.securesms.home.HomeActivity; import org.thoughtcrime.securesms.onboarding.landing.LandingActivity; @@ -39,8 +39,8 @@ public abstract class PassphraseRequiredActionBarActivity extends BaseActionBarA onPreCreate(); final boolean locked = KeyCachingService.isLocked(this) && - TextSecurePreferences.isScreenLockEnabled(this) && - TextSecurePreferences.getLocalNumber(this) != null; + MessagingModuleConfiguration.getShared().getPrefs().isScreenLockEnabled() && + MessagingModuleConfiguration.getShared().getPrefs().getLocalNumber() != null; routeApplicationState(locked); super.onCreate(savedInstanceState); @@ -125,7 +125,7 @@ public abstract class PassphraseRequiredActionBarActivity extends BaseActionBarA } private int getApplicationState(boolean locked) { - if (TextSecurePreferences.getLocalNumber(this) == null) { + if (MessagingModuleConfiguration.getShared().getPrefs().getLocalNumber() == null) { return STATE_WELCOME_SCREEN; } else if (locked) { return STATE_PROMPT_PASSPHRASE; diff --git a/app/src/main/java/org/thoughtcrime/securesms/components/ComposeText.java b/app/src/main/java/org/thoughtcrime/securesms/components/ComposeText.java index 42825360c0..8595011f2b 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/components/ComposeText.java +++ b/app/src/main/java/org/thoughtcrime/securesms/components/ComposeText.java @@ -22,6 +22,7 @@ import androidx.core.view.inputmethod.EditorInfoCompat; import androidx.core.view.inputmethod.InputConnectionCompat; import androidx.core.view.inputmethod.InputContentInfoCompat; +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.thoughtcrime.securesms.components.emoji.EmojiEditText; import org.session.libsignal.utilities.Log; import org.session.libsession.utilities.TextSecurePreferences; @@ -108,8 +109,8 @@ public class ComposeText extends EmojiEditText { } public void setTransport() { - final boolean useSystemEmoji = TextSecurePreferences.isSystemEmojiPreferred(getContext()); - final boolean isIncognito = TextSecurePreferences.isIncognitoKeyboardEnabled(getContext()); + final boolean useSystemEmoji = MessagingModuleConfiguration.getShared().getPrefs().isSystemEmojiPreferred(); + final boolean isIncognito = MessagingModuleConfiguration.getShared().getPrefs().isIncognitoKeyboardEnabled(); int imeOptions = (getImeOptions() & ~EditorInfo.IME_MASK_ACTION) | EditorInfo.IME_ACTION_SEND; int inputType = getInputType(); @@ -132,7 +133,7 @@ public class ComposeText extends EmojiEditText { public InputConnection onCreateInputConnection(EditorInfo editorInfo) { InputConnection inputConnection = super.onCreateInputConnection(editorInfo); - if(TextSecurePreferences.isEnterSendsEnabled(getContext())) { + if(MessagingModuleConfiguration.getShared().getPrefs().isEnterSendsEnabled()) { editorInfo.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION; } @@ -149,7 +150,7 @@ public class ComposeText extends EmojiEditText { } private void initialize() { - if (TextSecurePreferences.isIncognitoKeyboardEnabled(getContext())) { + if (MessagingModuleConfiguration.getShared().getPrefs().isIncognitoKeyboardEnabled()) { setImeOptions(getImeOptions() | 16777216); } } diff --git a/app/src/main/java/org/thoughtcrime/securesms/components/CustomDefaultPreference.java b/app/src/main/java/org/thoughtcrime/securesms/components/CustomDefaultPreference.java index 178803a9f0..5a1d2b4bee 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/components/CustomDefaultPreference.java +++ b/app/src/main/java/org/thoughtcrime/securesms/components/CustomDefaultPreference.java @@ -12,6 +12,8 @@ import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.AttributeSet; + +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.session.libsignal.utilities.Log; import android.view.View; import android.widget.AdapterView; @@ -84,19 +86,19 @@ public class CustomDefaultPreference extends DialogPreference { } private boolean isCustom() { - return TextSecurePreferences.getBooleanPreference(getContext(), customToggle, false); + return MessagingModuleConfiguration.getShared().getPrefs().getBooleanPreference(customToggle, false); } private void setCustom(boolean custom) { - TextSecurePreferences.setBooleanPreference(getContext(), customToggle, custom); + MessagingModuleConfiguration.getShared().getPrefs().setBooleanPreference(customToggle, custom); } private String getCustomValue() { - return TextSecurePreferences.getStringPreference(getContext(), customPreference, ""); + return MessagingModuleConfiguration.getShared().getPrefs().getStringPreference(customPreference, ""); } private void setCustomValue(String value) { - TextSecurePreferences.setStringPreference(getContext(), customPreference, value); + MessagingModuleConfiguration.getShared().getPrefs().setStringPreference(customPreference, value); } private String getDefaultValue() { diff --git a/app/src/main/java/org/thoughtcrime/securesms/components/camera/CameraView.java b/app/src/main/java/org/thoughtcrime/securesms/components/camera/CameraView.java index 11f6c4104b..7e067678e0 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/components/camera/CameraView.java +++ b/app/src/main/java/org/thoughtcrime/securesms/components/camera/CameraView.java @@ -32,6 +32,8 @@ import android.os.Build.VERSION; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import android.util.AttributeSet; + +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.session.libsignal.utilities.Log; import android.view.OrientationEventListener; import android.view.ViewGroup; @@ -81,7 +83,7 @@ public class CameraView extends ViewGroup { int camera = typedArray.getInt(R.styleable.CameraView_camera, -1); if (camera != -1) cameraId = camera; - else if (isMultiCamera()) cameraId = TextSecurePreferences.getDirectCaptureCameraId(context); + else if (isMultiCamera()) cameraId = MessagingModuleConfiguration.getShared().getPrefs().getDirectCaptureCameraId(); typedArray.recycle(); } @@ -266,7 +268,7 @@ public class CameraView extends ViewGroup { : CameraInfo.CAMERA_FACING_BACK; onPause(); onResume(); - TextSecurePreferences.setDirectCaptureCameraId(getContext(), cameraId); + MessagingModuleConfiguration.getShared().getPrefs().setDirectCaptureCameraId(cameraId); } } diff --git a/app/src/main/java/org/thoughtcrime/securesms/components/emoji/EmojiTextView.java b/app/src/main/java/org/thoughtcrime/securesms/components/emoji/EmojiTextView.java index 4f0072cc24..199b2278d9 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/components/emoji/EmojiTextView.java +++ b/app/src/main/java/org/thoughtcrime/securesms/components/emoji/EmojiTextView.java @@ -1,7 +1,6 @@ package org.thoughtcrime.securesms.components.emoji; import android.content.Context; -import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import androidx.annotation.NonNull; import androidx.annotation.Nullable; @@ -12,9 +11,10 @@ import android.text.TextUtils; import android.util.AttributeSet; import android.util.TypedValue; import network.loki.messenger.R; + +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.thoughtcrime.securesms.components.emoji.EmojiProvider.EmojiDrawable; import org.thoughtcrime.securesms.components.emoji.parsing.EmojiParser; -import org.session.libsession.utilities.TextSecurePreferences; import org.session.libsession.utilities.Util; import org.session.libsignal.utilities.guava.Optional; @@ -171,7 +171,7 @@ public class EmojiTextView extends AppCompatTextView { } private boolean useSystemEmoji() { - return TextSecurePreferences.isSystemEmojiPreferred(getContext()); + return MessagingModuleConfiguration.getShared().getPrefs().isSystemEmojiPreferred(); } @Override diff --git a/app/src/main/java/org/thoughtcrime/securesms/contacts/ContactAccessor.java b/app/src/main/java/org/thoughtcrime/securesms/contacts/ContactAccessor.java index d560247fb9..d017c14583 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/contacts/ContactAccessor.java +++ b/app/src/main/java/org/thoughtcrime/securesms/contacts/ContactAccessor.java @@ -74,9 +74,9 @@ public class ContactAccessor { } // if (context.getString(R.string.note_to_self).toLowerCase().contains(constraint.toLowerCase()) && -// !numberList.contains(TextSecurePreferences.getLocalNumber(context))) +// !numberList.contains(MessagingModuleConfiguration.getShared().getPrefs().getLocalNumber(context))) // { -// numberList.add(TextSecurePreferences.getLocalNumber(context)); +// numberList.add(MessagingModuleConfiguration.getShared().getPrefs().getLocalNumber(context)); // } return numberList; diff --git a/app/src/main/java/org/thoughtcrime/securesms/conversation/start/home/StartConversationFragment.kt b/app/src/main/java/org/thoughtcrime/securesms/conversation/start/home/StartConversationFragment.kt index 1934c5e5bb..2be893ac76 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/conversation/start/home/StartConversationFragment.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/conversation/start/home/StartConversationFragment.kt @@ -8,7 +8,9 @@ import androidx.compose.runtime.collectAsState import androidx.fragment.app.Fragment import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.MutableStateFlow +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.utilities.TextSecurePreferences +import org.session.libsession.utilities.prefs import org.thoughtcrime.securesms.conversation.start.StartConversationDelegate import org.thoughtcrime.securesms.conversation.start.NullStartConversationDelegate import org.thoughtcrime.securesms.ui.createThemedComposeView @@ -28,7 +30,7 @@ class StartConversationHomeFragment : Fragment() { savedInstanceState: Bundle? ): View = createThemedComposeView { StartConversationScreen( - accountId = TextSecurePreferences.getLocalNumber(requireContext())!!, + accountId = requireContext().prefs.getLocalNumber()!!, delegate = delegate.collectAsState().value ) } diff --git a/app/src/main/java/org/thoughtcrime/securesms/conversation/start/invitefriend/InviteFriendFragment.kt b/app/src/main/java/org/thoughtcrime/securesms/conversation/start/invitefriend/InviteFriendFragment.kt index 4239a7a067..19ffbb3dbe 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/conversation/start/invitefriend/InviteFriendFragment.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/conversation/start/invitefriend/InviteFriendFragment.kt @@ -7,7 +7,9 @@ import android.view.ViewGroup import androidx.compose.ui.platform.LocalContext import androidx.fragment.app.Fragment import dagger.hilt.android.AndroidEntryPoint +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.utilities.TextSecurePreferences +import org.session.libsession.utilities.prefs import org.thoughtcrime.securesms.conversation.start.StartConversationDelegate import org.thoughtcrime.securesms.preferences.copyPublicKey import org.thoughtcrime.securesms.preferences.sendInvitationToUseSession @@ -22,7 +24,7 @@ class InviteFriendFragment : Fragment() { savedInstanceState: Bundle? ): View = createThemedComposeView { InviteFriend( - TextSecurePreferences.getLocalNumber(LocalContext.current)!!, + requireContext().prefs.getLocalNumber()!!, onBack = { delegate.onDialogBackPressed() }, onClose = { delegate.onDialogClosePressed() }, copyPublicKey = requireContext()::copyPublicKey, diff --git a/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/ConversationReactionOverlay.kt b/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/ConversationReactionOverlay.kt index 56c6540ed5..ee452d5716 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/ConversationReactionOverlay.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/ConversationReactionOverlay.kt @@ -30,9 +30,10 @@ import kotlinx.coroutines.flow.filter import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import network.loki.messenger.R +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.snode.SnodeAPI -import org.session.libsession.utilities.TextSecurePreferences.Companion.getLocalNumber import org.session.libsession.utilities.ThemeUtil +import org.session.libsession.utilities.prefs import org.thoughtcrime.securesms.components.emoji.EmojiImageView import org.thoughtcrime.securesms.components.emoji.RecentEmojiPageModel import org.thoughtcrime.securesms.components.menu.ActionItem @@ -514,7 +515,7 @@ class ConversationReactionOverlay : FrameLayout { private fun getOldEmoji(messageRecord: MessageRecord): String? = messageRecord.reactions - .filter { it.author == getLocalNumber(context) } + .filter { it.author == context.prefs.getLocalNumber() } .firstOrNull() ?.let(ReactionRecord::emoji) @@ -527,7 +528,7 @@ class ConversationReactionOverlay : FrameLayout { val openGroup = get(context).lokiThreadDatabase().getOpenGroupChat(message.threadId) val recipient = get(context).threadDatabase().getRecipientForThreadId(message.threadId) ?: return emptyList() - val userPublicKey = getLocalNumber(context)!! + val userPublicKey = context.prefs.getLocalNumber()!! // Select message items += ActionItem(R.attr.menu_select_icon, R.string.conversation_context__menu_select, { handleActionItemClicked(Action.SELECT) }, R.string.AccessibilityId_select) // Reply diff --git a/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/dialogs/LinkPreviewDialog.kt b/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/dialogs/LinkPreviewDialog.kt index 996dd41f94..b7ea4b344e 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/dialogs/LinkPreviewDialog.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/dialogs/LinkPreviewDialog.kt @@ -4,7 +4,9 @@ import android.app.Dialog import android.os.Bundle import androidx.fragment.app.DialogFragment import network.loki.messenger.R +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.utilities.TextSecurePreferences +import org.session.libsession.utilities.prefs import org.thoughtcrime.securesms.createSessionDialog /** Shown the first time the user inputs a URL that could generate a link preview, to @@ -19,7 +21,7 @@ class LinkPreviewDialog(private val onEnabled: () -> Unit) : DialogFragment() { } private fun enable() { - TextSecurePreferences.setLinkPreviewsEnabled(requireContext(), true) + requireContext().prefs.setLinkPreviewsEnabled(true) dismiss() onEnabled() } diff --git a/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/input_bar/InputBar.kt b/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/input_bar/InputBar.kt index 052dcb69c4..5fffa3a766 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/input_bar/InputBar.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/input_bar/InputBar.kt @@ -21,8 +21,10 @@ import androidx.core.view.isGone import androidx.core.view.isVisible import network.loki.messenger.R import network.loki.messenger.databinding.ViewInputBarBinding +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.messaging.sending_receiving.link_preview.LinkPreview import org.session.libsession.utilities.TextSecurePreferences +import org.session.libsession.utilities.prefs import org.session.libsession.utilities.recipients.Recipient import org.thoughtcrime.securesms.conversation.v2.components.LinkPreviewDraftView import org.thoughtcrime.securesms.conversation.v2.components.LinkPreviewDraftViewDelegate @@ -158,7 +160,7 @@ class InputBar : RelativeLayout, InputBarEditTextDelegate, QuoteViewDelegate, Li // Edit text binding.inputBarEditText.setOnEditorActionListener(this) - if (TextSecurePreferences.isEnterSendsEnabled(context)) { + if (context.prefs.isEnterSendsEnabled()) { binding.inputBarEditText.imeOptions = EditorInfo.IME_ACTION_SEND binding.inputBarEditText.inputType = InputType.TYPE_TEXT_FLAG_CAP_SENTENCES @@ -168,7 +170,7 @@ class InputBar : RelativeLayout, InputBarEditTextDelegate, QuoteViewDelegate, Li binding.inputBarEditText.inputType or InputType.TYPE_TEXT_FLAG_CAP_SENTENCES } - val incognitoFlag = if (TextSecurePreferences.isIncognitoKeyboardEnabled(context)) 16777216 else 0 + val incognitoFlag = if (context.prefs.isIncognitoKeyboardEnabled()) 16777216 else 0 binding.inputBarEditText.imeOptions = binding.inputBarEditText.imeOptions or incognitoFlag // Always use incognito keyboard if setting enabled binding.inputBarEditText.delegate = this } @@ -216,7 +218,7 @@ class InputBar : RelativeLayout, InputBarEditTextDelegate, QuoteViewDelegate, Li it.delegate = this binding.inputBarAdditionalContentContainer.addView(layout) val attachments = (message as? MmsMessageRecord)?.slideDeck - val sender = if (message.isOutgoing) TextSecurePreferences.getLocalNumber(context)!! else message.individualRecipient.address.serialize() + val sender = if (message.isOutgoing) context.prefs.getLocalNumber()!! else message.individualRecipient.address.serialize() it.bind(sender, message.body, attachments, thread, true, message.isOpenGroupInvitation, message.threadId, false, glide) } diff --git a/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/menus/ConversationActionModeCallback.kt b/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/menus/ConversationActionModeCallback.kt index c7862ca22e..dbd537ba1a 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/menus/ConversationActionModeCallback.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/menus/ConversationActionModeCallback.kt @@ -9,6 +9,7 @@ import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.messaging.utilities.AccountId import org.session.libsession.messaging.utilities.SodiumUtilities import org.session.libsession.utilities.TextSecurePreferences +import org.session.libsession.utilities.prefs import org.session.libsignal.utilities.IdPrefix import org.thoughtcrime.securesms.conversation.v2.ConversationAdapter import org.thoughtcrime.securesms.database.model.MediaMmsMessageRecord @@ -36,7 +37,7 @@ class ConversationActionModeCallback(private val adapter: ConversationAdapter, p val firstMessage = selectedItems.iterator().next() val openGroup = DatabaseComponent.get(context).lokiThreadDatabase().getOpenGroupChat(threadID) val thread = DatabaseComponent.get(context).threadDatabase().getRecipientForThreadId(threadID)!! - val userPublicKey = TextSecurePreferences.getLocalNumber(context)!! + val userPublicKey = context.prefs.getLocalNumber()!! val edKeyPair = MessagingModuleConfiguration.shared.getUserED25519KeyPair()!! val blindedPublicKey = openGroup?.publicKey?.let { SodiumUtilities.blindedKeyPair(it, edKeyPair)?.publicKey?.asBytes } ?.let { AccountId(IdPrefix.BLINDED, it) }?.hexString diff --git a/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/menus/ConversationMenuHelper.kt b/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/menus/ConversationMenuHelper.kt index 76c5dafd22..e687ea94f2 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/menus/ConversationMenuHelper.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/menus/ConversationMenuHelper.kt @@ -20,7 +20,7 @@ import network.loki.messenger.R import org.session.libsession.messaging.sending_receiving.MessageSender import org.session.libsession.messaging.sending_receiving.leave import org.session.libsession.utilities.GroupUtil.doubleDecodeGroupID -import org.session.libsession.utilities.TextSecurePreferences +import org.session.libsession.utilities.prefs import org.session.libsession.utilities.recipients.Recipient import org.session.libsignal.utilities.guava.Optional import org.session.libsignal.utilities.toHexString @@ -162,7 +162,7 @@ object ConversationMenuHelper { private fun call(context: Context, thread: Recipient) { - if (!TextSecurePreferences.isCallNotificationsEnabled(context)) { + if (!context.prefs.isCallNotificationsEnabled()) { context.showSessionDialog { title(R.string.ConversationActivity_call_title) text(R.string.ConversationActivity_call_prompt) @@ -271,7 +271,7 @@ object ConversationMenuHelper { val group = DatabaseComponent.get(context).groupDatabase().getGroup(thread.address.toGroupString()).orNull() val admins = group.admins - val accountID = TextSecurePreferences.getLocalNumber(context) + val accountID = context.prefs.getLocalNumber() val isCurrentUserAdmin = admins.any { it.toString() == accountID } val message = if (isCurrentUserAdmin) { "Because you are the creator of this group it will be deleted for everyone. This cannot be undone." diff --git a/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/messages/EmojiReactionsView.kt b/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/messages/EmojiReactionsView.kt index 49e4b1044f..c58294e106 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/messages/EmojiReactionsView.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/messages/EmojiReactionsView.kt @@ -13,8 +13,9 @@ import androidx.core.content.ContextCompat import com.google.android.flexbox.JustifyContent import network.loki.messenger.R import network.loki.messenger.databinding.ViewEmojiReactionsBinding -import org.session.libsession.utilities.TextSecurePreferences.Companion.getLocalNumber +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.utilities.ThemeUtil +import org.session.libsession.utilities.prefs import org.thoughtcrime.securesms.components.emoji.EmojiImageView import org.thoughtcrime.securesms.components.emoji.EmojiUtil import org.thoughtcrime.securesms.conversation.v2.ViewUtil @@ -86,7 +87,7 @@ class EmojiReactionsView : ConstraintLayout, OnTouchListener { } private fun displayReactions(threshold: Int) { - val userPublicKey = getLocalNumber(context) + val userPublicKey = context.prefs.getLocalNumber() val reactions = buildSortedReactionsList(records!!, userPublicKey, threshold) binding.layoutEmojiContainer.removeAllViews() val overflowContainer = LinearLayout(context) diff --git a/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/messages/QuoteView.kt b/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/messages/QuoteView.kt index 77565244a0..6bfa70efe9 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/messages/QuoteView.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/messages/QuoteView.kt @@ -12,9 +12,11 @@ import androidx.core.view.isVisible import dagger.hilt.android.AndroidEntryPoint import network.loki.messenger.R import network.loki.messenger.databinding.ViewQuoteBinding +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.messaging.contacts.Contact import org.session.libsession.utilities.TextSecurePreferences import org.session.libsession.utilities.getColorFromAttr +import org.session.libsession.utilities.prefs import org.session.libsession.utilities.recipients.Recipient import org.thoughtcrime.securesms.conversation.v2.utilities.MentionUtilities import org.thoughtcrime.securesms.database.SessionContactDatabase @@ -71,7 +73,7 @@ class QuoteView @JvmOverloads constructor(context: Context, attrs: AttributeSet? isOriginalMissing: Boolean, glide: GlideRequests) { // Author val author = contactDb.getContactWithAccountID(authorPublicKey) - val localNumber = TextSecurePreferences.getLocalNumber(context) + val localNumber = context.prefs.getLocalNumber() val quoteIsLocalUser = localNumber != null && authorPublicKey == localNumber val authorDisplayName = diff --git a/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/utilities/MentionUtilities.kt b/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/utilities/MentionUtilities.kt index efa4e41d54..9bbf372512 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/utilities/MentionUtilities.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/utilities/MentionUtilities.kt @@ -12,12 +12,14 @@ import android.util.Range import androidx.core.content.res.ResourcesCompat import network.loki.messenger.R import nl.komponents.kovenant.combine.Tuple2 +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.messaging.contacts.Contact import org.session.libsession.messaging.open_groups.OpenGroup import org.session.libsession.messaging.utilities.SodiumUtilities import org.session.libsession.utilities.TextSecurePreferences import org.session.libsession.utilities.ThemeUtil import org.session.libsession.utilities.getColorFromAttr +import org.session.libsession.utilities.prefs import org.thoughtcrime.securesms.dependencies.DatabaseComponent import org.thoughtcrime.securesms.util.RoundedBackgroundSpan import org.thoughtcrime.securesms.util.getAccentColor @@ -54,7 +56,7 @@ object MentionUtilities { var matcher = pattern.matcher(text) val mentions = mutableListOf, String>>() var startIndex = 0 - val userPublicKey = TextSecurePreferences.getLocalNumber(context)!! + val userPublicKey = context.prefs.getLocalNumber()!! val openGroup by lazy { DatabaseComponent.get(context).storage().getOpenGroup(threadID) } // format the mention text diff --git a/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/utilities/ResendMessageUtilities.kt b/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/utilities/ResendMessageUtilities.kt index c1d6987904..10604a76bd 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/utilities/ResendMessageUtilities.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/utilities/ResendMessageUtilities.kt @@ -10,6 +10,7 @@ import org.session.libsession.messaging.messages.visible.VisibleMessage import org.session.libsession.messaging.sending_receiving.MessageSender import org.session.libsession.messaging.utilities.UpdateMessageData import org.session.libsession.utilities.TextSecurePreferences +import org.session.libsession.utilities.prefs import org.session.libsession.utilities.recipients.Recipient import org.thoughtcrime.securesms.database.model.MessageRecord import org.thoughtcrime.securesms.database.model.MmsMessageRecord @@ -44,7 +45,7 @@ object ResendMessageUtilities { messageRecord.linkPreviews.firstOrNull()?.let { message.linkPreview = LinkPreview.from(it) } messageRecord.quote?.quoteModel?.let { message.quote = Quote.from(it)?.apply { - if (userBlindedKey != null && publicKey == TextSecurePreferences.getLocalNumber(context)) { + if (userBlindedKey != null && publicKey == context.prefs.getLocalNumber()) { publicKey = userBlindedKey } } diff --git a/app/src/main/java/org/thoughtcrime/securesms/crypto/AttachmentSecretProvider.java b/app/src/main/java/org/thoughtcrime/securesms/crypto/AttachmentSecretProvider.java index 0344551cab..0c447ac095 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/crypto/AttachmentSecretProvider.java +++ b/app/src/main/java/org/thoughtcrime/securesms/crypto/AttachmentSecretProvider.java @@ -1,11 +1,9 @@ package org.thoughtcrime.securesms.crypto; -import android.content.Context; -import android.os.Build; import androidx.annotation.NonNull; -import org.session.libsession.utilities.TextSecurePreferences; +import org.session.libsession.messaging.MessagingModuleConfiguration; import java.security.SecureRandom; @@ -19,85 +17,55 @@ public class AttachmentSecretProvider { private static AttachmentSecretProvider provider; - public static synchronized AttachmentSecretProvider getInstance(@NonNull Context context) { - if (provider == null) provider = new AttachmentSecretProvider(context.getApplicationContext()); + public static synchronized AttachmentSecretProvider getInstance() { + if (provider == null) provider = new AttachmentSecretProvider(); return provider; } - private final Context context; - private AttachmentSecret attachmentSecret; - private AttachmentSecretProvider(@NonNull Context context) { - this.context = context.getApplicationContext(); - } - public synchronized AttachmentSecret getOrCreateAttachmentSecret() { if (attachmentSecret != null) return attachmentSecret; - String unencryptedSecret = TextSecurePreferences.getAttachmentUnencryptedSecret(context); - String encryptedSecret = TextSecurePreferences.getAttachmentEncryptedSecret(context); + String unencryptedSecret = MessagingModuleConfiguration.getShared().getPrefs().getAttachmentUnencryptedSecret(); + String encryptedSecret = MessagingModuleConfiguration.getShared().getPrefs().getAttachmentEncryptedSecret(); - if (unencryptedSecret != null) attachmentSecret = getUnencryptedAttachmentSecret(context, unencryptedSecret); + if (unencryptedSecret != null) attachmentSecret = getUnencryptedAttachmentSecret(unencryptedSecret); else if (encryptedSecret != null) attachmentSecret = getEncryptedAttachmentSecret(encryptedSecret); - else attachmentSecret = createAndStoreAttachmentSecret(context); + else attachmentSecret = createAndStoreAttachmentSecret(); return attachmentSecret; } - public synchronized AttachmentSecret setClassicKey(@NonNull Context context, @NonNull byte[] classicCipherKey, @NonNull byte[] classicMacKey) { - AttachmentSecret currentSecret = getOrCreateAttachmentSecret(); - currentSecret.setClassicCipherKey(classicCipherKey); - currentSecret.setClassicMacKey(classicMacKey); - - storeAttachmentSecret(context, attachmentSecret); - - return attachmentSecret; - } - - private AttachmentSecret getUnencryptedAttachmentSecret(@NonNull Context context, @NonNull String unencryptedSecret) - { + private AttachmentSecret getUnencryptedAttachmentSecret(@NonNull String unencryptedSecret) { AttachmentSecret attachmentSecret = AttachmentSecret.fromString(unencryptedSecret); - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { - return attachmentSecret; - } else { KeyStoreHelper.SealedData encryptedSecret = KeyStoreHelper.seal(attachmentSecret.serialize().getBytes()); - TextSecurePreferences.setAttachmentEncryptedSecret(context, encryptedSecret.serialize()); - TextSecurePreferences.setAttachmentUnencryptedSecret(context, null); + MessagingModuleConfiguration.getShared().getPrefs().setAttachmentEncryptedSecret(encryptedSecret.serialize()); + MessagingModuleConfiguration.getShared().getPrefs().setAttachmentUnencryptedSecret(null); return attachmentSecret; - } } private AttachmentSecret getEncryptedAttachmentSecret(@NonNull String serializedEncryptedSecret) { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { - throw new AssertionError("OS downgrade not supported. KeyStore sealed data exists on platform < M!"); - } else { - KeyStoreHelper.SealedData encryptedSecret = KeyStoreHelper.SealedData.fromString(serializedEncryptedSecret); - return AttachmentSecret.fromString(new String(KeyStoreHelper.unseal(encryptedSecret))); - } + KeyStoreHelper.SealedData encryptedSecret = KeyStoreHelper.SealedData.fromString(serializedEncryptedSecret); + return AttachmentSecret.fromString(new String(KeyStoreHelper.unseal(encryptedSecret))); } - private AttachmentSecret createAndStoreAttachmentSecret(@NonNull Context context) { + private AttachmentSecret createAndStoreAttachmentSecret() { SecureRandom random = new SecureRandom(); byte[] secret = new byte[32]; random.nextBytes(secret); AttachmentSecret attachmentSecret = new AttachmentSecret(null, null, secret); - storeAttachmentSecret(context, attachmentSecret); + storeAttachmentSecret(attachmentSecret); return attachmentSecret; } - private void storeAttachmentSecret(@NonNull Context context, @NonNull AttachmentSecret attachmentSecret) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + private void storeAttachmentSecret(@NonNull AttachmentSecret attachmentSecret) { KeyStoreHelper.SealedData encryptedSecret = KeyStoreHelper.seal(attachmentSecret.serialize().getBytes()); - TextSecurePreferences.setAttachmentEncryptedSecret(context, encryptedSecret.serialize()); - } else { - TextSecurePreferences.setAttachmentUnencryptedSecret(context, attachmentSecret.serialize()); - } + MessagingModuleConfiguration.getShared().getPrefs().setAttachmentEncryptedSecret(encryptedSecret.serialize()); } - } diff --git a/app/src/main/java/org/thoughtcrime/securesms/crypto/BiometricSecretProvider.kt b/app/src/main/java/org/thoughtcrime/securesms/crypto/BiometricSecretProvider.kt index ac12a69bbe..44232ba035 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/crypto/BiometricSecretProvider.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/crypto/BiometricSecretProvider.kt @@ -4,8 +4,10 @@ import android.content.Context import android.os.Build import android.security.keystore.KeyGenParameterSpec import android.security.keystore.KeyProperties +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.utilities.TextSecurePreferences import org.session.libsession.utilities.Util +import org.session.libsession.utilities.prefs import java.security.InvalidKeyException import java.security.KeyPairGenerator import java.security.KeyStore @@ -54,10 +56,10 @@ class BiometricSecretProvider { ks.load(null) if (!ks.containsAlias(BIOMETRIC_ASYM_KEY_ALIAS) || !ks.entryInstanceOf(BIOMETRIC_ASYM_KEY_ALIAS, KeyStore.PrivateKeyEntry::class.java) - || !TextSecurePreferences.getFingerprintKeyGenerated(context) + || !context.prefs.getFingerprintKeyGenerated() ) { createAsymmetricKey(context) - TextSecurePreferences.setFingerprintKeyGenerated(context) + context.prefs.setFingerprintKeyGenerated() } val signature = try { val key = ks.getKey(BIOMETRIC_ASYM_KEY_ALIAS, null) as PrivateKey @@ -67,7 +69,7 @@ class BiometricSecretProvider { } catch (e: InvalidKeyException) { ks.deleteEntry(BIOMETRIC_ASYM_KEY_ALIAS) createAsymmetricKey(context) - TextSecurePreferences.setFingerprintKeyGenerated(context) + context.prefs.setFingerprintKeyGenerated() val key = ks.getKey(BIOMETRIC_ASYM_KEY_ALIAS, null) as PrivateKey val signature = Signature.getInstance(SIGNATURE_ALGORITHM) signature.initSign(key) diff --git a/app/src/main/java/org/thoughtcrime/securesms/crypto/DatabaseSecretProvider.java b/app/src/main/java/org/thoughtcrime/securesms/crypto/DatabaseSecretProvider.java index 0ad22c3a90..c18808d3af 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/crypto/DatabaseSecretProvider.java +++ b/app/src/main/java/org/thoughtcrime/securesms/crypto/DatabaseSecretProvider.java @@ -1,10 +1,8 @@ package org.thoughtcrime.securesms.crypto; - -import android.content.Context; -import android.os.Build; import androidx.annotation.NonNull; +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.session.libsession.utilities.TextSecurePreferences; import java.io.IOException; @@ -15,63 +13,51 @@ public class DatabaseSecretProvider { @SuppressWarnings("unused") private static final String TAG = DatabaseSecretProvider.class.getSimpleName(); - private final Context context; + private final TextSecurePreferences prefs; - public DatabaseSecretProvider(@NonNull Context context) { - this.context = context.getApplicationContext(); + public DatabaseSecretProvider(@NonNull TextSecurePreferences prefs) { + this.prefs = prefs; } public DatabaseSecret getOrCreateDatabaseSecret() { - String unencryptedSecret = TextSecurePreferences.getDatabaseUnencryptedSecret(context); - String encryptedSecret = TextSecurePreferences.getDatabaseEncryptedSecret(context); + String unencryptedSecret = prefs.getDatabaseUnencryptedSecret(); + String encryptedSecret = prefs.getDatabaseEncryptedSecret(); - if (unencryptedSecret != null) return getUnencryptedDatabaseSecret(context, unencryptedSecret); + if (unencryptedSecret != null) return getUnencryptedDatabaseSecret(unencryptedSecret); else if (encryptedSecret != null) return getEncryptedDatabaseSecret(encryptedSecret); - else return createAndStoreDatabaseSecret(context); + else return createAndStoreDatabaseSecret(); } - private DatabaseSecret getUnencryptedDatabaseSecret(@NonNull Context context, @NonNull String unencryptedSecret) + private DatabaseSecret getUnencryptedDatabaseSecret(@NonNull String unencryptedSecret) { try { DatabaseSecret databaseSecret = new DatabaseSecret(unencryptedSecret); - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { - return databaseSecret; - } else { - KeyStoreHelper.SealedData encryptedSecret = KeyStoreHelper.seal(databaseSecret.asBytes()); + KeyStoreHelper.SealedData encryptedSecret = KeyStoreHelper.seal(databaseSecret.asBytes()); - TextSecurePreferences.setDatabaseEncryptedSecret(context, encryptedSecret.serialize()); - TextSecurePreferences.setDatabaseUnencryptedSecret(context, null); + prefs.setDatabaseEncryptedSecret(encryptedSecret.serialize()); + prefs.setDatabaseUnencryptedSecret(null); - return databaseSecret; - } + return databaseSecret; } catch (IOException e) { throw new AssertionError(e); } } private DatabaseSecret getEncryptedDatabaseSecret(@NonNull String serializedEncryptedSecret) { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { - throw new AssertionError("OS downgrade not supported. KeyStore sealed data exists on platform < M!"); - } else { - KeyStoreHelper.SealedData encryptedSecret = KeyStoreHelper.SealedData.fromString(serializedEncryptedSecret); - return new DatabaseSecret(KeyStoreHelper.unseal(encryptedSecret)); - } + KeyStoreHelper.SealedData encryptedSecret = KeyStoreHelper.SealedData.fromString(serializedEncryptedSecret); + return new DatabaseSecret(KeyStoreHelper.unseal(encryptedSecret)); } - private DatabaseSecret createAndStoreDatabaseSecret(@NonNull Context context) { + private DatabaseSecret createAndStoreDatabaseSecret() { SecureRandom random = new SecureRandom(); byte[] secret = new byte[32]; random.nextBytes(secret); DatabaseSecret databaseSecret = new DatabaseSecret(secret); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - KeyStoreHelper.SealedData encryptedSecret = KeyStoreHelper.seal(databaseSecret.asBytes()); - TextSecurePreferences.setDatabaseEncryptedSecret(context, encryptedSecret.serialize()); - } else { - TextSecurePreferences.setDatabaseUnencryptedSecret(context, databaseSecret.asString()); - } + KeyStoreHelper.SealedData encryptedSecret = KeyStoreHelper.seal(databaseSecret.asBytes()); + prefs.setDatabaseEncryptedSecret(encryptedSecret.serialize()); return databaseSecret; } diff --git a/app/src/main/java/org/thoughtcrime/securesms/database/GroupDatabase.java b/app/src/main/java/org/thoughtcrime/securesms/database/GroupDatabase.java index 66d01114ef..903432a72c 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/database/GroupDatabase.java +++ b/app/src/main/java/org/thoughtcrime/securesms/database/GroupDatabase.java @@ -14,6 +14,7 @@ import com.annimon.stream.Stream; import net.zetetic.database.sqlcipher.SQLiteDatabase; import org.jetbrains.annotations.NotNull; +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.session.libsession.utilities.Address; import org.session.libsession.utilities.GroupRecord; import org.session.libsession.utilities.TextSecurePreferences; @@ -172,7 +173,7 @@ public class GroupDatabase extends Database implements LokiOpenGroupDatabaseProt List recipients = new LinkedList<>(); for (Address member : members) { - if (!includeSelf && Util.isOwnNumber(context, member.serialize())) + if (!includeSelf && Util.isOwnNumber(member.serialize())) continue; if (member.isContact()) { @@ -186,7 +187,7 @@ public class GroupDatabase extends Database implements LokiOpenGroupDatabaseProt public @NonNull List
getGroupMemberAddresses(String groupId, boolean includeSelf) { List
members = getCurrentMembers(groupId, false); if (!includeSelf) { - String ownNumber = TextSecurePreferences.getLocalNumber(context); + String ownNumber = MessagingModuleConfiguration.getShared().getPrefs().getLocalNumber(); if (ownNumber == null) return members; Address ownAddress = Address.fromSerialized(ownNumber); int indexOfSelf = members.indexOf(ownAddress); diff --git a/app/src/main/java/org/thoughtcrime/securesms/database/LokiAPIDatabase.kt b/app/src/main/java/org/thoughtcrime/securesms/database/LokiAPIDatabase.kt index f60c53bbe3..8c58abcaa1 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/database/LokiAPIDatabase.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/database/LokiAPIDatabase.kt @@ -2,7 +2,9 @@ package org.thoughtcrime.securesms.database import android.content.ContentValues import android.content.Context +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.utilities.TextSecurePreferences +import org.session.libsession.utilities.prefs import org.session.libsignal.crypto.ecc.DjbECPrivateKey import org.session.libsignal.crypto.ecc.DjbECPublicKey import org.session.libsignal.crypto.ecc.ECKeyPair @@ -479,13 +481,13 @@ class LokiAPIDatabase(context: Context, helper: SQLCipherOpenHelper) : Database( } override fun getLastSnodePoolRefreshDate(): Date? { - val time = TextSecurePreferences.getLastSnodePoolRefreshDate(context) + val time = context.prefs.getLastSnodePoolRefreshDate() if (time <= 0) { return null } return Date(time) } override fun setLastSnodePoolRefreshDate(date: Date) { - TextSecurePreferences.setLastSnodePoolRefreshDate(context, date) + context.prefs.setLastSnodePoolRefreshDate(date) } override fun getUserX25519KeyPair(): ECKeyPair { diff --git a/app/src/main/java/org/thoughtcrime/securesms/database/LokiUserDatabase.kt b/app/src/main/java/org/thoughtcrime/securesms/database/LokiUserDatabase.kt index 4a5468c5d4..07939e5836 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/database/LokiUserDatabase.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/database/LokiUserDatabase.kt @@ -1,8 +1,10 @@ package org.thoughtcrime.securesms.database import android.content.Context +import org.session.libsession.messaging.MessagingModuleConfiguration import org.thoughtcrime.securesms.database.helpers.SQLCipherOpenHelper import org.session.libsession.utilities.TextSecurePreferences +import org.session.libsession.utilities.prefs class LokiUserDatabase(context: Context, helper: SQLCipherOpenHelper) : Database(context, helper) { @@ -20,8 +22,8 @@ class LokiUserDatabase(context: Context, helper: SQLCipherOpenHelper) : Database } fun getDisplayName(publicKey: String): String? { - if (publicKey == TextSecurePreferences.getLocalNumber(context)) { - return TextSecurePreferences.getProfileName(context) + if (publicKey == context.prefs.getLocalNumber()) { + return context.prefs.getProfileName() } else { val database = databaseHelper.readableDatabase val result = database.get(displayNameTable, "${Companion.publicKey} = ?", arrayOf( publicKey )) { cursor -> diff --git a/app/src/main/java/org/thoughtcrime/securesms/database/MessagingDatabase.java b/app/src/main/java/org/thoughtcrime/securesms/database/MessagingDatabase.java index bc74496dda..f6773dfffd 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/database/MessagingDatabase.java +++ b/app/src/main/java/org/thoughtcrime/securesms/database/MessagingDatabase.java @@ -14,7 +14,6 @@ import org.session.libsession.utilities.IdentityKeyMismatchList; import org.session.libsignal.crypto.IdentityKey; import org.session.libsignal.utilities.JsonUtil; import org.session.libsignal.utilities.Log; -import org.thoughtcrime.securesms.conversation.disappearingmessages.ExpiryType; import org.thoughtcrime.securesms.database.helpers.SQLCipherOpenHelper; import org.thoughtcrime.securesms.database.model.MessageRecord; import org.thoughtcrime.securesms.util.SqlUtil; diff --git a/app/src/main/java/org/thoughtcrime/securesms/database/MmsDatabase.kt b/app/src/main/java/org/thoughtcrime/securesms/database/MmsDatabase.kt index 23a1af7ceb..39b602825a 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/database/MmsDatabase.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/database/MmsDatabase.kt @@ -25,6 +25,7 @@ import org.apache.commons.lang3.StringUtils import org.json.JSONArray import org.json.JSONException import org.json.JSONObject +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.messaging.messages.ExpirationConfiguration import org.session.libsession.messaging.messages.signal.IncomingMediaMessage import org.session.libsession.messaging.messages.signal.OutgoingGroupMediaMessage @@ -45,8 +46,8 @@ import org.session.libsession.utilities.IdentityKeyMismatch import org.session.libsession.utilities.IdentityKeyMismatchList import org.session.libsession.utilities.NetworkFailure import org.session.libsession.utilities.NetworkFailureList -import org.session.libsession.utilities.TextSecurePreferences.Companion.isReadReceiptsEnabled import org.session.libsession.utilities.Util.toIsoBytes +import org.session.libsession.utilities.prefs import org.session.libsession.utilities.recipients.Recipient import org.session.libsignal.utilities.JsonUtil import org.session.libsignal.utilities.Log @@ -1264,7 +1265,7 @@ class MmsDatabase(context: Context, databaseHelper: SQLCipherOpenHelper) : Messa DELIVERY_RECEIPT_COUNT ) ) - val readReceiptCount = if (isReadReceiptsEnabled(context)) cursor.getInt(cursor.getColumnIndexOrThrow(READ_RECEIPT_COUNT)) else 0 + val readReceiptCount = if (context.prefs.isReadReceiptsEnabled()) cursor.getInt(cursor.getColumnIndexOrThrow(READ_RECEIPT_COUNT)) else 0 val hasMention = (cursor.getInt(cursor.getColumnIndexOrThrow(HAS_MENTION)) == 1) val contentLocationBytes: ByteArray? = contentLocation?.takeUnless { it.isEmpty() }?.let(::toIsoBytes) val transactionIdBytes: ByteArray? = transactionId?.takeUnless { it.isEmpty() }?.let(::toIsoBytes) @@ -1309,7 +1310,7 @@ class MmsDatabase(context: Context, databaseHelper: SQLCipherOpenHelper) : Messa val expireStarted = cursor.getLong(cursor.getColumnIndexOrThrow(EXPIRE_STARTED)) val unidentified = cursor.getInt(cursor.getColumnIndexOrThrow(UNIDENTIFIED)) == 1 val hasMention = cursor.getInt(cursor.getColumnIndexOrThrow(HAS_MENTION)) == 1 - if (!isReadReceiptsEnabled(context)) { + if (!context.prefs.isReadReceiptsEnabled()) { readReceiptCount = 0 } val recipient = getRecipientFor(address) diff --git a/app/src/main/java/org/thoughtcrime/securesms/database/MmsSmsDatabase.java b/app/src/main/java/org/thoughtcrime/securesms/database/MmsSmsDatabase.java index b737be855e..942f798901 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/database/MmsSmsDatabase.java +++ b/app/src/main/java/org/thoughtcrime/securesms/database/MmsSmsDatabase.java @@ -106,7 +106,7 @@ public class MmsSmsDatabase extends Database { MmsSmsDatabase.Reader reader = readerFor(cursor, getQuote); MessageRecord messageRecord; - boolean isOwnNumber = Util.isOwnNumber(context, serializedAuthor); + boolean isOwnNumber = Util.isOwnNumber(serializedAuthor); while ((messageRecord = reader.getNext()) != null) { if ((isOwnNumber && messageRecord.isOutgoing()) || @@ -122,7 +122,7 @@ public class MmsSmsDatabase extends Database { public @Nullable MessageRecord getSentMessageFor(long timestamp, String serializedAuthor) { // Early exit if the author is not us - boolean isOwnNumber = Util.isOwnNumber(context, serializedAuthor); + boolean isOwnNumber = Util.isOwnNumber(serializedAuthor); if (!isOwnNumber) { Log.i(TAG, "Asked to find sent messages but provided author is not us - returning null."); return null; @@ -145,7 +145,7 @@ public class MmsSmsDatabase extends Database { public MessageRecord getLastSentMessageRecordFromSender(long threadId, String serializedAuthor) { // Early exit if the author is not us - boolean isOwnNumber = Util.isOwnNumber(context, serializedAuthor); + boolean isOwnNumber = Util.isOwnNumber(serializedAuthor); if (!isOwnNumber) { Log.i(TAG, "Asked to find last sent message but provided author is not us - returning null."); return null; @@ -375,7 +375,7 @@ public class MmsSmsDatabase extends Database { try (Cursor cursor = queryTables(new String[]{ MmsSmsColumns.NORMALIZED_DATE_SENT, MmsSmsColumns.ADDRESS }, selection, order, null)) { String serializedAddress = address.serialize(); - boolean isOwnNumber = Util.isOwnNumber(context, address.serialize()); + boolean isOwnNumber = Util.isOwnNumber(address.serialize()); while (cursor != null && cursor.moveToNext()) { boolean quoteIdMatches = cursor.getLong(0) == quoteId; @@ -395,7 +395,7 @@ public class MmsSmsDatabase extends Database { try (Cursor cursor = queryTables(new String[]{ MmsSmsColumns.NORMALIZED_DATE_SENT, MmsSmsColumns.ADDRESS }, selection, order, null)) { String serializedAddress = address.serialize(); - boolean isOwnNumber = Util.isOwnNumber(context, address.serialize()); + boolean isOwnNumber = Util.isOwnNumber(address.serialize()); while (cursor != null && cursor.moveToNext()) { boolean timestampMatches = cursor.getLong(0) == sentTimestamp; diff --git a/app/src/main/java/org/thoughtcrime/securesms/database/SmsDatabase.java b/app/src/main/java/org/thoughtcrime/securesms/database/SmsDatabase.java index 84b9441834..b4a4f7d7d6 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/database/SmsDatabase.java +++ b/app/src/main/java/org/thoughtcrime/securesms/database/SmsDatabase.java @@ -28,6 +28,7 @@ import com.annimon.stream.Stream; import net.zetetic.database.sqlcipher.SQLiteDatabase; import net.zetetic.database.sqlcipher.SQLiteStatement; import org.apache.commons.lang3.StringUtils; +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.session.libsession.messaging.calls.CallMessageType; import org.session.libsession.messaging.messages.signal.IncomingGroupMessage; import org.session.libsession.messaging.messages.signal.IncomingTextMessage; @@ -837,7 +838,7 @@ public class SmsDatabase extends MessagingDatabase { boolean unidentified = cursor.getInt(cursor.getColumnIndexOrThrow(SmsDatabase.UNIDENTIFIED)) == 1; boolean hasMention = cursor.getInt(cursor.getColumnIndexOrThrow(SmsDatabase.HAS_MENTION)) == 1; - if (!TextSecurePreferences.isReadReceiptsEnabled(context)) { + if (!MessagingModuleConfiguration.getShared().getPrefs().isReadReceiptsEnabled()) { readReceiptCount = 0; } diff --git a/app/src/main/java/org/thoughtcrime/securesms/database/Storage.kt b/app/src/main/java/org/thoughtcrime/securesms/database/Storage.kt index a9b238126f..60ff542271 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/database/Storage.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/database/Storage.kt @@ -18,6 +18,7 @@ import network.loki.messenger.libsession_util.util.afterSend import org.session.libsession.avatars.AvatarHelper import org.session.libsession.database.StorageProtocol import org.session.libsession.messaging.BlindedIdMapping +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.messaging.calls.CallMessageType import org.session.libsession.messaging.contacts.Contact import org.session.libsession.messaging.jobs.AttachmentUploadJob @@ -68,6 +69,7 @@ import org.session.libsession.utilities.ProfileKeyUtil import org.session.libsession.utilities.SSKEnvironment import org.session.libsession.utilities.SSKEnvironment.ProfileManagerProtocol.Companion.NAME_PADDED_LENGTH import org.session.libsession.utilities.TextSecurePreferences +import org.session.libsession.utilities.prefs import org.session.libsession.utilities.recipients.Recipient import org.session.libsession.utilities.recipients.Recipient.DisappearingState import org.session.libsignal.crypto.ecc.DjbECPrivateKey @@ -174,7 +176,7 @@ open class Storage( } override fun getUserPublicKey(): String? { - return TextSecurePreferences.getLocalNumber(context) + return context.prefs.getLocalNumber() } override fun getUserX25519KeyPair(): ECKeyPair { @@ -182,9 +184,9 @@ open class Storage( } override fun getUserProfile(): Profile { - val displayName = TextSecurePreferences.getProfileName(context) + val displayName = context.prefs.getProfileName() val profileKey = ProfileKeyUtil.getProfileKey(context) - val profilePictureUrl = TextSecurePreferences.getProfilePictureURL(context) + val profilePictureUrl = context.prefs.getProfilePictureURL() return Profile(displayName, profileKey, profilePictureUrl) } @@ -209,8 +211,8 @@ open class Storage( Recipient.from(context, it, false) } ourRecipient.resolve().profileKey = newProfileKey - TextSecurePreferences.setProfileKey(context, newProfileKey?.let { Base64.encodeBytes(it) }) - TextSecurePreferences.setProfilePictureURL(context, newProfilePicture) + context.prefs.setProfileKey(newProfileKey?.let { Base64.encodeBytes(it) }) + context.prefs.setProfilePictureURL(newProfilePicture) if (newProfileKey != null) { JobQueue.shared.add(RetrieveProfileAvatarJob(newProfilePicture, ourRecipient.address)) @@ -218,10 +220,10 @@ open class Storage( } override fun getOrGenerateRegistrationID(): Int { - var registrationID = TextSecurePreferences.getLocalRegistrationId(context) + var registrationID = context.prefs.getLocalRegistrationId() if (registrationID == 0) { registrationID = KeyHelper.generateRegistrationId(false) - TextSecurePreferences.setLocalRegistrationId(context, registrationID) + context.prefs.setLocalRegistrationId(registrationID) } return registrationID } @@ -478,7 +480,7 @@ open class Storage( val profileManager = SSKEnvironment.shared.profileManager name.takeUnless { it.isEmpty() }?.truncate(NAME_PADDED_LENGTH)?.let { - TextSecurePreferences.setProfileName(context, it) + context.prefs.setProfileName(it) profileManager.setName(context, recipient, it) if (it != name) userProfile.setName(it) } @@ -487,7 +489,7 @@ open class Storage( if (userPic == UserPic.DEFAULT) { clearUserPic() } else if (userPic.key.isNotEmpty() && userPic.url.isNotEmpty() - && TextSecurePreferences.getProfilePictureURL(context) != userPic.url) { + && context.prefs.getProfilePictureURL() != userPic.url) { setUserProfilePicture(userPic.url, userPic.key) } if (userProfile.getNtsPriority() == PRIORITY_HIDDEN) { @@ -523,11 +525,11 @@ open class Storage( // would love to get rid of recipient and context from this val recipient = Recipient.from(context, fromSerialized(userPublicKey), false) // clear picture if userPic is null - TextSecurePreferences.setProfileKey(context, null) + context.prefs.setProfileKey(null) ProfileKeyUtil.setEncodedProfileKey(context, null) recipientDatabase.setProfileAvatar(recipient, null) - TextSecurePreferences.setProfileAvatarId(context, 0) - TextSecurePreferences.setProfilePictureURL(context, null) + context.prefs.setProfileAvatarId(0) + context.prefs.setProfilePictureURL(null) Recipient.removeCached(fromSerialized(userPublicKey)) configFactory.user?.setPic(UserPic.DEFAULT) @@ -786,7 +788,7 @@ open class Storage( // message timestamp and as such we cannot use that to identify the local message. override fun markAsSentToCommunity(threadId: Long, messageID: Long) { val database = DatabaseComponent.get(context).mmsSmsDatabase() - val message = database.getLastSentMessageRecordFromSender(threadId, TextSecurePreferences.getLocalNumber(context)) + val message = database.getLastSentMessageRecordFromSender(threadId, context.prefs.getLocalNumber()) // Ensure we can find the local message.. if (message == null) { @@ -851,7 +853,7 @@ open class Storage( // modifies the message timestamp and as such we cannot use that to identify the local message. override fun markUnidentifiedInCommunity(threadId: Long, messageId: Long) { val database = DatabaseComponent.get(context).mmsSmsDatabase() - val message = database.getLastSentMessageRecordFromSender(threadId, TextSecurePreferences.getLocalNumber(context)) + val message = database.getLastSentMessageRecordFromSender(threadId, context.prefs.getLocalNumber()) // Check to ensure the message exists if (message == null) { diff --git a/app/src/main/java/org/thoughtcrime/securesms/database/ThreadDatabase.java b/app/src/main/java/org/thoughtcrime/securesms/database/ThreadDatabase.java index f5c6da5fb9..6b50d61aef 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/database/ThreadDatabase.java +++ b/app/src/main/java/org/thoughtcrime/securesms/database/ThreadDatabase.java @@ -31,6 +31,7 @@ import androidx.annotation.Nullable; import com.annimon.stream.Stream; import net.zetetic.database.sqlcipher.SQLiteDatabase; import org.jetbrains.annotations.NotNull; +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.session.libsession.snode.SnodeAPI; import org.session.libsession.utilities.Address; import org.session.libsession.utilities.Contact; @@ -924,7 +925,7 @@ public class ThreadDatabase extends Database { Uri snippetUri = getSnippetUri(cursor); boolean pinned = cursor.getInt(cursor.getColumnIndexOrThrow(ThreadDatabase.IS_PINNED)) != 0; - if (!TextSecurePreferences.isReadReceiptsEnabled(context)) { + if (!MessagingModuleConfiguration.getShared().getPrefs().isReadReceiptsEnabled()) { readReceiptCount = 0; } diff --git a/app/src/main/java/org/thoughtcrime/securesms/database/helpers/SQLCipherOpenHelper.java b/app/src/main/java/org/thoughtcrime/securesms/database/helpers/SQLCipherOpenHelper.java index cd1988e83f..9cee14ca30 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/database/helpers/SQLCipherOpenHelper.java +++ b/app/src/main/java/org/thoughtcrime/securesms/database/helpers/SQLCipherOpenHelper.java @@ -13,6 +13,7 @@ import net.zetetic.database.sqlcipher.SQLiteDatabase; import net.zetetic.database.sqlcipher.SQLiteDatabaseHook; import net.zetetic.database.sqlcipher.SQLiteOpenHelper; +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.session.libsession.utilities.TextSecurePreferences; import org.session.libsignal.utilities.Log; import org.thoughtcrime.securesms.crypto.DatabaseSecret; @@ -125,9 +126,9 @@ public class SQLCipherOpenHelper extends SQLiteOpenHelper { // if not vacuumed in a while, perform that operation long currentTime = System.currentTimeMillis(); // 7 days - if (currentTime - TextSecurePreferences.getLastVacuumTime(context) > 604_800_000) { + if (currentTime - MessagingModuleConfiguration.getShared().getPrefs().getLastVacuumTime() > 604_800_000) { connection.execute("VACUUM;", null, null); - TextSecurePreferences.setLastVacuumNow(context); + MessagingModuleConfiguration.getShared().getPrefs().setLastVacuumNow(); } } }, diff --git a/app/src/main/java/org/thoughtcrime/securesms/dependencies/AppModule.kt b/app/src/main/java/org/thoughtcrime/securesms/dependencies/AppModule.kt index dd35843ef3..bc758ee75d 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/dependencies/AppModule.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/dependencies/AppModule.kt @@ -13,6 +13,7 @@ import org.thoughtcrime.securesms.repository.DefaultConversationRepository @InstallIn(SingletonComponent::class) abstract class AppModule { + @Binds abstract fun bindConversationRepository(repository: DefaultConversationRepository): ConversationRepository } diff --git a/app/src/main/java/org/thoughtcrime/securesms/dependencies/ConfigFactory.kt b/app/src/main/java/org/thoughtcrime/securesms/dependencies/ConfigFactory.kt index 505a7939a8..be70c88a7b 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/dependencies/ConfigFactory.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/dependencies/ConfigFactory.kt @@ -7,9 +7,11 @@ import network.loki.messenger.libsession_util.Contacts import network.loki.messenger.libsession_util.ConversationVolatileConfig import network.loki.messenger.libsession_util.UserGroupsConfig import network.loki.messenger.libsession_util.UserProfile +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.utilities.ConfigFactoryProtocol import org.session.libsession.utilities.ConfigFactoryUpdateListener import org.session.libsession.utilities.TextSecurePreferences +import org.session.libsession.utilities.prefs import org.session.libsignal.protos.SignalServiceProtos.SharedConfigMessage import org.session.libsignal.utilities.Log import org.thoughtcrime.securesms.database.ConfigDatabase @@ -49,7 +51,7 @@ class ConfigFactory( private val userGroupsLock = Object() private var _userGroups: UserGroupsConfig? = null - private val isConfigForcedOn by lazy { TextSecurePreferences.hasForcedNewConfig(context) } + private val isConfigForcedOn by lazy { context.prefs.hasForcedNewConfig() } private val listeners: MutableList = mutableListOf() fun registerListener(listener: ConfigFactoryUpdateListener) { diff --git a/app/src/main/java/org/thoughtcrime/securesms/dependencies/DatabaseModule.kt b/app/src/main/java/org/thoughtcrime/securesms/dependencies/DatabaseModule.kt index 30fb40d89a..d2fd372b93 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/dependencies/DatabaseModule.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/dependencies/DatabaseModule.kt @@ -8,6 +8,7 @@ import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import org.session.libsession.database.MessageDataProvider import org.session.libsession.utilities.SSKEnvironment +import org.session.libsession.utilities.TextSecurePreferences import org.thoughtcrime.securesms.attachments.DatabaseAttachmentProvider import org.thoughtcrime.securesms.crypto.AttachmentSecret import org.thoughtcrime.securesms.crypto.AttachmentSecretProvider @@ -32,12 +33,12 @@ object DatabaseModule { @Provides @Singleton - fun provideAttachmentSecret(@ApplicationContext context: Context) = AttachmentSecretProvider.getInstance(context).orCreateAttachmentSecret + fun provideAttachmentSecret(@ApplicationContext context: Context) = AttachmentSecretProvider.getInstance().orCreateAttachmentSecret @Provides @Singleton - fun provideOpenHelper(@ApplicationContext context: Context): SQLCipherOpenHelper { - val dbSecret = DatabaseSecretProvider(context).orCreateDatabaseSecret + fun provideOpenHelper(@ApplicationContext context: Context, prefs: TextSecurePreferences): SQLCipherOpenHelper { + val dbSecret = DatabaseSecretProvider(prefs).orCreateDatabaseSecret SQLCipherOpenHelper.migrateSqlCipher3To4IfNeeded(context, dbSecret) return SQLCipherOpenHelper(context, dbSecret) } diff --git a/app/src/main/java/org/thoughtcrime/securesms/dependencies/SessionUtilModule.kt b/app/src/main/java/org/thoughtcrime/securesms/dependencies/SessionUtilModule.kt index cd4b071338..bc8133fad5 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/dependencies/SessionUtilModule.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/dependencies/SessionUtilModule.kt @@ -6,8 +6,10 @@ import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.utilities.ConfigFactoryUpdateListener import org.session.libsession.utilities.TextSecurePreferences +import org.session.libsession.utilities.prefs import org.thoughtcrime.securesms.crypto.KeyPairUtilities import org.thoughtcrime.securesms.database.ConfigDatabase import javax.inject.Singleton @@ -25,7 +27,7 @@ object SessionUtilModule { @Singleton fun provideConfigFactory(@ApplicationContext context: Context, configDatabase: ConfigDatabase): ConfigFactory = ConfigFactory(context, configDatabase) { - val localUserPublicKey = TextSecurePreferences.getLocalNumber(context) + val localUserPublicKey = context.prefs.getLocalNumber() val secretKey = maybeUserEdSecretKey(context) if (localUserPublicKey == null || secretKey == null) null else secretKey to localUserPublicKey diff --git a/app/src/main/java/org/thoughtcrime/securesms/giph/ui/GiphyActivity.java b/app/src/main/java/org/thoughtcrime/securesms/giph/ui/GiphyActivity.java index dcfdb66112..c93afa01b0 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/giph/ui/GiphyActivity.java +++ b/app/src/main/java/org/thoughtcrime/securesms/giph/ui/GiphyActivity.java @@ -18,6 +18,7 @@ import androidx.viewpager.widget.ViewPager; import com.google.android.material.tabs.TabLayout; +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.session.libsession.utilities.MediaTypes; import org.thoughtcrime.securesms.PassphraseRequiredActionBarActivity; import org.session.libsignal.utilities.Log; @@ -59,7 +60,7 @@ public class GiphyActivity extends PassphraseRequiredActionBarActivity GiphyActivityToolbar toolbar = ViewUtil.findById(this, R.id.giphy_toolbar); toolbar.setOnFilterChangedListener(this); toolbar.setOnLayoutChangedListener(this); - toolbar.setPersistence(GiphyActivityToolbarTextSecurePreferencesPersistence.fromContext(this)); + toolbar.setPersistence(new GiphyActivityToolbarTextSecurePreferencesPersistence()); setSupportActionBar(toolbar); diff --git a/app/src/main/java/org/thoughtcrime/securesms/giph/ui/GiphyActivityToolbarTextSecurePreferencesPersistence.java b/app/src/main/java/org/thoughtcrime/securesms/giph/ui/GiphyActivityToolbarTextSecurePreferencesPersistence.java deleted file mode 100644 index 3147590d6a..0000000000 --- a/app/src/main/java/org/thoughtcrime/securesms/giph/ui/GiphyActivityToolbarTextSecurePreferencesPersistence.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.thoughtcrime.securesms.giph.ui; - -import android.content.Context; - -import org.session.libsession.utilities.TextSecurePreferences; - -class GiphyActivityToolbarTextSecurePreferencesPersistence implements GiphyActivityToolbar.Persistence { - - static GiphyActivityToolbar.Persistence fromContext(Context context) { - return new GiphyActivityToolbarTextSecurePreferencesPersistence(context.getApplicationContext()); - } - - private final Context context; - - private GiphyActivityToolbarTextSecurePreferencesPersistence(Context context) { - this.context = context; - } - - @Override - public boolean getGridSelected() { - return TextSecurePreferences.isGifSearchInGridLayout(context); - } - - @Override - public void setGridSelected(boolean isGridSelected) { - TextSecurePreferences.setIsGifSearchInGridLayout(context, isGridSelected); - } -} diff --git a/app/src/main/java/org/thoughtcrime/securesms/giph/ui/GiphyActivityToolbarTextSecurePreferencesPersistence.kt b/app/src/main/java/org/thoughtcrime/securesms/giph/ui/GiphyActivityToolbarTextSecurePreferencesPersistence.kt new file mode 100644 index 0000000000..1e3c1cff44 --- /dev/null +++ b/app/src/main/java/org/thoughtcrime/securesms/giph/ui/GiphyActivityToolbarTextSecurePreferencesPersistence.kt @@ -0,0 +1,9 @@ +package org.thoughtcrime.securesms.giph.ui + +import org.session.libsession.messaging.MessagingModuleConfiguration.Companion.shared +import org.thoughtcrime.securesms.giph.ui.GiphyActivityToolbar.Persistence + +class GiphyActivityToolbarTextSecurePreferencesPersistence: Persistence { + override fun getGridSelected(): Boolean = shared.prefs.isGifSearchInGridLayout() + override fun setGridSelected(isGridSelected: Boolean) = shared.prefs.setIsGifSearchInGridLayout(isGridSelected) +} diff --git a/app/src/main/java/org/thoughtcrime/securesms/giph/ui/GiphyFragment.java b/app/src/main/java/org/thoughtcrime/securesms/giph/ui/GiphyFragment.java index 5e401c23fc..f9c35125b3 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/giph/ui/GiphyFragment.java +++ b/app/src/main/java/org/thoughtcrime/securesms/giph/ui/GiphyFragment.java @@ -16,11 +16,11 @@ import android.view.View; import android.view.ViewGroup; import android.widget.TextView; +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.thoughtcrime.securesms.giph.model.GiphyImage; import org.thoughtcrime.securesms.giph.net.GiphyLoader; import org.thoughtcrime.securesms.giph.util.InfiniteScrollListener; import org.thoughtcrime.securesms.mms.GlideApp; -import org.session.libsession.utilities.TextSecurePreferences; import org.session.libsession.utilities.ViewUtil; import java.util.LinkedList; @@ -57,7 +57,7 @@ public abstract class GiphyFragment extends Fragment implements LoaderManager.Lo this.giphyAdapter = new GiphyAdapter(getActivity(), GlideApp.with(this), new LinkedList<>()); this.giphyAdapter.setListener(this); - setLayoutManager(TextSecurePreferences.isGifSearchInGridLayout(getContext())); + setLayoutManager(MessagingModuleConfiguration.getShared().getPrefs().isGifSearchInGridLayout()); this.recyclerView.setItemAnimator(new DefaultItemAnimator()); this.recyclerView.setAdapter(giphyAdapter); this.recyclerView.addOnScrollListener(new GiphyScrollListener()); diff --git a/app/src/main/java/org/thoughtcrime/securesms/groups/CreateGroupFragment.kt b/app/src/main/java/org/thoughtcrime/securesms/groups/CreateGroupFragment.kt index 7bfea9aab0..cdfd9d9454 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/groups/CreateGroupFragment.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/groups/CreateGroupFragment.kt @@ -18,11 +18,13 @@ import network.loki.messenger.R import network.loki.messenger.databinding.FragmentCreateGroupBinding import nl.komponents.kovenant.ui.failUi import nl.komponents.kovenant.ui.successUi +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.messaging.sending_receiving.MessageSender import org.session.libsession.messaging.sending_receiving.groupSizeLimit import org.session.libsession.utilities.Address import org.session.libsession.utilities.Device import org.session.libsession.utilities.TextSecurePreferences +import org.session.libsession.utilities.prefs import org.session.libsession.utilities.recipients.Recipient import org.thoughtcrime.securesms.contacts.SelectContactsAdapter import org.thoughtcrime.securesms.conversation.start.StartConversationDelegate @@ -88,7 +90,7 @@ class CreateGroupFragment : Fragment() { if (selectedMembers.count() >= groupSizeLimit) { // Minus one because we're going to include self later return@setOnClickListener Toast.makeText(context, R.string.activity_create_closed_group_too_many_group_members_error, Toast.LENGTH_LONG).show() } - val userPublicKey = TextSecurePreferences.getLocalNumber(requireContext())!! + val userPublicKey = requireContext().prefs.getLocalNumber()!! isLoading = true binding.loaderContainer.fadeIn() MessageSender.createClosedGroup(device, name.toString(), selectedMembers + setOf( userPublicKey )).successUi { groupID -> diff --git a/app/src/main/java/org/thoughtcrime/securesms/groups/EditClosedGroupActivity.kt b/app/src/main/java/org/thoughtcrime/securesms/groups/EditClosedGroupActivity.kt index da982589c2..e5e63b668b 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/groups/EditClosedGroupActivity.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/groups/EditClosedGroupActivity.kt @@ -22,12 +22,14 @@ import nl.komponents.kovenant.Promise import nl.komponents.kovenant.task import nl.komponents.kovenant.ui.failUi import nl.komponents.kovenant.ui.successUi +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.messaging.sending_receiving.MessageSender import org.session.libsession.messaging.sending_receiving.groupSizeLimit import org.session.libsession.utilities.Address import org.session.libsession.utilities.GroupUtil import org.session.libsession.utilities.TextSecurePreferences import org.session.libsession.utilities.ThemeUtil +import org.session.libsession.utilities.prefs import org.session.libsession.utilities.recipients.Recipient import org.session.libsignal.utilities.Log import org.session.libsignal.utilities.toHexString @@ -107,7 +109,7 @@ class EditClosedGroupActivity : PassphraseRequiredActionBarActivity() { groupID = intent.getStringExtra(groupIDKey)!! val groupInfo = DatabaseComponent.get(this).groupDatabase().getGroup(groupID).get() originalName = groupInfo.title - isSelfAdmin = groupInfo.admins.any{ it.serialize() == TextSecurePreferences.getLocalNumber(this) } + isSelfAdmin = groupInfo.admins.any{ it.serialize() == prefs.getLocalNumber() } name = originalName @@ -291,7 +293,7 @@ class EditClosedGroupActivity : PassphraseRequiredActionBarActivity() { return Toast.makeText(this, R.string.activity_create_closed_group_too_many_group_members_error, Toast.LENGTH_LONG).show() } - val userPublicKey = TextSecurePreferences.getLocalNumber(this)!! + val userPublicKey = prefs.getLocalNumber()!! val userAsRecipient = Recipient.from(this, Address.fromSerialized(userPublicKey), false) if (!members.contains(userAsRecipient) && !members.map { it.address.toString() }.containsAll(originalMembers.minus(userPublicKey))) { diff --git a/app/src/main/java/org/thoughtcrime/securesms/groups/EditClosedGroupMembersAdapter.kt b/app/src/main/java/org/thoughtcrime/securesms/groups/EditClosedGroupMembersAdapter.kt index b2d0f6255a..e89d3cc4d0 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/groups/EditClosedGroupMembersAdapter.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/groups/EditClosedGroupMembersAdapter.kt @@ -3,11 +3,13 @@ package org.thoughtcrime.securesms.groups import android.content.Context import androidx.recyclerview.widget.RecyclerView import android.view.ViewGroup +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.utilities.Address import org.thoughtcrime.securesms.contacts.UserView import org.thoughtcrime.securesms.mms.GlideRequests import org.session.libsession.utilities.recipients.Recipient import org.session.libsession.utilities.TextSecurePreferences +import org.session.libsession.utilities.prefs class EditClosedGroupMembersAdapter( private val context: Context, @@ -41,7 +43,7 @@ class EditClosedGroupMembersAdapter( override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) { val member = members[position] - val unlocked = admin && member != TextSecurePreferences.getLocalNumber(context) + val unlocked = admin && member != context.prefs.getLocalNumber() viewHolder.view.bind(Recipient.from( context, diff --git a/app/src/main/java/org/thoughtcrime/securesms/groups/GroupManager.java b/app/src/main/java/org/thoughtcrime/securesms/groups/GroupManager.java index d4c5acf4ed..45c478343a 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/groups/GroupManager.java +++ b/app/src/main/java/org/thoughtcrime/securesms/groups/GroupManager.java @@ -56,7 +56,7 @@ public class GroupManager { final Recipient groupRecipient = Recipient.from(context, Address.fromSerialized(groupId), false); final Set
memberAddresses = new HashSet<>(); - memberAddresses.add(Address.fromSerialized(Objects.requireNonNull(TextSecurePreferences.getLocalNumber(context)))); + memberAddresses.add(Address.fromSerialized(Objects.requireNonNull(MessagingModuleConfiguration.getShared().getPrefs().getLocalNumber()))); groupDatabase.create(groupId, name, new LinkedList<>(memberAddresses), null, null, new LinkedList<>(), System.currentTimeMillis()); groupDatabase.updateProfilePicture(groupId, avatarBytes); diff --git a/app/src/main/java/org/thoughtcrime/securesms/home/HomeActivity.kt b/app/src/main/java/org/thoughtcrime/securesms/home/HomeActivity.kt index b03838ce7b..cd453b5534 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/home/HomeActivity.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/home/HomeActivity.kt @@ -38,6 +38,7 @@ import org.session.libsession.utilities.Address import org.session.libsession.utilities.GroupUtil import org.session.libsession.utilities.ProfilePictureModifiedEvent import org.session.libsession.utilities.TextSecurePreferences +import org.session.libsession.utilities.prefs import org.session.libsession.utilities.recipients.Recipient import org.session.libsignal.utilities.Log import org.session.libsignal.utilities.ThreadUtils @@ -324,7 +325,7 @@ class HomeActivity : PassphraseRequiredActionBarActivity(), binding.sessionToolbar.isVisible = !isShown binding.recyclerView.isVisible = !isShown binding.emptyStateContainer.isVisible = (binding.recyclerView.adapter as HomeAdapter).itemCount == 0 && binding.recyclerView.isVisible - binding.seedReminderView.isVisible = !TextSecurePreferences.getHasViewedSeed(this) && !isShown + binding.seedReminderView.isVisible = !prefs.getHasViewedSeed() && !isShown binding.globalSearchRecycler.isInvisible = !isShown binding.newConversationButton.isVisible = !isShown } diff --git a/app/src/main/java/org/thoughtcrime/securesms/logging/LogSecretProvider.java b/app/src/main/java/org/thoughtcrime/securesms/logging/LogSecretProvider.java index aabd2811db..9ffaf795b6 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/logging/LogSecretProvider.java +++ b/app/src/main/java/org/thoughtcrime/securesms/logging/LogSecretProvider.java @@ -4,6 +4,7 @@ import android.content.Context; import android.os.Build; import androidx.annotation.NonNull; +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.thoughtcrime.securesms.crypto.KeyStoreHelper; import org.session.libsignal.utilities.Base64; import org.session.libsession.utilities.TextSecurePreferences; @@ -14,8 +15,8 @@ import java.security.SecureRandom; class LogSecretProvider { static byte[] getOrCreateAttachmentSecret(@NonNull Context context) { - String unencryptedSecret = TextSecurePreferences.getLogUnencryptedSecret(context); - String encryptedSecret = TextSecurePreferences.getLogEncryptedSecret(context); + String unencryptedSecret = MessagingModuleConfiguration.getShared().getPrefs().getLogUnencryptedSecret(); + String encryptedSecret = MessagingModuleConfiguration.getShared().getPrefs().getLogEncryptedSecret(); if (unencryptedSecret != null) return parseUnencryptedSecret(unencryptedSecret); else if (encryptedSecret != null) return parseEncryptedSecret(encryptedSecret); @@ -44,12 +45,8 @@ class LogSecretProvider { byte[] secret = new byte[32]; random.nextBytes(secret); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - KeyStoreHelper.SealedData encryptedSecret = KeyStoreHelper.seal(secret); - TextSecurePreferences.setLogEncryptedSecret(context, encryptedSecret.serialize()); - } else { - TextSecurePreferences.setLogUnencryptedSecret(context, Base64.encodeBytes(secret)); - } + KeyStoreHelper.SealedData encryptedSecret = KeyStoreHelper.seal(secret); + MessagingModuleConfiguration.getShared().getPrefs().setLogEncryptedSecret(encryptedSecret.serialize()); return secret; } diff --git a/app/src/main/java/org/thoughtcrime/securesms/mediasend/Camera1Fragment.java b/app/src/main/java/org/thoughtcrime/securesms/mediasend/Camera1Fragment.java index 23f9d33e07..0799dc059e 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/mediasend/Camera1Fragment.java +++ b/app/src/main/java/org/thoughtcrime/securesms/mediasend/Camera1Fragment.java @@ -35,6 +35,8 @@ import com.bumptech.glide.request.target.SimpleTarget; import com.bumptech.glide.request.transition.Transition; import network.loki.messenger.R; + +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.session.libsignal.utilities.Log; import org.thoughtcrime.securesms.mms.GlideApp; import org.session.libsession.utilities.ServiceUtil; @@ -78,7 +80,7 @@ public class Camera1Fragment extends Fragment implements TextureView.SurfaceText display.getSize(displaySize); controller = (Controller) getActivity(); - camera = new Camera1Controller(TextSecurePreferences.getDirectCaptureCameraId(getContext()), displaySize.x, displaySize.y, this); + camera = new Camera1Controller(MessagingModuleConfiguration.getShared().getPrefs().getDirectCaptureCameraId(), displaySize.x, displaySize.y, this); orderEnforcer = new OrderEnforcer<>(Stage.SURFACE_AVAILABLE, Stage.CAMERA_PROPERTIES_AVAILABLE); viewModel = new ViewModelProvider(requireActivity(), new MediaSendViewModel.Factory(requireActivity().getApplication(), new MediaRepository())).get(MediaSendViewModel.class); } @@ -212,7 +214,7 @@ public class Camera1Fragment extends Fragment implements TextureView.SurfaceText flipButton.setVisibility(properties.getCameraCount() > 1 ? View.VISIBLE : View.GONE); flipButton.setOnClickListener(v -> { int newCameraId = camera.flip(); - TextSecurePreferences.setDirectCaptureCameraId(getContext(), newCameraId); + MessagingModuleConfiguration.getShared().getPrefs().setDirectCaptureCameraId(newCameraId); Animation animation = new RotateAnimation(0, -180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); animation.setDuration(200); diff --git a/app/src/main/java/org/thoughtcrime/securesms/mediasend/MediaSendFragment.java b/app/src/main/java/org/thoughtcrime/securesms/mediasend/MediaSendFragment.java index cba1529a51..ea60c47c0a 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/mediasend/MediaSendFragment.java +++ b/app/src/main/java/org/thoughtcrime/securesms/mediasend/MediaSendFragment.java @@ -28,6 +28,7 @@ import android.view.inputmethod.EditorInfo; import android.widget.ImageButton; import android.widget.TextView; +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.session.libsession.utilities.MediaTypes; import org.thoughtcrime.securesms.components.ComposeText; import org.thoughtcrime.securesms.components.ControllableViewPager; @@ -50,7 +51,6 @@ import org.thoughtcrime.securesms.util.PushCharacterCalculator; import org.thoughtcrime.securesms.util.Stopwatch; import org.session.libsignal.utilities.guava.Optional; -import org.session.libsession.utilities.TextSecurePreferences; import org.session.libsession.utilities.Util; import org.session.libsession.utilities.Stub; import org.session.libsignal.utilities.ListenableFuture; @@ -215,7 +215,7 @@ public class MediaSendFragment extends Fragment implements ViewTreeObserver.OnGl return isSend; }); - if (TextSecurePreferences.isSystemEmojiPreferred(getContext())) { + if (MessagingModuleConfiguration.getShared().getPrefs().isSystemEmojiPreferred()) { emojiToggle.setVisibility(View.GONE); } else { emojiToggle.setOnClickListener(this::onEmojiToggleClicked); @@ -511,7 +511,7 @@ public class MediaSendFragment extends Fragment implements ViewTreeObserver.OnGl public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) { if (keyCode == KeyEvent.KEYCODE_ENTER) { - if (TextSecurePreferences.isEnterSendsEnabled(requireContext())) { + if (MessagingModuleConfiguration.getShared().getPrefs().isEnterSendsEnabled()) { sendButton.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER)); sendButton.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER)); return true; diff --git a/app/src/main/java/org/thoughtcrime/securesms/mms/SignalGlideModule.java b/app/src/main/java/org/thoughtcrime/securesms/mms/SignalGlideModule.java index 02172b7248..9843840d3e 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/mms/SignalGlideModule.java +++ b/app/src/main/java/org/thoughtcrime/securesms/mms/SignalGlideModule.java @@ -58,7 +58,7 @@ public class SignalGlideModule extends AppGlideModule { @Override public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) { - AttachmentSecret attachmentSecret = AttachmentSecretProvider.getInstance(context).getOrCreateAttachmentSecret(); + AttachmentSecret attachmentSecret = AttachmentSecretProvider.getInstance().getOrCreateAttachmentSecret(); byte[] secret = attachmentSecret.getModernKey(); registry.prepend(File.class, File.class, UnitModelLoader.Factory.getInstance()); diff --git a/app/src/main/java/org/thoughtcrime/securesms/notifications/AbstractNotificationBuilder.java b/app/src/main/java/org/thoughtcrime/securesms/notifications/AbstractNotificationBuilder.java index 64617eb6a1..b078a5ca15 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/notifications/AbstractNotificationBuilder.java +++ b/app/src/main/java/org/thoughtcrime/securesms/notifications/AbstractNotificationBuilder.java @@ -11,6 +11,7 @@ import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.NotificationCompat; +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.session.libsession.utilities.NotificationPrivacyPreference; import org.session.libsession.utilities.TextSecurePreferences; import org.session.libsession.utilities.Util; @@ -50,8 +51,8 @@ public abstract class AbstractNotificationBuilder extends NotificationCompat.Bui } public void setAlarms(@Nullable Uri ringtone, VibrateState vibrate) { - Uri defaultRingtone = NotificationChannels.supported() ? NotificationChannels.getMessageRingtone(context) : TextSecurePreferences.getNotificationRingtone(context); - boolean defaultVibrate = NotificationChannels.supported() ? NotificationChannels.getMessageVibrate(context) : TextSecurePreferences.isNotificationVibrateEnabled(context); + Uri defaultRingtone = NotificationChannels.supported() ? NotificationChannels.getMessageRingtone(context) : MessagingModuleConfiguration.getShared().getPrefs().getNotificationRingtone(); + boolean defaultVibrate = NotificationChannels.supported() ? NotificationChannels.getMessageVibrate(context) : MessagingModuleConfiguration.getShared().getPrefs().isNotificationVibrateEnabled(); if (ringtone == null && !TextUtils.isEmpty(defaultRingtone.toString())) setSound(defaultRingtone); else if (ringtone != null && !ringtone.toString().isEmpty()) setSound(ringtone); @@ -64,7 +65,7 @@ public abstract class AbstractNotificationBuilder extends NotificationCompat.Bui } private void setLed() { - int ledColor = TextSecurePreferences.getNotificationLedColor(context); + int ledColor = MessagingModuleConfiguration.getShared().getPrefs().getNotificationLedColor(); setLights(ledColor, 500,2000); } diff --git a/app/src/main/java/org/thoughtcrime/securesms/notifications/BackgroundPollWorker.kt b/app/src/main/java/org/thoughtcrime/securesms/notifications/BackgroundPollWorker.kt index 63f6d07da1..270da644cd 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/notifications/BackgroundPollWorker.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/notifications/BackgroundPollWorker.kt @@ -22,6 +22,7 @@ import org.session.libsession.messaging.sending_receiving.pollers.ClosedGroupPol import org.session.libsession.messaging.sending_receiving.pollers.OpenGroupPoller import org.session.libsession.snode.SnodeAPI import org.session.libsession.utilities.TextSecurePreferences +import org.session.libsession.utilities.prefs import org.session.libsignal.utilities.Log import org.session.libsignal.utilities.recover import org.thoughtcrime.securesms.dependencies.DatabaseComponent @@ -76,7 +77,7 @@ class BackgroundPollWorker(val context: Context, params: WorkerParameters) : Wor } override fun doWork(): Result { - if (TextSecurePreferences.getLocalNumber(context) == null) { + if (MessagingModuleConfiguration.shared.prefs.getLocalNumber() == null) { Log.v(TAG, "User not registered yet.") return Result.failure() } @@ -108,7 +109,7 @@ class BackgroundPollWorker(val context: Context, params: WorkerParameters) : Wor var dmsPromise: Promise = Promise.ofSuccess(Unit) if (requestTargets.contains(Targets.DMS)) { - val userPublicKey = TextSecurePreferences.getLocalNumber(context)!! + val userPublicKey = context.prefs.getLocalNumber()!! dmsPromise = SnodeAPI.getMessages(userPublicKey).bind { envelopes -> val params = envelopes.map { (envelope, serverHash) -> // FIXME: Using a job here seems like a bad idea... diff --git a/app/src/main/java/org/thoughtcrime/securesms/notifications/DefaultMessageNotifier.java b/app/src/main/java/org/thoughtcrime/securesms/notifications/DefaultMessageNotifier.java index 5abaee4033..40d6e875f6 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/notifications/DefaultMessageNotifier.java +++ b/app/src/main/java/org/thoughtcrime/securesms/notifications/DefaultMessageNotifier.java @@ -40,6 +40,7 @@ import com.annimon.stream.Optional; import com.annimon.stream.Stream; import com.goterl.lazysodium.utils.KeyPair; +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.session.libsession.messaging.open_groups.OpenGroup; import org.session.libsession.messaging.sending_receiving.notifications.MessageNotifier; import org.session.libsession.messaging.utilities.AccountId; @@ -138,18 +139,18 @@ public class DefaultMessageNotifier implements MessageNotifier { intent.putExtra(ConversationActivityV2.THREAD_ID, threadId); intent.setData((Uri.parse("custom://" + SnodeAPI.getNowWithOffset()))); - FailedNotificationBuilder builder = new FailedNotificationBuilder(context, TextSecurePreferences.getNotificationPrivacy(context), intent); + FailedNotificationBuilder builder = new FailedNotificationBuilder(context, MessagingModuleConfiguration.getShared().getPrefs().getNotificationPrivacy(), intent); ((NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE)) .notify((int)threadId, builder.build()); } } public void notifyMessagesPending(Context context) { - if (!TextSecurePreferences.isNotificationsEnabled(context)) { + if (!MessagingModuleConfiguration.getShared().getPrefs().isNotificationsEnabled()) { return; } - PendingMessageNotificationBuilder builder = new PendingMessageNotificationBuilder(context, TextSecurePreferences.getNotificationPrivacy(context)); + PendingMessageNotificationBuilder builder = new PendingMessageNotificationBuilder(context, MessagingModuleConfiguration.getShared().getPrefs().getNotificationPrivacy()); ServiceUtil.getNotificationManager(context).notify(PENDING_MESSAGES_ID, builder.build()); } @@ -210,7 +211,7 @@ public class DefaultMessageNotifier implements MessageNotifier { @Override public void updateNotification(@NonNull Context context) { - if (!TextSecurePreferences.isNotificationsEnabled(context)) { + if (!MessagingModuleConfiguration.getShared().getPrefs().isNotificationsEnabled()) { return; } @@ -238,10 +239,10 @@ public class DefaultMessageNotifier implements MessageNotifier { if (recipient != null && !recipient.isGroupRecipient() && threads.getMessageCount(threadId) == 1 && !(recipient.isApproved() || threads.getLastSeenAndHasSent(threadId).second())) { - TextSecurePreferences.removeHasHiddenMessageRequests(context); + MessagingModuleConfiguration.getShared().getPrefs().removeHasHiddenMessageRequests(); } - if (!TextSecurePreferences.isNotificationsEnabled(context) || + if (!MessagingModuleConfiguration.getShared().getPrefs().isNotificationsEnabled() || (recipient != null && recipient.isMuted())) { return; @@ -271,7 +272,7 @@ public class DefaultMessageNotifier implements MessageNotifier { try { telcoCursor = DatabaseComponent.get(context).mmsSmsDatabase().getUnread(); // TODO: add a notification specific lighter query here - if ((telcoCursor == null || telcoCursor.isAfterLast()) || TextSecurePreferences.getLocalNumber(context) == null) + if ((telcoCursor == null || telcoCursor.isAfterLast()) || MessagingModuleConfiguration.getShared().getPrefs().getLocalNumber() == null) { updateBadge(context, 0); cancelActiveNotifications(context); @@ -324,7 +325,7 @@ public class DefaultMessageNotifier implements MessageNotifier { return; } - SingleRecipientNotificationBuilder builder = new SingleRecipientNotificationBuilder(context, TextSecurePreferences.getNotificationPrivacy(context)); + SingleRecipientNotificationBuilder builder = new SingleRecipientNotificationBuilder(context, MessagingModuleConfiguration.getShared().getPrefs().getNotificationPrivacy()); List notifications = notificationState.getNotifications(); Recipient recipient = notifications.get(0).getRecipient(); int notificationId = (int) (SUMMARY_NOTIFICATION_ID + (bundled ? notifications.get(0).getThreadId() : 0)); @@ -411,7 +412,7 @@ public class DefaultMessageNotifier implements MessageNotifier { { Log.i(TAG, "sendMultiThreadNotification() signal: " + signal); - MultipleRecipientNotificationBuilder builder = new MultipleRecipientNotificationBuilder(context, TextSecurePreferences.getNotificationPrivacy(context)); + MultipleRecipientNotificationBuilder builder = new MultipleRecipientNotificationBuilder(context, MessagingModuleConfiguration.getShared().getPrefs().getNotificationPrivacy()); List notifications = notificationState.getNotifications(); builder.setMessageCount(notificationState.getMessageCount(), notificationState.getThreadCount()); @@ -501,7 +502,7 @@ public class DefaultMessageNotifier implements MessageNotifier { threadRecipients = threadDatabase.getRecipientForThreadId(threadId); messageRequest = threadRecipients != null && !threadRecipients.isGroupRecipient() && !threadRecipients.isApproved() && !threadDatabase.getLastSeenAndHasSent(threadId).second(); - if (messageRequest && (threadDatabase.getMessageCount(threadId) > 1 || !TextSecurePreferences.hasHiddenMessageRequests(context))) { + if (messageRequest && (threadDatabase.getMessageCount(threadId) > 1 || !MessagingModuleConfiguration.getShared().getPrefs().hasHiddenMessageRequests())) { continue; } } @@ -523,7 +524,7 @@ public class DefaultMessageNotifier implements MessageNotifier { } else if (record.isOpenGroupInvitation()) { body = SpanUtil.italic(context.getString(R.string.ThreadRecord_open_group_invitation)); } - String userPublicKey = TextSecurePreferences.getLocalNumber(context); + String userPublicKey = MessagingModuleConfiguration.getShared().getPrefs().getLocalNumber(); String blindedPublicKey = cache.get(threadId); if (blindedPublicKey == null) { blindedPublicKey = generateBlindedId(threadId, context); @@ -594,7 +595,7 @@ public class DefaultMessageNotifier implements MessageNotifier { } private void scheduleReminder(Context context, int count) { - if (count >= TextSecurePreferences.getRepeatAlertsCount(context)) { + if (count >= MessagingModuleConfiguration.getShared().getPrefs().getRepeatAlertsCount()) { return; } diff --git a/app/src/main/java/org/thoughtcrime/securesms/notifications/MarkReadReceiver.kt b/app/src/main/java/org/thoughtcrime/securesms/notifications/MarkReadReceiver.kt index 59681c1f8a..096b3f1464 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/notifications/MarkReadReceiver.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/notifications/MarkReadReceiver.kt @@ -6,15 +6,14 @@ import android.content.Context import android.content.Intent import android.os.AsyncTask import androidx.core.app.NotificationManagerCompat -import org.session.libsession.messaging.MessagingModuleConfiguration.Companion.shared +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.messaging.messages.control.ReadReceipt import org.session.libsession.messaging.sending_receiving.MessageSender.send import org.session.libsession.snode.SnodeAPI import org.session.libsession.snode.SnodeAPI.nowWithOffset import org.session.libsession.utilities.SSKEnvironment -import org.session.libsession.utilities.TextSecurePreferences -import org.session.libsession.utilities.TextSecurePreferences.Companion.isReadReceiptsEnabled import org.session.libsession.utilities.associateByNotNull +import org.session.libsession.utilities.prefs import org.session.libsession.utilities.recipients.Recipient import org.session.libsignal.utilities.Log import org.thoughtcrime.securesms.ApplicationContext @@ -35,7 +34,7 @@ class MarkReadReceiver : BroadcastReceiver() { val currentTime = nowWithOffset threadIds.forEach { Log.i(TAG, "Marking as read: $it") - shared.storage.markConversationAsRead(it, currentTime, true) + MessagingModuleConfiguration.shared.storage.markConversationAsRead(it, currentTime, true) } return null } @@ -102,7 +101,7 @@ class MarkReadReceiver : BroadcastReceiver() { SnodeAPI.alterTtl( messageHashes = hashes, newExpiry = nowWithOffset + expiresIn, - publicKey = TextSecurePreferences.getLocalNumber(context)!!, + publicKey = context.prefs.getLocalNumber()!!, shorten = true ) } @@ -112,7 +111,7 @@ class MarkReadReceiver : BroadcastReceiver() { context: Context, markedReadMessages: List ) { - if (!isReadReceiptsEnabled(context)) return + if (!context.prefs.isReadReceiptsEnabled()) return markedReadMessages.map { it.syncMessageId } .filter { shouldSendReadReceipt(Recipient.from(context, it.address, false)) } @@ -130,7 +129,7 @@ class MarkReadReceiver : BroadcastReceiver() { hashToMessage: Map ) { @Suppress("UNCHECKED_CAST") - val expiries = SnodeAPI.getExpiries(hashToMessage.keys.toList(), TextSecurePreferences.getLocalNumber(context)!!).get()["expiries"] as Map + val expiries = SnodeAPI.getExpiries(hashToMessage.keys.toList(), context.prefs.getLocalNumber()!!).get()["expiries"] as Map hashToMessage.forEach { (hash, info) -> expiries[hash]?.let { scheduleDeletion(context, info.expirationInfo, it - info.expirationInfo.expireStarted) } } } diff --git a/app/src/main/java/org/thoughtcrime/securesms/notifications/MultipleRecipientNotificationBuilder.java b/app/src/main/java/org/thoughtcrime/securesms/notifications/MultipleRecipientNotificationBuilder.java index 7042a1766a..d67971c1b8 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/notifications/MultipleRecipientNotificationBuilder.java +++ b/app/src/main/java/org/thoughtcrime/securesms/notifications/MultipleRecipientNotificationBuilder.java @@ -10,6 +10,7 @@ import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.NotificationCompat; +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.session.libsession.messaging.contacts.Contact; import org.session.libsession.utilities.NotificationPrivacyPreference; import org.session.libsession.utilities.TextSecurePreferences; @@ -39,7 +40,7 @@ public class MultipleRecipientNotificationBuilder extends AbstractNotificationBu setGroupSummary(true); if (!NotificationChannels.supported()) { - setPriority(TextSecurePreferences.getNotificationPriority(context)); + setPriority(MessagingModuleConfiguration.getShared().getPrefs().getNotificationPriority()); } } diff --git a/app/src/main/java/org/thoughtcrime/securesms/notifications/NotificationChannels.java b/app/src/main/java/org/thoughtcrime/securesms/notifications/NotificationChannels.java index 8bf1d7d8d8..a9a9e061d5 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/notifications/NotificationChannels.java +++ b/app/src/main/java/org/thoughtcrime/securesms/notifications/NotificationChannels.java @@ -20,6 +20,7 @@ import androidx.annotation.WorkerThread; import com.annimon.stream.Collectors; import com.annimon.stream.Stream; +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.session.libsession.utilities.Address; import org.session.libsession.utilities.ServiceUtil; import org.session.libsession.utilities.TextSecurePreferences; @@ -69,10 +70,10 @@ public class NotificationChannels { NotificationManager notificationManager = ServiceUtil.getNotificationManager(context); - int oldVersion = TextSecurePreferences.getNotificationChannelVersion(context); + int oldVersion = MessagingModuleConfiguration.getShared().getPrefs().getNotificationChannelVersion(); if (oldVersion != VERSION) { onUpgrade(notificationManager, oldVersion, VERSION); - TextSecurePreferences.setNotificationChannelVersion(context, VERSION); + MessagingModuleConfiguration.getShared().getPrefs().setNotificationChannelVersion(VERSION); } onCreate(context, notificationManager); @@ -112,7 +113,7 @@ public class NotificationChannels { * @return The channel ID for the default messages channel. */ public static synchronized @NonNull String getMessagesChannel(@NonNull Context context) { - return getMessagesChannelId(TextSecurePreferences.getNotificationMessagesChannelVersion(context)); + return getMessagesChannelId(MessagingModuleConfiguration.getShared().getPrefs().getNotificationMessagesChannelVersion()); } /** @@ -143,7 +144,7 @@ public class NotificationChannels { */ public static synchronized String createChannelFor(@NonNull Context context, @NonNull Recipient recipient) { VibrateState vibrateState = recipient.getMessageVibrate(); - boolean vibrationEnabled = vibrateState == VibrateState.DEFAULT ? TextSecurePreferences.isNotificationVibrateEnabled(context) : vibrateState == VibrateState.ENABLED; + boolean vibrationEnabled = vibrateState == VibrateState.DEFAULT ? MessagingModuleConfiguration.getShared().getPrefs().isNotificationVibrateEnabled() : vibrateState == VibrateState.ENABLED; Uri messageRingtone = recipient.getMessageRingtone() != null ? recipient.getMessageRingtone() : getMessageRingtone(context); String displayName = getChannelDisplayNameFor(context, recipient.getName(), recipient.getProfileName(), recipient.getAddress()); @@ -166,7 +167,7 @@ public class NotificationChannels { String channelId = generateChannelIdFor(address); NotificationChannel channel = new NotificationChannel(channelId, displayName, NotificationManager.IMPORTANCE_HIGH); - setLedPreference(channel, TextSecurePreferences.getNotificationLedColor(context)); + setLedPreference(channel, MessagingModuleConfiguration.getShared().getPrefs().getNotificationLedColor()); channel.setGroup(CATEGORY_MESSAGES); channel.enableVibration(vibrationEnabled); @@ -434,9 +435,9 @@ public class NotificationChannels { NotificationChannel other = new NotificationChannel(OTHER, context.getString(R.string.NotificationChannel_other), NotificationManager.IMPORTANCE_LOW); messages.setGroup(CATEGORY_MESSAGES); - messages.enableVibration(TextSecurePreferences.isNotificationVibrateEnabled(context)); - messages.setSound(TextSecurePreferences.getNotificationRingtone(context), getRingtoneAudioAttributes()); - setLedPreference(messages, TextSecurePreferences.getNotificationLedColor(context)); + messages.enableVibration(MessagingModuleConfiguration.getShared().getPrefs().isNotificationVibrateEnabled()); + messages.setSound(MessagingModuleConfiguration.getShared().getPrefs().getNotificationRingtone(), getRingtoneAudioAttributes()); + setLedPreference(messages, MessagingModuleConfiguration.getShared().getPrefs().getNotificationLedColor()); calls.setShowBadge(false); calls.setSound(null, null); @@ -528,12 +529,12 @@ public class NotificationChannels { @TargetApi(26) private static void updateMessageChannel(@NonNull Context context, @NonNull ChannelUpdater updater) { NotificationManager notificationManager = ServiceUtil.getNotificationManager(context); - int existingVersion = TextSecurePreferences.getNotificationMessagesChannelVersion(context); + int existingVersion = MessagingModuleConfiguration.getShared().getPrefs().getNotificationMessagesChannelVersion(); int newVersion = existingVersion + 1; Log.i(TAG, "Updating message channel from version " + existingVersion + " to " + newVersion); if (updateExistingChannel(notificationManager, getMessagesChannelId(existingVersion), getMessagesChannelId(newVersion), updater)) { - TextSecurePreferences.setNotificationMessagesChannelVersion(context, newVersion); + MessagingModuleConfiguration.getShared().getPrefs().setNotificationMessagesChannelVersion(newVersion); } else { onCreate(context, notificationManager); } diff --git a/app/src/main/java/org/thoughtcrime/securesms/notifications/PendingMessageNotificationBuilder.java b/app/src/main/java/org/thoughtcrime/securesms/notifications/PendingMessageNotificationBuilder.java index 935d575c56..8b533384a1 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/notifications/PendingMessageNotificationBuilder.java +++ b/app/src/main/java/org/thoughtcrime/securesms/notifications/PendingMessageNotificationBuilder.java @@ -7,6 +7,7 @@ import android.content.Intent; import androidx.core.app.NotificationCompat; +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.session.libsession.utilities.NotificationPrivacyPreference; import org.session.libsession.utilities.TextSecurePreferences; import org.session.libsession.utilities.recipients.Recipient; @@ -34,7 +35,7 @@ public class PendingMessageNotificationBuilder extends AbstractNotificationBuild setAlarms(null, Recipient.VibrateState.DEFAULT); if (!NotificationChannels.supported()) { - setPriority(TextSecurePreferences.getNotificationPriority(context)); + setPriority(MessagingModuleConfiguration.getShared().getPrefs().getNotificationPriority()); } } } diff --git a/app/src/main/java/org/thoughtcrime/securesms/notifications/SingleRecipientNotificationBuilder.java b/app/src/main/java/org/thoughtcrime/securesms/notifications/SingleRecipientNotificationBuilder.java index d5aeba6022..64e43c1ffd 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/notifications/SingleRecipientNotificationBuilder.java +++ b/app/src/main/java/org/thoughtcrime/securesms/notifications/SingleRecipientNotificationBuilder.java @@ -29,6 +29,7 @@ import com.bumptech.glide.load.engine.DiskCacheStrategy; import org.session.libsession.avatars.ContactColors; import org.session.libsession.avatars.ContactPhoto; import org.session.libsession.avatars.GeneratedContactPhoto; +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.session.libsession.messaging.contacts.Contact; import org.session.libsession.utilities.NotificationPrivacyPreference; import org.session.libsession.utilities.TextSecurePreferences; @@ -69,7 +70,7 @@ public class SingleRecipientNotificationBuilder extends AbstractNotificationBuil setCategory(NotificationCompat.CATEGORY_MESSAGE); if (!NotificationChannels.supported()) { - setPriority(TextSecurePreferences.getNotificationPriority(context)); + setPriority(MessagingModuleConfiguration.getShared().getPrefs().getNotificationPriority()); } } diff --git a/app/src/main/java/org/thoughtcrime/securesms/notifications/TokenManager.kt b/app/src/main/java/org/thoughtcrime/securesms/notifications/TokenManager.kt index b3db642b81..53ee01d63b 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/notifications/TokenManager.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/notifications/TokenManager.kt @@ -1,7 +1,5 @@ package org.thoughtcrime.securesms.notifications -import android.content.Context -import dagger.hilt.android.qualifiers.ApplicationContext import org.session.libsession.utilities.TextSecurePreferences import javax.inject.Inject import javax.inject.Singleton @@ -10,7 +8,7 @@ private const val INTERVAL: Int = 12 * 60 * 60 * 1000 @Singleton class TokenManager @Inject constructor( - @ApplicationContext private val context: Context, + private val prefs: TextSecurePreferences ) { val hasValidRegistration get() = isRegistered && !isExpired val isRegistered get() = time > 0 @@ -25,8 +23,8 @@ class TokenManager @Inject constructor( } private var time - get() = TextSecurePreferences.getPushRegisterTime(context) - set(value) = TextSecurePreferences.setPushRegisterTime(context, value) + get() = prefs.getPushRegisterTime() + set(value) = prefs.setPushRegisterTime(value) private fun currentTime() = System.currentTimeMillis() } diff --git a/app/src/main/java/org/thoughtcrime/securesms/onboarding/landing/LandingActivity.kt b/app/src/main/java/org/thoughtcrime/securesms/onboarding/landing/LandingActivity.kt index 3be3eafcc2..a8432b9606 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/onboarding/landing/LandingActivity.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/onboarding/landing/LandingActivity.kt @@ -40,7 +40,7 @@ class LandingActivity: BaseActionBarActivity() { } IdentityKeyUtil.generateIdentityKeyPair(this) - TextSecurePreferences.setPasswordDisabled(this, true) + prefs.setPasswordDisabled(true) // AC: This is a temporary workaround to trick the old code that the screen is unlocked. KeyCachingService.setMasterSecret(applicationContext, Object()) } diff --git a/app/src/main/java/org/thoughtcrime/securesms/preferences/CallToggleListener.kt b/app/src/main/java/org/thoughtcrime/securesms/preferences/CallToggleListener.kt index ea747798c8..5fc52a5ae2 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/preferences/CallToggleListener.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/preferences/CallToggleListener.kt @@ -4,13 +4,13 @@ import android.Manifest import androidx.fragment.app.Fragment import androidx.preference.Preference import network.loki.messenger.R -import org.session.libsession.utilities.TextSecurePreferences -import org.session.libsession.utilities.TextSecurePreferences.Companion.setBooleanPreference +import org.session.libsession.messaging.MessagingModuleConfiguration +import org.session.libsession.utilities.prefs import org.thoughtcrime.securesms.permissions.Permissions import org.thoughtcrime.securesms.showSessionDialog internal class CallToggleListener( - private val context: Fragment, + private val fragment: Fragment, private val setCallback: (Boolean) -> Unit ) : Preference.OnPreferenceChangeListener { @@ -18,7 +18,7 @@ internal class CallToggleListener( if (newValue == false) return true // check if we've shown the info dialog and check for microphone permissions - context.showSessionDialog { + fragment.showSessionDialog { title(R.string.dialog_voice_video_title) text(R.string.dialog_voice_video_message) button(R.string.dialog_link_preview_enable_button_title, R.string.AccessibilityId_enable) { requestMicrophonePermission() } @@ -29,14 +29,10 @@ internal class CallToggleListener( } private fun requestMicrophonePermission() { - Permissions.with(context) + Permissions.with(fragment) .request(Manifest.permission.RECORD_AUDIO) .onAllGranted { - setBooleanPreference( - context.requireContext(), - TextSecurePreferences.CALL_NOTIFICATIONS_ENABLED, - true - ) + fragment.requireContext().prefs.setCallNotificationsEnabled(true) setCallback(true) } .onAnyDenied { setCallback(false) } diff --git a/app/src/main/java/org/thoughtcrime/securesms/preferences/NotificationsPreferenceFragment.kt b/app/src/main/java/org/thoughtcrime/securesms/preferences/NotificationsPreferenceFragment.kt index fa6461acc4..6d0790247e 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/preferences/NotificationsPreferenceFragment.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/preferences/NotificationsPreferenceFragment.kt @@ -18,8 +18,9 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import network.loki.messenger.R +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.utilities.TextSecurePreferences -import org.session.libsession.utilities.TextSecurePreferences.Companion.isNotificationsEnabled +import org.session.libsession.utilities.prefs import org.thoughtcrime.securesms.ApplicationContext import org.thoughtcrime.securesms.components.SwitchPreferenceCompat import org.thoughtcrime.securesms.notifications.NotificationChannels @@ -175,7 +176,7 @@ class NotificationsPreferenceFragment : ListSummaryPreferenceFragment() { companion object { @Suppress("unused") private val TAG = NotificationsPreferenceFragment::class.java.simpleName - fun getSummary(context: Context): CharSequence = when (isNotificationsEnabled(context)) { + fun getSummary(context: Context): CharSequence = when (context.prefs.isNotificationsEnabled()) { true -> R.string.ApplicationPreferencesActivity_On false -> R.string.ApplicationPreferencesActivity_Off }.let(context::getString) diff --git a/app/src/main/java/org/thoughtcrime/securesms/preferences/PrivacySettingsPreferenceFragment.kt b/app/src/main/java/org/thoughtcrime/securesms/preferences/PrivacySettingsPreferenceFragment.kt index 21b12496bd..037c91443e 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/preferences/PrivacySettingsPreferenceFragment.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/preferences/PrivacySettingsPreferenceFragment.kt @@ -13,9 +13,9 @@ import androidx.preference.PreferenceDataStore import dagger.hilt.android.AndroidEntryPoint import network.loki.messenger.BuildConfig import network.loki.messenger.R +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.utilities.TextSecurePreferences -import org.session.libsession.utilities.TextSecurePreferences.Companion.isPasswordDisabled -import org.session.libsession.utilities.TextSecurePreferences.Companion.setScreenLockEnabled +import org.session.libsession.utilities.prefs import org.thoughtcrime.securesms.ApplicationContext import org.thoughtcrime.securesms.components.SwitchPreferenceCompat import org.thoughtcrime.securesms.dependencies.ConfigFactory @@ -30,6 +30,7 @@ import javax.inject.Inject class PrivacySettingsPreferenceFragment : ListSummaryPreferenceFragment() { @Inject lateinit var configFactory: ConfigFactory + @Inject lateinit var prefs: TextSecurePreferences override fun onCreate(paramBundle: Bundle?) { super.onCreate(paramBundle) @@ -109,12 +110,8 @@ class PrivacySettingsPreferenceFragment : ListSummaryPreferenceFragment() { addPreferencesFromResource(R.xml.preferences_app_protection) } - override fun onResume() { - super.onResume() - } - private fun initializeVisibility() { - if (isPasswordDisabled(requireContext())) { + if (prefs.isPasswordDisabled()) { val keyguardManager = requireContext().getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager if (!keyguardManager.isKeyguardSecure) { @@ -130,10 +127,10 @@ class PrivacySettingsPreferenceFragment : ListSummaryPreferenceFragment() { private inner class ScreenLockListener : Preference.OnPreferenceChangeListener { override fun onPreferenceChange(preference: Preference, newValue: Any): Boolean { val enabled = newValue as Boolean - setScreenLockEnabled(context!!, enabled) + requireContext().prefs.setScreenLockEnabled(enabled) val intent = Intent(context, KeyCachingService::class.java) intent.action = KeyCachingService.LOCK_TOGGLED_EVENT - context!!.startService(intent) + requireContext().startService(intent) return true } } diff --git a/app/src/main/java/org/thoughtcrime/securesms/preferences/QRCodeActivity.kt b/app/src/main/java/org/thoughtcrime/securesms/preferences/QRCodeActivity.kt index 5e14e46dd1..1c67803ef6 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/preferences/QRCodeActivity.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/preferences/QRCodeActivity.kt @@ -18,8 +18,10 @@ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.asSharedFlow import network.loki.messenger.R +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.utilities.Address import org.session.libsession.utilities.TextSecurePreferences +import org.session.libsession.utilities.prefs import org.session.libsession.utilities.recipients.Recipient import org.session.libsignal.utilities.PublicKeyValidation import org.thoughtcrime.securesms.PassphraseRequiredActionBarActivity @@ -47,7 +49,7 @@ class QRCodeActivity : PassphraseRequiredActionBarActivity() { setComposeContent { Tabs( - TextSecurePreferences.getLocalNumber(this)!!, + prefs.getLocalNumber()!!, errors.asSharedFlow(), onScan = ::onScan ) diff --git a/app/src/main/java/org/thoughtcrime/securesms/preferences/SettingsActivity.kt b/app/src/main/java/org/thoughtcrime/securesms/preferences/SettingsActivity.kt index 0ef4b800fd..b8b70d026c 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/preferences/SettingsActivity.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/preferences/SettingsActivity.kt @@ -108,7 +108,7 @@ class SettingsActivity : PassphraseRequiredActionBarActivity() { set(value) { field = value; handleDisplayNameEditActionModeChanged() } private var tempFile: File? = null - private val hexEncodedPublicKey: String get() = TextSecurePreferences.getLocalNumber(this)!! + private val hexEncodedPublicKey: String get() = prefs.getLocalNumber()!! companion object { private const val SCROLL_STATE = "SCROLL_STATE" @@ -140,7 +140,7 @@ class SettingsActivity : PassphraseRequiredActionBarActivity() { } private fun getDisplayName(): String = - TextSecurePreferences.getProfileName(this) ?: truncateIdForDisplay(hexEncodedPublicKey) + prefs.getProfileName() ?: truncateIdForDisplay(hexEncodedPublicKey) private fun setupProfilePictureView(view: ProfilePictureView) { view.apply { @@ -255,7 +255,7 @@ class SettingsActivity : PassphraseRequiredActionBarActivity() { binding.loader.isVisible = true val promises = mutableListOf>() if (displayName != null) { - TextSecurePreferences.setProfileName(this, displayName) + prefs.setProfileName(displayName) configFactory.user?.setName(displayName) } val encodedProfileKey = ProfileKeyUtil.generateEncodedProfileKey(this) @@ -269,11 +269,11 @@ class SettingsActivity : PassphraseRequiredActionBarActivity() { all(promises) successUi { // Do this on the UI thread so that it happens before the alwaysUi clause below val userConfig = configFactory.user if (isUpdatingProfilePicture) { - AvatarHelper.setAvatar(this, Address.fromSerialized(TextSecurePreferences.getLocalNumber(this)!!), profilePicture) + AvatarHelper.setAvatar(this, Address.fromSerialized(prefs.getLocalNumber()!!), profilePicture) prefs.setProfileAvatarId(profilePicture?.let { SecureRandom().nextInt() } ?: 0 ) ProfileKeyUtil.setEncodedProfileKey(this, encodedProfileKey) // new config - val url = TextSecurePreferences.getProfilePictureURL(this) + val url = prefs.getProfilePictureURL() val profileKey = ProfileKeyUtil.getProfileKey(this) if (profilePicture == null) { userConfig?.setPic(UserPic.DEFAULT) diff --git a/app/src/main/java/org/thoughtcrime/securesms/preferences/Util.kt b/app/src/main/java/org/thoughtcrime/securesms/preferences/Util.kt index 1271ece02e..58f537f728 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/preferences/Util.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/preferences/Util.kt @@ -6,7 +6,9 @@ import android.content.Context import android.content.Intent import android.widget.Toast import network.loki.messenger.R +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.utilities.TextSecurePreferences +import org.session.libsession.utilities.prefs fun Context.sendInvitationToUseSession() { Intent().apply { @@ -15,7 +17,7 @@ fun Context.sendInvitationToUseSession() { Intent.EXTRA_TEXT, getString( R.string.accountIdShare, - TextSecurePreferences.getLocalNumber(this@sendInvitationToUseSession) + prefs.getLocalNumber() ) ) type = "text/plain" @@ -25,7 +27,7 @@ fun Context.sendInvitationToUseSession() { fun Context.copyPublicKey() { val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager - val clip = ClipData.newPlainText("Account ID", TextSecurePreferences.getLocalNumber(this)) + val clip = ClipData.newPlainText("Account ID", prefs.getLocalNumber()) clipboard.setPrimaryClip(clip) Toast.makeText(this, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show() } diff --git a/app/src/main/java/org/thoughtcrime/securesms/providers/BlobProvider.java b/app/src/main/java/org/thoughtcrime/securesms/providers/BlobProvider.java index 6d900a5b37..269e13cb3b 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/providers/BlobProvider.java +++ b/app/src/main/java/org/thoughtcrime/securesms/providers/BlobProvider.java @@ -98,7 +98,7 @@ public class BlobProvider { String directory = getDirectory(storageType); File file = new File(getOrCreateCacheDirectory(context, directory), buildFileName(id)); - return ModernDecryptingPartInputStream.createFor(AttachmentSecretProvider.getInstance(context).getOrCreateAttachmentSecret(), file, 0); + return ModernDecryptingPartInputStream.createFor(AttachmentSecretProvider.getInstance().getOrCreateAttachmentSecret(), file, 0); } } else { throw new IOException("Provided URI does not match this spec. Uri: " + uri); @@ -174,7 +174,7 @@ public class BlobProvider { @WorkerThread private synchronized @NonNull Uri writeBlobSpecToDisk(@NonNull Context context, @NonNull BlobSpec blobSpec, @Nullable ErrorListener errorListener) throws IOException { - AttachmentSecret attachmentSecret = AttachmentSecretProvider.getInstance(context).getOrCreateAttachmentSecret(); + AttachmentSecret attachmentSecret = AttachmentSecretProvider.getInstance().getOrCreateAttachmentSecret(); String directory = getDirectory(blobSpec.getStorageType()); File outputFile = new File(getOrCreateCacheDirectory(context, directory), buildFileName(blobSpec.id)); OutputStream outputStream = ModernEncryptingPartOutputStream.createFor(attachmentSecret, outputFile, true).second; diff --git a/app/src/main/java/org/thoughtcrime/securesms/scribbles/ImageEditorFragment.java b/app/src/main/java/org/thoughtcrime/securesms/scribbles/ImageEditorFragment.java index 39b75c7a82..d2962b6d0c 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/scribbles/ImageEditorFragment.java +++ b/app/src/main/java/org/thoughtcrime/securesms/scribbles/ImageEditorFragment.java @@ -12,6 +12,8 @@ import android.view.View; import android.view.ViewGroup; import network.loki.messenger.R; + +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.thoughtcrime.securesms.imageeditor.ColorableRenderer; import org.thoughtcrime.securesms.imageeditor.ImageEditorView; import org.thoughtcrime.securesms.imageeditor.Renderer; @@ -209,7 +211,7 @@ public final class ImageEditorFragment extends Fragment implements ImageEditorHu } private void startTextEntityEditing(@NonNull EditorElement textElement, boolean selectAll) { - imageEditorView.startTextEditing(textElement, TextSecurePreferences.isIncognitoKeyboardEnabled(requireContext()), selectAll); + imageEditorView.startTextEditing(textElement, MessagingModuleConfiguration.getShared().getPrefs().isIncognitoKeyboardEnabled(), selectAll); } protected void addText() { diff --git a/app/src/main/java/org/thoughtcrime/securesms/search/SearchRepository.java b/app/src/main/java/org/thoughtcrime/securesms/search/SearchRepository.java index 204b63f802..83119e090b 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/search/SearchRepository.java +++ b/app/src/main/java/org/thoughtcrime/securesms/search/SearchRepository.java @@ -6,6 +6,8 @@ import android.database.DatabaseUtils; import android.database.MergeCursor; import androidx.annotation.NonNull; import com.annimon.stream.Stream; + +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.session.libsession.messaging.contacts.Contact; import org.session.libsession.utilities.Address; import org.session.libsession.utilities.GroupRecord; @@ -137,7 +139,7 @@ public class SearchRepository { private CursorList queryConversations(@NonNull String query, List matchingAddresses) { List numbers = contactAccessor.getNumbersForThreadSearchFilter(context, query); - String localUserNumber = TextSecurePreferences.getLocalNumber(context); + String localUserNumber = MessagingModuleConfiguration.getShared().getPrefs().getLocalNumber(); if (localUserNumber != null) { matchingAddresses.remove(localUserNumber); } diff --git a/app/src/main/java/org/thoughtcrime/securesms/service/ExpiringMessageManager.kt b/app/src/main/java/org/thoughtcrime/securesms/service/ExpiringMessageManager.kt index 2f6ad7fd8b..546c6eb931 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/service/ExpiringMessageManager.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/service/ExpiringMessageManager.kt @@ -3,7 +3,7 @@ package org.thoughtcrime.securesms.service import android.content.Context import network.loki.messenger.libsession_util.util.ExpiryMode import network.loki.messenger.libsession_util.util.ExpiryMode.AfterSend -import org.session.libsession.messaging.MessagingModuleConfiguration.Companion.shared +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.messaging.messages.control.ExpirationTimerUpdate import org.session.libsession.messaging.messages.signal.IncomingMediaMessage import org.session.libsession.messaging.messages.signal.OutgoingExpirationUpdateMessage @@ -12,7 +12,7 @@ import org.session.libsession.utilities.Address.Companion.fromSerialized import org.session.libsession.utilities.GroupUtil.doubleEncodeGroupID import org.session.libsession.utilities.GroupUtil.getDecodedGroupIDAsData import org.session.libsession.utilities.SSKEnvironment.MessageExpirationManagerProtocol -import org.session.libsession.utilities.TextSecurePreferences.Companion.getLocalNumber +import org.session.libsession.utilities.prefs import org.session.libsession.utilities.recipients.Recipient import org.session.libsignal.messages.SignalServiceGroup import org.session.libsignal.utilities.Log @@ -87,7 +87,7 @@ class ExpiringMessageManager(context: Context) : MessageExpirationManagerProtoco val groupAddress = fromSerialized(groupID) recipient = Recipient.from(context, groupAddress, false) } - val threadId = shared.storage.getThreadId(recipient) ?: return + val threadId = MessagingModuleConfiguration.shared.storage.getThreadId(recipient) ?: return val mediaMessage = IncomingMediaMessage( address, sentTimestamp!!, -1, expiresInMillis, expireStartedAt, true, @@ -125,7 +125,7 @@ class ExpiringMessageManager(context: Context) : MessageExpirationManagerProtoco val address = fromSerialized(serializedAddress) val recipient = Recipient.from(context, address, false) - message.threadID = shared.storage.getOrCreateThreadIdFor(address) + message.threadID = MessagingModuleConfiguration.shared.storage.getOrCreateThreadIdFor(address) val timerUpdateMessage = OutgoingExpirationUpdateMessage( recipient, sentTimestamp!!, @@ -149,7 +149,7 @@ class ExpiringMessageManager(context: Context) : MessageExpirationManagerProtoco override fun insertExpirationTimerMessage(message: ExpirationTimerUpdate) { val expiryMode: ExpiryMode = message.expiryMode - val userPublicKey = getLocalNumber(context) + val userPublicKey = context.prefs.getLocalNumber() val senderPublicKey = message.sender val sentTimestamp = message.sentTimestamp ?: 0 val expireStartedAt = if ((expiryMode is AfterSend || message.isSenderSelf) && !message.isGroup) sentTimestamp else 0 diff --git a/app/src/main/java/org/thoughtcrime/securesms/service/KeyCachingService.java b/app/src/main/java/org/thoughtcrime/securesms/service/KeyCachingService.java index f919af7ad6..e0f03c47d1 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/service/KeyCachingService.java +++ b/app/src/main/java/org/thoughtcrime/securesms/service/KeyCachingService.java @@ -16,6 +16,8 @@ */ package org.thoughtcrime.securesms.service; +import static org.session.libsession.utilities.TextSecurePreferencesKt.getPrefs; + import android.annotation.SuppressLint; import android.app.AlarmManager; import android.app.Notification; @@ -38,6 +40,7 @@ import androidx.core.app.NotificationCompat; import org.session.libsession.utilities.ServiceUtil; import org.session.libsession.utilities.TextSecurePreferences; +import org.session.libsession.utilities.TextSecurePreferencesKt; import org.session.libsignal.utilities.Log; import org.thoughtcrime.securesms.ApplicationContext; import org.thoughtcrime.securesms.DatabaseUpgradeActivity; @@ -68,12 +71,13 @@ public class KeyCachingService extends Service { private static final String PASSPHRASE_EXPIRED_EVENT = "org.thoughtcrime.securesms.service.action.PASSPHRASE_EXPIRED_EVENT"; public static final String CLEAR_KEY_ACTION = "org.thoughtcrime.securesms.service.action.CLEAR_KEY"; - private final IBinder binder = new KeySetBinder(); - // AC: This is a temporal drop off replacement for the refactoring time being. // This field only indicates if the app was unlocked or not (null means locked). private static Object masterSecret = null; + private final IBinder binder = new KeySetBinder(); + private final TextSecurePreferences prefs = getPrefs(this); + /** * A temporal utility method to quickly call {@link KeyCachingService#setMasterSecret(Object)} * without explicitly binding to the service. @@ -100,7 +104,9 @@ public class KeyCachingService extends Service { public KeyCachingService() {} public static synchronized boolean isLocked(Context context) { - boolean enabled = !TextSecurePreferences.isPasswordDisabled(context) || TextSecurePreferences.isScreenLockEnabled(context); + TextSecurePreferences prefs = ApplicationContext.getInstance(context).getPrefs(); + + boolean enabled = !prefs.isPasswordDisabled() || prefs.isScreenLockEnabled(); return getMasterSecret(context) == null && enabled; } @@ -156,7 +162,7 @@ public class KeyCachingService extends Service { Log.i(TAG, "onCreate()"); super.onCreate(); - if (TextSecurePreferences.isPasswordDisabled(this) && !TextSecurePreferences.isScreenLockEnabled(this)) { + if (prefs.isPasswordDisabled() && !prefs.isScreenLockEnabled()) { setMasterSecret(new Object()); } } @@ -205,22 +211,24 @@ public class KeyCachingService extends Service { } private static void startTimeoutIfAppropriate(@NonNull Context context) { + TextSecurePreferences prefs = ApplicationContext.getInstance(context).getPrefs(); + boolean appVisible = ApplicationContext.getInstance(context).isAppVisible(); boolean secretSet = KeyCachingService.masterSecret != null; - boolean timeoutEnabled = TextSecurePreferences.isPassphraseTimeoutEnabled(context); - boolean passLockActive = timeoutEnabled && !TextSecurePreferences.isPasswordDisabled(context); + boolean timeoutEnabled = prefs.isPassphraseTimeoutEnabled(); + boolean passLockActive = timeoutEnabled && !prefs.isPasswordDisabled(); - long screenTimeout = TextSecurePreferences.getScreenLockTimeout(context); - boolean screenLockActive = screenTimeout >= 0 && TextSecurePreferences.isScreenLockEnabled(context); + long screenTimeout = prefs.getScreenLockTimeout(); + boolean screenLockActive = screenTimeout >= 0 && prefs.isScreenLockEnabled(); if (!appVisible && secretSet && (passLockActive || screenLockActive)) { - long passphraseTimeoutMinutes = TextSecurePreferences.getPassphraseTimeoutInterval(context); - long screenLockTimeoutSeconds = TextSecurePreferences.getScreenLockTimeout(context); + long passphraseTimeoutMinutes = prefs.getPassphraseTimeoutInterval(); + long screenLockTimeoutSeconds = prefs.getScreenLockTimeout(); long timeoutMillis; - if (!TextSecurePreferences.isPasswordDisabled(context)) timeoutMillis = TimeUnit.MINUTES.toMillis(passphraseTimeoutMinutes); + if (!prefs.isPasswordDisabled()) timeoutMillis = TimeUnit.MINUTES.toMillis(passphraseTimeoutMinutes); else timeoutMillis = TimeUnit.SECONDS.toMillis(screenLockTimeoutSeconds); Log.i(TAG, "Starting timeout: " + timeoutMillis); @@ -234,7 +242,7 @@ public class KeyCachingService extends Service { } private void foregroundService() { - if (TextSecurePreferences.isPasswordDisabled(this) && !TextSecurePreferences.isScreenLockEnabled(this)) { + if (prefs.isPasswordDisabled() && !prefs.isScreenLockEnabled()) { stopForeground(true); return; } diff --git a/app/src/main/java/org/thoughtcrime/securesms/service/PanicResponderListener.java b/app/src/main/java/org/thoughtcrime/securesms/service/PanicResponderListener.java index a23544d570..77db93111d 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/service/PanicResponderListener.java +++ b/app/src/main/java/org/thoughtcrime/securesms/service/PanicResponderListener.java @@ -6,6 +6,8 @@ import android.content.Intent; import android.os.Build; import org.session.libsession.utilities.TextSecurePreferences; +import org.session.libsession.utilities.TextSecurePreferencesKt; +import org.thoughtcrime.securesms.ApplicationContext; /** * Respond to a PanicKit trigger Intent by locking the app. PanicKit provides a @@ -18,7 +20,8 @@ public class PanicResponderListener extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { - if (intent != null && !TextSecurePreferences.isPasswordDisabled(context) && + TextSecurePreferences prefs = ApplicationContext.getInstance(context).getPrefs(); + if (intent != null && !prefs.isPasswordDisabled() && "info.guardianproject.panic.action.TRIGGER".equals(intent.getAction())) { Intent lockIntent = new Intent(context, KeyCachingService.class); diff --git a/app/src/main/java/org/thoughtcrime/securesms/service/UpdateApkReadyListener.java b/app/src/main/java/org/thoughtcrime/securesms/service/UpdateApkReadyListener.java index eea6ba00f8..b764cc3d3c 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/service/UpdateApkReadyListener.java +++ b/app/src/main/java/org/thoughtcrime/securesms/service/UpdateApkReadyListener.java @@ -13,6 +13,7 @@ import android.net.Uri; import androidx.annotation.Nullable; import androidx.core.app.NotificationCompat; +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.session.libsession.utilities.FileUtils; import org.session.libsession.utilities.ServiceUtil; import org.session.libsession.utilities.TextSecurePreferences; @@ -39,9 +40,9 @@ public class UpdateApkReadyListener extends BroadcastReceiver { if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())) { long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -2); - if (downloadId == TextSecurePreferences.getUpdateApkDownloadId(context)) { + if (downloadId == MessagingModuleConfiguration.getShared().getPrefs().getUpdateApkDownloadId()) { Uri uri = getLocalUriForDownloadId(context, downloadId); - String encodedDigest = TextSecurePreferences.getUpdateApkDigest(context); + String encodedDigest = MessagingModuleConfiguration.getShared().getPrefs().getUpdateApkDigest(); if (uri == null) { Log.w(TAG, "Downloaded local URI is null?"); diff --git a/app/src/main/java/org/thoughtcrime/securesms/sskenvironment/ProfileManager.kt b/app/src/main/java/org/thoughtcrime/securesms/sskenvironment/ProfileManager.kt index 18127b0040..b6ae2bee50 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/sskenvironment/ProfileManager.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/sskenvironment/ProfileManager.kt @@ -2,12 +2,14 @@ package org.thoughtcrime.securesms.sskenvironment import android.content.Context import network.loki.messenger.libsession_util.util.UserPic +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.messaging.contacts.Contact import org.session.libsession.messaging.jobs.JobQueue import org.session.libsession.messaging.jobs.RetrieveProfileAvatarJob import org.session.libsession.messaging.utilities.AccountId import org.session.libsession.utilities.SSKEnvironment import org.session.libsession.utilities.TextSecurePreferences +import org.session.libsession.utilities.prefs import org.session.libsession.utilities.recipients.Recipient import org.session.libsignal.utilities.IdPrefix import org.thoughtcrime.securesms.dependencies.ConfigFactory @@ -91,7 +93,7 @@ class ProfileManager(private val context: Context, private val configFactory: Co override fun contactUpdatedInternal(contact: Contact): String? { val contactConfig = configFactory.contacts ?: return null - if (contact.accountID == TextSecurePreferences.getLocalNumber(context)) return null + if (contact.accountID == context.prefs.getLocalNumber()) return null val sessionId = AccountId(contact.accountID) if (sessionId.prefix != IdPrefix.STANDARD) return null // only internally store standard session IDs contactConfig.upsertContact(contact.accountID) { diff --git a/app/src/main/java/org/thoughtcrime/securesms/sskenvironment/ReadReceiptManager.kt b/app/src/main/java/org/thoughtcrime/securesms/sskenvironment/ReadReceiptManager.kt index bdf42f0e46..f8f58dc3c2 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/sskenvironment/ReadReceiptManager.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/sskenvironment/ReadReceiptManager.kt @@ -1,9 +1,11 @@ package org.thoughtcrime.securesms.sskenvironment import android.content.Context +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.utilities.Address import org.session.libsession.utilities.SSKEnvironment import org.session.libsession.utilities.TextSecurePreferences +import org.session.libsession.utilities.prefs import org.session.libsignal.utilities.Log import org.thoughtcrime.securesms.database.MessagingDatabase.SyncMessageId import org.thoughtcrime.securesms.dependencies.DatabaseComponent @@ -11,7 +13,7 @@ import org.thoughtcrime.securesms.dependencies.DatabaseComponent class ReadReceiptManager: SSKEnvironment.ReadReceiptManagerProtocol { override fun processReadReceipts(context: Context, fromRecipientId: String, sentTimestamps: List, readTimestamp: Long) { - if (TextSecurePreferences.isReadReceiptsEnabled(context)) { + if (context.prefs.isReadReceiptsEnabled()) { // Redirect message to master device conversation var address = Address.fromSerialized(fromRecipientId) diff --git a/app/src/main/java/org/thoughtcrime/securesms/sskenvironment/TypingStatusRepository.java b/app/src/main/java/org/thoughtcrime/securesms/sskenvironment/TypingStatusRepository.java index a18ad8211f..6f190494cf 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/sskenvironment/TypingStatusRepository.java +++ b/app/src/main/java/org/thoughtcrime/securesms/sskenvironment/TypingStatusRepository.java @@ -11,6 +11,7 @@ import com.annimon.stream.Collectors; import com.annimon.stream.Stream; import org.jetbrains.annotations.NotNull; +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.session.libsession.utilities.Address; import org.session.libsession.utilities.SSKEnvironment; import org.session.libsession.utilities.TextSecurePreferences; @@ -48,7 +49,7 @@ public class TypingStatusRepository implements SSKEnvironment.TypingIndicatorsPr @Override public synchronized void didReceiveTypingStartedMessage(@NotNull Context context, long threadId, @NotNull Address author, int device) { - if (author.serialize().equals(TextSecurePreferences.getLocalNumber(context))) { + if (author.serialize().equals(MessagingModuleConfiguration.getShared().getPrefs().getLocalNumber())) { return; } @@ -77,7 +78,7 @@ public class TypingStatusRepository implements SSKEnvironment.TypingIndicatorsPr @Override public synchronized void didReceiveTypingStoppedMessage(@NotNull Context context, long threadId, @NotNull Address author, int device, boolean isReplacedByIncomingMessage) { - if (author.serialize().equals(TextSecurePreferences.getLocalNumber(context))) { + if (author.serialize().equals(MessagingModuleConfiguration.getShared().getPrefs().getLocalNumber())) { return; } diff --git a/app/src/main/java/org/thoughtcrime/securesms/ui/color/ColorsFromPreferences.kt b/app/src/main/java/org/thoughtcrime/securesms/ui/color/ColorsFromPreferences.kt index a65c08cba0..24e072e337 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/ui/color/ColorsFromPreferences.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/ui/color/ColorsFromPreferences.kt @@ -2,6 +2,7 @@ package org.thoughtcrime.securesms.ui.color import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.utilities.TextSecurePreferences import org.session.libsession.utilities.TextSecurePreferences.Companion.BLUE_ACCENT import org.session.libsession.utilities.TextSecurePreferences.Companion.CLASSIC_DARK diff --git a/app/src/main/java/org/thoughtcrime/securesms/util/AttachmentUtil.java b/app/src/main/java/org/thoughtcrime/securesms/util/AttachmentUtil.java index bda23c0377..987857d83f 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/util/AttachmentUtil.java +++ b/app/src/main/java/org/thoughtcrime/securesms/util/AttachmentUtil.java @@ -10,6 +10,7 @@ import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.WorkerThread; +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.session.libsession.messaging.sending_receiving.attachments.AttachmentId; import org.session.libsession.messaging.sending_receiving.attachments.DatabaseAttachment; import org.session.libsession.utilities.ServiceUtil; @@ -79,9 +80,9 @@ public class AttachmentUtil { } private static @NonNull Set getAllowedAutoDownloadTypes(@NonNull Context context) { - if (isConnectedWifi(context)) return TextSecurePreferences.getWifiMediaDownloadAllowed(context); - else if (isConnectedRoaming(context)) return TextSecurePreferences.getRoamingMediaDownloadAllowed(context); - else if (isConnectedMobile(context)) return TextSecurePreferences.getMobileMediaDownloadAllowed(context); + if (isConnectedWifi(context)) return MessagingModuleConfiguration.getShared().getPrefs().getWifiMediaDownloadAllowed(); + else if (isConnectedRoaming(context)) return MessagingModuleConfiguration.getShared().getPrefs().getRoamingMediaDownloadAllowed(); + else if (isConnectedMobile(context)) return MessagingModuleConfiguration.getShared().getPrefs().getMobileMediaDownloadAllowed(); else return Collections.emptySet(); } diff --git a/app/src/main/java/org/thoughtcrime/securesms/util/ConfigurationMessageUtilities.kt b/app/src/main/java/org/thoughtcrime/securesms/util/ConfigurationMessageUtilities.kt index 94dbcf7d1f..fee5faafc9 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/util/ConfigurationMessageUtilities.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/util/ConfigurationMessageUtilities.kt @@ -19,8 +19,8 @@ import org.session.libsession.messaging.messages.Destination import org.session.libsession.messaging.messages.control.ConfigurationMessage import org.session.libsession.utilities.Address import org.session.libsession.utilities.GroupUtil -import org.session.libsession.utilities.TextSecurePreferences import org.session.libsession.utilities.WindowDebouncer +import org.session.libsession.utilities.prefs import org.session.libsignal.crypto.ecc.DjbECPublicKey import org.session.libsignal.utilities.Hex import org.session.libsignal.utilities.IdPrefix @@ -52,13 +52,13 @@ object ConfigurationMessageUtilities { @JvmStatic fun syncConfigurationIfNeeded(context: Context) { // add if check here to schedule new config job process and return early - val userPublicKey = TextSecurePreferences.getLocalNumber(context) ?: return + val userPublicKey = context.prefs.getLocalNumber() ?: return scheduleConfigSync(userPublicKey) } fun forceSyncConfigurationNowIfNeeded(context: Context): Promise { // add if check here to schedule new config job process and return early - val userPublicKey = TextSecurePreferences.getLocalNumber(context) ?: return Promise.ofFail(NullPointerException("User Public Key is null")) + val userPublicKey = context.prefs.getLocalNumber() ?: return Promise.ofFail(NullPointerException("User Public Key is null")) // schedule job if none exist // don't schedule job if we already have one scheduleConfigSync(userPublicKey) diff --git a/app/src/main/java/org/thoughtcrime/securesms/util/VersionTracker.kt b/app/src/main/java/org/thoughtcrime/securesms/util/VersionTracker.kt index 222b9b7fc8..f705140bef 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/util/VersionTracker.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/util/VersionTracker.kt @@ -1,16 +1,16 @@ package org.thoughtcrime.securesms.util import android.content.Context +import org.session.libsession.messaging.MessagingModuleConfiguration +import org.session.libsession.utilities.prefs import java.io.IOException import java.lang.RuntimeException -import org.session.libsession.utilities.TextSecurePreferences - object VersionTracker { @JvmStatic fun getLastSeenVersion(context: Context): Int { - var version = TextSecurePreferences.getLastVersionCode(context) + var version = context.prefs.getLastVersionCode() // Zero means the app is freshly installed = user is actually on the current version. if (version == 0) { version = updateLastSeenVersion(context) @@ -22,7 +22,7 @@ object VersionTracker { fun updateLastSeenVersion(context: Context): Int { return try { val currentVersionCode = Util.getCanonicalVersionCode() - TextSecurePreferences.setLastVersionCode(context, currentVersionCode) + context.prefs.setLastVersionCode(currentVersionCode) currentVersionCode } catch (e: IOException) { throw RuntimeException("Failed to update the last seen app version.", e) diff --git a/libsession/src/main/java/org/session/libsession/messaging/MessagingModuleConfiguration.kt b/libsession/src/main/java/org/session/libsession/messaging/MessagingModuleConfiguration.kt index e4f15b2114..823416f8ca 100644 --- a/libsession/src/main/java/org/session/libsession/messaging/MessagingModuleConfiguration.kt +++ b/libsession/src/main/java/org/session/libsession/messaging/MessagingModuleConfiguration.kt @@ -1,11 +1,13 @@ package org.session.libsession.messaging +import android.annotation.SuppressLint import android.content.Context import com.goterl.lazysodium.utils.KeyPair import org.session.libsession.database.MessageDataProvider import org.session.libsession.database.StorageProtocol import org.session.libsession.utilities.ConfigFactoryProtocol import org.session.libsession.utilities.Device +import org.session.libsession.utilities.prefs class MessagingModuleConfiguration( val context: Context, @@ -16,19 +18,11 @@ class MessagingModuleConfiguration( val configFactory: ConfigFactoryProtocol, val lastSentTimestampCache: LastSentTimestampCache ) { + val prefs get() = context.prefs companion object { + @SuppressLint("StaticFieldLeak") @JvmStatic - val shared: MessagingModuleConfiguration - get() = context.getSystemService(MESSAGING_MODULE_SERVICE) as MessagingModuleConfiguration - - const val MESSAGING_MODULE_SERVICE: String = "MessagingModuleConfiguration_MESSAGING_MODULE_SERVICE" - - private lateinit var context: Context - - @JvmStatic - fun configure(context: Context) { - this.context = context - } + lateinit var shared: MessagingModuleConfiguration } -} \ No newline at end of file +} diff --git a/libsession/src/main/java/org/session/libsession/messaging/jobs/RetrieveProfileAvatarJob.kt b/libsession/src/main/java/org/session/libsession/messaging/jobs/RetrieveProfileAvatarJob.kt index 9ca2534f66..dd9891d30a 100644 --- a/libsession/src/main/java/org/session/libsession/messaging/jobs/RetrieveProfileAvatarJob.kt +++ b/libsession/src/main/java/org/session/libsession/messaging/jobs/RetrieveProfileAvatarJob.kt @@ -5,10 +5,9 @@ import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.messaging.utilities.Data import org.session.libsession.utilities.Address import org.session.libsession.utilities.DownloadUtilities.downloadFile -import org.session.libsession.utilities.TextSecurePreferences.Companion.setProfileAvatarId -import org.session.libsession.utilities.TextSecurePreferences.Companion.setProfilePictureURL import org.session.libsession.utilities.Util.copy import org.session.libsession.utilities.Util.equals +import org.session.libsession.utilities.prefs import org.session.libsession.utilities.recipients.Recipient import org.session.libsignal.streams.ProfileCipherInputStream import org.session.libsignal.utilities.Log @@ -64,8 +63,8 @@ class RetrieveProfileAvatarJob(private val profileAvatar: String?, val recipient Log.w(TAG, "Removing profile avatar for: " + recipient.address.serialize()) if (recipient.isLocalNumber) { - setProfileAvatarId(context, SecureRandom().nextInt()) - setProfilePictureURL(context, null) + context.prefs.setProfileAvatarId(SecureRandom().nextInt()) + context.prefs.setProfilePictureURL(null) } AvatarHelper.delete(context, recipient.address) @@ -83,8 +82,8 @@ class RetrieveProfileAvatarJob(private val profileAvatar: String?, val recipient decryptDestination.renameTo(AvatarHelper.getAvatarFile(context, recipient.address)) if (recipient.isLocalNumber) { - setProfileAvatarId(context, SecureRandom().nextInt()) - setProfilePictureURL(context, profileAvatar) + context.prefs.setProfileAvatarId(SecureRandom().nextInt()) + context.prefs.setProfilePictureURL(profileAvatar) } storage.setProfileAvatar(recipient, profileAvatar) diff --git a/libsession/src/main/java/org/session/libsession/messaging/jobs/TrimThreadJob.kt b/libsession/src/main/java/org/session/libsession/messaging/jobs/TrimThreadJob.kt index cc388b0376..5426f3e6af 100644 --- a/libsession/src/main/java/org/session/libsession/messaging/jobs/TrimThreadJob.kt +++ b/libsession/src/main/java/org/session/libsession/messaging/jobs/TrimThreadJob.kt @@ -2,7 +2,7 @@ package org.session.libsession.messaging.jobs import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.messaging.utilities.Data -import org.session.libsession.utilities.TextSecurePreferences +import org.session.libsession.utilities.prefs class TrimThreadJob(val threadId: Long, val openGroupId: String?) : Job { override var delegate: JobDelegate? = null @@ -22,7 +22,7 @@ class TrimThreadJob(val threadId: Long, val openGroupId: String?) : Job { override suspend fun execute(dispatcherName: String) { val context = MessagingModuleConfiguration.shared.context - val trimmingEnabled = TextSecurePreferences.isThreadLengthTrimmingEnabled(context) + val trimmingEnabled = context.prefs.isThreadLengthTrimmingEnabled() val storage = MessagingModuleConfiguration.shared.storage val messageCount = storage.getMessageCount(threadId) if (trimmingEnabled && !openGroupId.isNullOrEmpty() && messageCount >= THREAD_LENGTH_TRIGGER_SIZE) { diff --git a/libsession/src/main/java/org/session/libsession/messaging/messages/control/ConfigurationMessage.kt b/libsession/src/main/java/org/session/libsession/messaging/messages/control/ConfigurationMessage.kt index 7544ff9c82..a1bbfd27ab 100644 --- a/libsession/src/main/java/org/session/libsession/messaging/messages/control/ConfigurationMessage.kt +++ b/libsession/src/main/java/org/session/libsession/messaging/messages/control/ConfigurationMessage.kt @@ -7,6 +7,7 @@ import org.session.libsession.utilities.Address import org.session.libsession.utilities.GroupUtil import org.session.libsession.utilities.ProfileKeyUtil import org.session.libsession.utilities.TextSecurePreferences +import org.session.libsession.utilities.prefs import org.session.libsignal.crypto.ecc.DjbECPrivateKey import org.session.libsignal.crypto.ecc.DjbECPublicKey import org.session.libsignal.crypto.ecc.ECKeyPair @@ -117,8 +118,9 @@ class ConfigurationMessage(var closedGroups: List, var openGroups: val sharedConfig = MessagingModuleConfiguration.shared val storage = sharedConfig.storage val context = sharedConfig.context - val displayName = TextSecurePreferences.getProfileName(context) ?: return null - val profilePicture = TextSecurePreferences.getProfilePictureURL(context) + val prefs = context.prefs + val displayName = prefs.getProfileName() ?: return null + val profilePicture = prefs.getProfilePictureURL() val profileKey = ProfileKeyUtil.getProfileKey(context) val groups = storage.getAllGroups(includeInactive = false) for (group in groups) { diff --git a/libsession/src/main/java/org/session/libsession/messaging/open_groups/OpenGroupApi.kt b/libsession/src/main/java/org/session/libsession/messaging/open_groups/OpenGroupApi.kt index 9e056e50bb..b2ec9c4b20 100644 --- a/libsession/src/main/java/org/session/libsession/messaging/open_groups/OpenGroupApi.kt +++ b/libsession/src/main/java/org/session/libsession/messaging/open_groups/OpenGroupApi.kt @@ -26,6 +26,7 @@ import org.session.libsession.snode.OnionRequestAPI import org.session.libsession.snode.OnionResponse import org.session.libsession.snode.SnodeAPI import org.session.libsession.utilities.TextSecurePreferences +import org.session.libsession.utilities.prefs import org.session.libsignal.utilities.Base64.decode import org.session.libsignal.utilities.Base64.encodeBytes import org.session.libsignal.utilities.HTTP @@ -50,8 +51,7 @@ object OpenGroupApi { private val hasPerformedInitialPoll = mutableMapOf() private var hasUpdatedLastOpenDate = false private val timeSinceLastOpen by lazy { - val context = MessagingModuleConfiguration.shared.context - val lastOpenDate = TextSecurePreferences.getLastOpenTimeDate(context) + val lastOpenDate = MessagingModuleConfiguration.shared.context.prefs.getLastOpenTimeDate() val now = System.currentTimeMillis() now - lastOpenDate } @@ -703,7 +703,7 @@ object OpenGroupApi { hasPerformedInitialPoll[server] = true if (!hasUpdatedLastOpenDate) { hasUpdatedLastOpenDate = true - TextSecurePreferences.setLastOpenDate(context) + context.prefs.setLastOpenDate() } val lastInboxMessageId = storage.getLastInboxMessageId(server) val lastOutboxMessageId = storage.getLastOutboxMessageId(server) diff --git a/libsession/src/main/java/org/session/libsession/messaging/sending_receiving/MessageSenderClosedGroupHandler.kt b/libsession/src/main/java/org/session/libsession/messaging/sending_receiving/MessageSenderClosedGroupHandler.kt index e30d58b939..85ec3e65a4 100644 --- a/libsession/src/main/java/org/session/libsession/messaging/sending_receiving/MessageSenderClosedGroupHandler.kt +++ b/libsession/src/main/java/org/session/libsession/messaging/sending_receiving/MessageSenderClosedGroupHandler.kt @@ -16,6 +16,7 @@ import org.session.libsession.utilities.Address.Companion.fromSerialized import org.session.libsession.utilities.Device import org.session.libsession.utilities.GroupUtil import org.session.libsession.utilities.TextSecurePreferences +import org.session.libsession.utilities.prefs import org.session.libsignal.crypto.ecc.Curve import org.session.libsignal.crypto.ecc.ECKeyPair import org.session.libsignal.messages.SignalServiceGroup @@ -240,7 +241,7 @@ fun MessageSender.leave(groupPublicKey: String, notifyUser: Boolean = true): Pro ThreadUtils.queue { val context = MessagingModuleConfiguration.shared.context val storage = MessagingModuleConfiguration.shared.storage - val userPublicKey = TextSecurePreferences.getLocalNumber(context)!! + val userPublicKey = context.prefs.getLocalNumber()!! val groupID = GroupUtil.doubleEncodeGroupID(groupPublicKey) val group = storage.getGroup(groupID) ?: return@queue deferred.reject(Error.NoThread) val updatedMembers = group.members.map { it.serialize() }.toSet() - userPublicKey diff --git a/libsession/src/main/java/org/session/libsession/messaging/sending_receiving/ReceivedMessageHandler.kt b/libsession/src/main/java/org/session/libsession/messaging/sending_receiving/ReceivedMessageHandler.kt index 7bc47931d6..47b847aca9 100644 --- a/libsession/src/main/java/org/session/libsession/messaging/sending_receiving/ReceivedMessageHandler.kt +++ b/libsession/src/main/java/org/session/libsession/messaging/sending_receiving/ReceivedMessageHandler.kt @@ -1,7 +1,6 @@ package org.session.libsession.messaging.sending_receiving import android.text.TextUtils -import network.loki.messenger.libsession_util.ConfigBase import network.loki.messenger.libsession_util.util.ExpiryMode import org.session.libsession.avatars.AvatarHelper import org.session.libsession.messaging.MessagingModuleConfiguration @@ -41,6 +40,7 @@ import org.session.libsession.utilities.GroupUtil.doubleEncodeGroupID import org.session.libsession.utilities.ProfileKeyUtil import org.session.libsession.utilities.SSKEnvironment import org.session.libsession.utilities.TextSecurePreferences +import org.session.libsession.utilities.prefs import org.session.libsession.utilities.recipients.Recipient import org.session.libsignal.crypto.ecc.DjbECPrivateKey import org.session.libsignal.crypto.ecc.DjbECPublicKey @@ -194,17 +194,18 @@ private fun MessageReceiver.handleDataExtractionNotification(message: DataExtrac private fun handleConfigurationMessage(message: ConfigurationMessage) { val context = MessagingModuleConfiguration.shared.context val storage = MessagingModuleConfiguration.shared.storage - if (TextSecurePreferences.getConfigurationMessageSynced(context) - && !TextSecurePreferences.shouldUpdateProfile(context, message.sentTimestamp!!)) return + val prefs = context.prefs + if (prefs.getConfigurationMessageSynced() + && !prefs.shouldUpdateProfile(message.sentTimestamp!!)) return val userPublicKey = storage.getUserPublicKey() if (userPublicKey == null || message.sender != storage.getUserPublicKey()) return - val firstTimeSync = !TextSecurePreferences.getConfigurationMessageSynced(context) + val firstTimeSync = !prefs.getConfigurationMessageSynced() - TextSecurePreferences.setConfigurationMessageSynced(context, true) - TextSecurePreferences.setLastProfileUpdateTime(context, message.sentTimestamp!!) + prefs.setConfigurationMessageSynced(true) + prefs.setLastProfileUpdateTime(message.sentTimestamp!!) - TextSecurePreferences.setHasLegacyConfig(context, true) + prefs.setHasLegacyConfig(true) if (!firstTimeSync) return val allClosedGroupPublicKeys = storage.getAllClosedGroupPublicKeys() @@ -233,11 +234,11 @@ private fun handleConfigurationMessage(message: ConfigurationMessage) { val profileManager = SSKEnvironment.shared.profileManager val recipient = Recipient.from(context, Address.fromSerialized(userPublicKey), false) if (message.displayName.isNotEmpty()) { - TextSecurePreferences.setProfileName(context, message.displayName) + prefs.setProfileName(message.displayName) profileManager.setName(context, recipient, message.displayName) } if (message.profileKey.isNotEmpty() && !message.profilePicture.isNullOrEmpty() - && TextSecurePreferences.getProfilePictureURL(context) != message.profilePicture) { + && prefs.getProfilePictureURL() != message.profilePicture) { val profileKey = Base64.encodeBytes(message.profileKey) ProfileKeyUtil.setEncodedProfileKey(context, profileKey) profileManager.setProfilePicture(context, recipient, message.profilePicture, message.profileKey) @@ -641,7 +642,7 @@ private fun MessageReceiver.handleClosedGroupEncryptionKeyPair(message: ClosedGr private fun MessageReceiver.handleClosedGroupNameChanged(message: ClosedGroupControlMessage) { val context = MessagingModuleConfiguration.shared.context val storage = MessagingModuleConfiguration.shared.storage - val userPublicKey = TextSecurePreferences.getLocalNumber(context) + val userPublicKey = context.prefs.getLocalNumber() val senderPublicKey = message.sender ?: return val kind = message.kind!! as? ClosedGroupControlMessage.Kind.NameChange ?: return val groupPublicKey = message.groupPublicKey ?: return diff --git a/libsession/src/main/java/org/session/libsession/messaging/sending_receiving/notifications/PushRegistryV1.kt b/libsession/src/main/java/org/session/libsession/messaging/sending_receiving/notifications/PushRegistryV1.kt index 1599dd93d5..70f7ac80f3 100644 --- a/libsession/src/main/java/org/session/libsession/messaging/sending_receiving/notifications/PushRegistryV1.kt +++ b/libsession/src/main/java/org/session/libsession/messaging/sending_receiving/notifications/PushRegistryV1.kt @@ -11,6 +11,7 @@ import org.session.libsession.snode.OnionResponse import org.session.libsession.snode.Version import org.session.libsession.utilities.Device import org.session.libsession.utilities.TextSecurePreferences +import org.session.libsession.utilities.prefs import org.session.libsignal.utilities.JsonUtil import org.session.libsignal.utilities.Log import org.session.libsignal.utilities.emptyPromise @@ -28,9 +29,9 @@ object PushRegistryV1 { fun register( device: Device, - isPushEnabled: Boolean = TextSecurePreferences.isPushEnabled(context), - token: String? = TextSecurePreferences.getPushToken(context), - publicKey: String? = TextSecurePreferences.getLocalNumber(context), + isPushEnabled: Boolean = context.prefs.isPushEnabled(), + token: String? = context.prefs.getPushToken(), + publicKey: String? = context.prefs.getLocalNumber(), legacyGroupPublicKeys: Collection = MessagingModuleConfiguration.shared.storage.getAllClosedGroupPublicKeys() ): Promise<*, Exception> = when { isPushEnabled -> retryIfNeeded(maxRetryCount) { @@ -78,7 +79,7 @@ object PushRegistryV1 { fun unregister(): Promise<*, Exception> { Log.d(TAG, "unregisterV1 requested") - val token = TextSecurePreferences.getPushToken(context) ?: emptyPromise() + val token = context.prefs.getPushToken() ?: emptyPromise() return retryIfNeeded(maxRetryCount) { val parameters = mapOf("token" to token) @@ -99,7 +100,7 @@ object PushRegistryV1 { fun subscribeGroup( closedGroupPublicKey: String, - isPushEnabled: Boolean = TextSecurePreferences.isPushEnabled(context), + isPushEnabled: Boolean = context.prefs.isPushEnabled(), publicKey: String = MessagingModuleConfiguration.shared.storage.getUserPublicKey()!! ) = if (isPushEnabled) { performGroupOperation("subscribe_closed_group", closedGroupPublicKey, publicKey) @@ -107,7 +108,7 @@ object PushRegistryV1 { fun unsubscribeGroup( closedGroupPublicKey: String, - isPushEnabled: Boolean = TextSecurePreferences.isPushEnabled(context), + isPushEnabled: Boolean = context.prefs.isPushEnabled(), publicKey: String = MessagingModuleConfiguration.shared.storage.getUserPublicKey()!! ) = if (isPushEnabled) { performGroupOperation("unsubscribe_closed_group", closedGroupPublicKey, publicKey) diff --git a/libsession/src/main/java/org/session/libsession/utilities/ProfileKeyUtil.java b/libsession/src/main/java/org/session/libsession/utilities/ProfileKeyUtil.java index 4550965ae7..7d9f438f72 100644 --- a/libsession/src/main/java/org/session/libsession/utilities/ProfileKeyUtil.java +++ b/libsession/src/main/java/org/session/libsession/utilities/ProfileKeyUtil.java @@ -1,10 +1,13 @@ package org.session.libsession.utilities; +import static org.session.libsession.utilities.TextSecurePreferencesKt.getPrefs; + import android.content.Context; import androidx.annotation.NonNull; import androidx.annotation.Nullable; +import org.session.libsession.messaging.MessagingModuleConfiguration; import org.session.libsignal.utilities.Base64; import java.io.IOException; @@ -15,11 +18,11 @@ public class ProfileKeyUtil { public static synchronized @NonNull byte[] getProfileKey(@NonNull Context context) { try { - String encodedProfileKey = TextSecurePreferences.getProfileKey(context); + String encodedProfileKey = MessagingModuleConfiguration.getShared().getPrefs().getProfileKey(); if (encodedProfileKey == null) { encodedProfileKey = Util.getSecret(PROFILE_KEY_BYTES); - TextSecurePreferences.setProfileKey(context, encodedProfileKey); + MessagingModuleConfiguration.getShared().getPrefs().setProfileKey(encodedProfileKey); } return Base64.decode(encodedProfileKey); @@ -41,6 +44,6 @@ public class ProfileKeyUtil { } public static synchronized void setEncodedProfileKey(@NonNull Context context, @Nullable String key) { - TextSecurePreferences.setProfileKey(context, key); + MessagingModuleConfiguration.getShared().getPrefs().setProfileKey(key); } } diff --git a/libsession/src/main/java/org/session/libsession/utilities/ProfilePictureUtilities.kt b/libsession/src/main/java/org/session/libsession/utilities/ProfilePictureUtilities.kt index 38d8838c0e..9f61dbba0d 100644 --- a/libsession/src/main/java/org/session/libsession/utilities/ProfilePictureUtilities.kt +++ b/libsession/src/main/java/org/session/libsession/utilities/ProfilePictureUtilities.kt @@ -4,6 +4,7 @@ import android.content.Context import nl.komponents.kovenant.Promise import nl.komponents.kovenant.deferred import okio.Buffer +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsession.messaging.file_server.FileServerApi import org.session.libsignal.streams.ProfileCipherOutputStream import org.session.libsignal.utilities.ProfileAvatarData @@ -35,9 +36,9 @@ object ProfilePictureUtilities { } catch (e: Exception) { deferred.reject(e) } - TextSecurePreferences.setLastProfilePictureUpload(context, Date().time) + context.prefs.setLastProfilePictureUpload(Date().time) val url = "${FileServerApi.server}/file/$id" - TextSecurePreferences.setProfilePictureURL(context, url) + context.prefs.setProfilePictureURL(url) deferred.resolve(Unit) } return deferred.promise diff --git a/libsession/src/main/java/org/session/libsession/utilities/TextSecurePreferences.kt b/libsession/src/main/java/org/session/libsession/utilities/TextSecurePreferences.kt index f9d2283e48..f48a942c1f 100644 --- a/libsession/src/main/java/org/session/libsession/utilities/TextSecurePreferences.kt +++ b/libsession/src/main/java/org/session/libsession/utilities/TextSecurePreferences.kt @@ -1,6 +1,7 @@ package org.session.libsession.utilities import android.content.Context +import android.content.SharedPreferences import android.hardware.Camera import android.net.Uri import android.provider.Settings @@ -13,27 +14,61 @@ import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.asSharedFlow import org.session.libsession.R +import org.session.libsession.utilities.TextSecurePreferences.Companion.instance import org.session.libsignal.utilities.Log import java.io.IOException -import java.util.Arrays import java.util.Date import javax.inject.Inject import javax.inject.Singleton +/** + * Preference definition. + */ +class Pref( + val name: String, + val default: T, + private val get: SharedPreferences.(String, T) -> T, + private val set: SharedPreferences.Editor.(String, T) -> SharedPreferences.Editor +) { + fun get(prefs: SharedPreferences) = prefs.get(name, default) + fun set(value: T, prefs: SharedPreferences) = prefs.edit().set(name, value).apply() +} + +fun Pref(name: String, default: Boolean) = Pref(name, default, SharedPreferences::getBoolean, SharedPreferences.Editor::putBoolean) +fun Pref(name: String, default: Int) = Pref(name, default, SharedPreferences::getInt, SharedPreferences.Editor::putInt) +fun Pref(name: String, default: Long) = Pref(name, default, SharedPreferences::getLong, SharedPreferences.Editor::putLong) +fun Pref(name: String, default: String) = Pref(name, default, SharedPreferences::getString, SharedPreferences.Editor::putStringOrRemove) +fun Pref(name: String) = Pref(name, null, SharedPreferences::getString, SharedPreferences.Editor::putStringOrRemove) + +private fun SharedPreferences.Editor.putStringOrRemove(name: String, value: String?) = value?.let { putString(name, it) } ?: run { remove(name) } + +operator fun SharedPreferences.get(pref: Pref): T = pref.get(this) +operator fun SharedPreferences.set(pref: Pref, value: T) = pref.set(value, this) + +val Context.prefs get() = instance ?: TextSecurePreferences(this).also { instance = it } + @Singleton class TextSecurePreferences @Inject constructor( @ApplicationContext private val context: Context ) { + val Context.prefs get() = TextSecurePreferences(this) + + private val sharedPreferences = getDefaultSharedPreferences(context) + + operator fun get(pref: Pref): T = sharedPreferences[pref] + companion object { val TAG = TextSecurePreferences::class.simpleName + var instance: TextSecurePreferences? = null + internal val _events = MutableSharedFlow(0, 64, BufferOverflow.DROP_OLDEST) val events get() = _events.asSharedFlow() @JvmStatic var pushSuffix = "" - const val DISABLE_PASSPHRASE_PREF = "pref_disable_passphrase" + val DISABLE_PASSPHRASE_PREF = Pref("pref_disable_passphrase", true) const val LANGUAGE_PREF = "pref_language" const val LAST_VERSION_CODE_PREF = "last_version_code" const val RINGTONE_PREF = "pref_key_ringtone" @@ -125,891 +160,353 @@ class TextSecurePreferences @Inject constructor( const val OCEAN_LIGHT = "ocean.light" const val ALLOW_MESSAGE_REQUESTS = "libsession.ALLOW_MESSAGE_REQUESTS" - - @JvmStatic - fun getConfigurationMessageSynced(context: Context): Boolean { - return getBooleanPreference(context, CONFIGURATION_SYNCED, false) - } - - @JvmStatic - fun setConfigurationMessageSynced(context: Context, value: Boolean) { - setBooleanPreference(context, CONFIGURATION_SYNCED, value) - _events.tryEmit(CONFIGURATION_SYNCED) - } - - @JvmStatic - fun isPushEnabled(context: Context): Boolean { - return getBooleanPreference(context, IS_PUSH_ENABLED, false) - } - - @JvmStatic - fun getPushToken(context: Context): String? { - return getStringPreference(context, PUSH_TOKEN, "") - } - - fun getPushRegisterTime(context: Context): Long { - return getLongPreference(context, PUSH_REGISTER_TIME, 0) - } - - fun setPushRegisterTime(context: Context, value: Long) { - setLongPreference(context, PUSH_REGISTER_TIME, value) - } - - // endregion - @JvmStatic - fun isScreenLockEnabled(context: Context): Boolean { - return getBooleanPreference(context, SCREEN_LOCK, false) - } - - @JvmStatic - fun setScreenLockEnabled(context: Context, value: Boolean) { - setBooleanPreference(context, SCREEN_LOCK, value) - } - - @JvmStatic - fun getScreenLockTimeout(context: Context): Long { - return getLongPreference(context, SCREEN_LOCK_TIMEOUT, 0) - } - - @JvmStatic - fun setScreenLockTimeout(context: Context, value: Long) { - setLongPreference(context, SCREEN_LOCK_TIMEOUT, value) - } - - @JvmStatic - fun setAttachmentEncryptedSecret(context: Context, secret: String) { - setStringPreference(context, ATTACHMENT_ENCRYPTED_SECRET, secret) - } - - @JvmStatic - fun setAttachmentUnencryptedSecret(context: Context, secret: String?) { - setStringPreference(context, ATTACHMENT_UNENCRYPTED_SECRET, secret) - } - - @JvmStatic - fun getAttachmentEncryptedSecret(context: Context): String? { - return getStringPreference(context, ATTACHMENT_ENCRYPTED_SECRET, null) - } - - @JvmStatic - fun getAttachmentUnencryptedSecret(context: Context): String? { - return getStringPreference(context, ATTACHMENT_UNENCRYPTED_SECRET, null) - } - - @JvmStatic - fun setDatabaseEncryptedSecret(context: Context, secret: String) { - setStringPreference(context, DATABASE_ENCRYPTED_SECRET, secret) - } - - @JvmStatic - fun setDatabaseUnencryptedSecret(context: Context, secret: String?) { - setStringPreference(context, DATABASE_UNENCRYPTED_SECRET, secret) - } - - @JvmStatic - fun getDatabaseUnencryptedSecret(context: Context): String? { - return getStringPreference(context, DATABASE_UNENCRYPTED_SECRET, null) - } - - @JvmStatic - fun getDatabaseEncryptedSecret(context: Context): String? { - return getStringPreference(context, DATABASE_ENCRYPTED_SECRET, null) - } - - @JvmStatic - fun isIncognitoKeyboardEnabled(context: Context): Boolean { - return getBooleanPreference(context, INCOGNITO_KEYBORAD_PREF, true) - } - - @JvmStatic - fun isReadReceiptsEnabled(context: Context): Boolean { - return getBooleanPreference(context, READ_RECEIPTS_PREF, false) - } - - fun setReadReceiptsEnabled(context: Context, enabled: Boolean) { - setBooleanPreference(context, READ_RECEIPTS_PREF, enabled) - } - - @JvmStatic - fun isTypingIndicatorsEnabled(context: Context): Boolean { - return getBooleanPreference(context, TYPING_INDICATORS, false) - } - - @JvmStatic - fun setTypingIndicatorsEnabled(context: Context, enabled: Boolean) { - setBooleanPreference(context, TYPING_INDICATORS, enabled) - } - - @JvmStatic - fun isLinkPreviewsEnabled(context: Context): Boolean { - return getBooleanPreference(context, LINK_PREVIEWS, false) - } - - @JvmStatic - fun setLinkPreviewsEnabled(context: Context, enabled: Boolean) { - setBooleanPreference(context, LINK_PREVIEWS, enabled) - } - - @JvmStatic - fun hasSeenGIFMetaDataWarning(context: Context): Boolean { - return getBooleanPreference(context, GIF_METADATA_WARNING, false) - } - - @JvmStatic - fun setHasSeenGIFMetaDataWarning(context: Context) { - setBooleanPreference(context, GIF_METADATA_WARNING, true) - } - - @JvmStatic - fun isGifSearchInGridLayout(context: Context): Boolean { - return getBooleanPreference(context, GIF_GRID_LAYOUT, false) - } - - @JvmStatic - fun setIsGifSearchInGridLayout(context: Context, isGrid: Boolean) { - setBooleanPreference(context, GIF_GRID_LAYOUT, isGrid) - } - - @JvmStatic - fun getProfileKey(context: Context): String? { - return getStringPreference(context, PROFILE_KEY_PREF, null) - } - - @JvmStatic - fun setProfileKey(context: Context, key: String?) { - setStringPreference(context, PROFILE_KEY_PREF, key) - } - - @JvmStatic - fun setProfileName(context: Context, name: String?) { - setStringPreference(context, PROFILE_NAME_PREF, name) - _events.tryEmit(PROFILE_NAME_PREF) - } - - @JvmStatic - fun getProfileName(context: Context): String? { - return getStringPreference(context, PROFILE_NAME_PREF, null) - } - - @JvmStatic - fun setProfileAvatarId(context: Context, id: Int) { - setIntegerPreference(context, PROFILE_AVATAR_ID_PREF, id) - } - - @JvmStatic - fun getProfileAvatarId(context: Context): Int { - return getIntegerPreference(context, PROFILE_AVATAR_ID_PREF, 0) - } - - fun setProfilePictureURL(context: Context, url: String?) { - setStringPreference(context, PROFILE_AVATAR_URL_PREF, url) - } - - @JvmStatic - fun getProfilePictureURL(context: Context): String? { - return getStringPreference(context, PROFILE_AVATAR_URL_PREF, null) - } - - @JvmStatic - fun getNotificationPriority(context: Context): Int { - return getStringPreference(context, NOTIFICATION_PRIORITY_PREF, NotificationCompat.PRIORITY_HIGH.toString())!!.toInt() - } - - @JvmStatic - fun getMessageBodyTextSize(context: Context): Int { - return getStringPreference(context, MESSAGE_BODY_TEXT_SIZE_PREF, "16")!!.toInt() - } - - @JvmStatic - fun setDirectCaptureCameraId(context: Context, value: Int) { - setIntegerPreference(context, DIRECT_CAPTURE_CAMERA_ID, value) - } - - @JvmStatic - fun getDirectCaptureCameraId(context: Context): Int { - return getIntegerPreference(context, DIRECT_CAPTURE_CAMERA_ID, Camera.CameraInfo.CAMERA_FACING_BACK) - } - - @JvmStatic - fun getNotificationPrivacy(context: Context): NotificationPrivacyPreference { - return NotificationPrivacyPreference(getStringPreference(context, NOTIFICATION_PRIVACY_PREF, "all")) - } - - @JvmStatic - fun getRepeatAlertsCount(context: Context): Int { - return try { - getStringPreference(context, REPEAT_ALERTS_PREF, "0")!!.toInt() - } catch (e: NumberFormatException) { - Log.w(TAG, e) - 0 - } - } - - fun getLocalRegistrationId(context: Context): Int { - return getIntegerPreference(context, LOCAL_REGISTRATION_ID_PREF, 0) - } - - fun setLocalRegistrationId(context: Context, registrationId: Int) { - setIntegerPreference(context, LOCAL_REGISTRATION_ID_PREF, registrationId) - } - - @JvmStatic - fun getUpdateApkDownloadId(context: Context): Long { - return getLongPreference(context, UPDATE_APK_DOWNLOAD_ID, -1) - } - - @JvmStatic - fun getUpdateApkDigest(context: Context): String? { - return getStringPreference(context, UPDATE_APK_DIGEST, null) - } - - @JvmStatic - fun getLocalNumber(context: Context): String? { - return getStringPreference(context, LOCAL_NUMBER_PREF, null) - } - - @JvmStatic - fun setHasLegacyConfig(context: Context, newValue: Boolean) { - setBooleanPreference(context, HAS_RECEIVED_LEGACY_CONFIG, newValue) - _events.tryEmit(HAS_RECEIVED_LEGACY_CONFIG) - } - - fun setLocalNumber(context: Context, localNumber: String) { - setStringPreference(context, LOCAL_NUMBER_PREF, localNumber.toLowerCase()) - } - - @JvmStatic - fun isEnterSendsEnabled(context: Context): Boolean { - return getBooleanPreference(context, ENTER_SENDS_PREF, false) - } - - @JvmStatic - fun isPasswordDisabled(context: Context): Boolean { - return getBooleanPreference(context, DISABLE_PASSPHRASE_PREF, true) - } - - fun setPasswordDisabled(context: Context, disabled: Boolean) { - setBooleanPreference(context, DISABLE_PASSPHRASE_PREF, disabled) - } - - @JvmStatic - fun isScreenSecurityEnabled(context: Context): Boolean { - return getBooleanPreference(context, SCREEN_SECURITY_PREF, context.resources.getBoolean(R.bool.screen_security_default)) - } - - fun getLastVersionCode(context: Context): Int { - return getIntegerPreference(context, LAST_VERSION_CODE_PREF, 0) - } - - @Throws(IOException::class) - fun setLastVersionCode(context: Context, versionCode: Int) { - if (!setIntegerPreferenceBlocking(context, LAST_VERSION_CODE_PREF, versionCode)) { - throw IOException("couldn't write version code to sharedpreferences") - } - } - - @JvmStatic - fun isPassphraseTimeoutEnabled(context: Context): Boolean { - return getBooleanPreference(context, PASSPHRASE_TIMEOUT_PREF, false) - } - - @JvmStatic - fun getPassphraseTimeoutInterval(context: Context): Int { - return getIntegerPreference(context, PASSPHRASE_TIMEOUT_INTERVAL_PREF, 5 * 60) - } - - @JvmStatic - fun getLanguage(context: Context): String? { - return getStringPreference(context, LANGUAGE_PREF, "zz") - } - - @JvmStatic - fun isNotificationsEnabled(context: Context): Boolean { - return getBooleanPreference(context, NOTIFICATION_PREF, true) - } - - @JvmStatic - fun getNotificationRingtone(context: Context): Uri { - var result = getStringPreference(context, RINGTONE_PREF, Settings.System.DEFAULT_NOTIFICATION_URI.toString()) - if (result != null && result.startsWith("file:")) { - result = Settings.System.DEFAULT_NOTIFICATION_URI.toString() - } - return Uri.parse(result) - } - - @JvmStatic - fun isNotificationVibrateEnabled(context: Context): Boolean { - return getBooleanPreference(context, VIBRATE_PREF, true) - } - - @JvmStatic - fun getNotificationLedColor(context: Context): Int { - return getIntegerPreference(context, LED_COLOR_PREF_PRIMARY, ThemeUtil.getThemedColor(context, R.attr.colorAccent)) - } - - @JvmStatic - fun isThreadLengthTrimmingEnabled(context: Context): Boolean { - return getBooleanPreference(context, THREAD_TRIM_ENABLED, true) - } - - @JvmStatic - fun isSystemEmojiPreferred(context: Context): Boolean { - return getBooleanPreference(context, SYSTEM_EMOJI_PREF, false) - } - - @JvmStatic - fun getMobileMediaDownloadAllowed(context: Context): Set? { - return getMediaDownloadAllowed(context, MEDIA_DOWNLOAD_MOBILE_PREF, R.array.pref_media_download_mobile_data_default) - } - - @JvmStatic - fun getWifiMediaDownloadAllowed(context: Context): Set? { - return getMediaDownloadAllowed(context, MEDIA_DOWNLOAD_WIFI_PREF, R.array.pref_media_download_wifi_default) - } - - @JvmStatic - fun getRoamingMediaDownloadAllowed(context: Context): Set? { - return getMediaDownloadAllowed(context, MEDIA_DOWNLOAD_ROAMING_PREF, R.array.pref_media_download_roaming_default) - } - - private fun getMediaDownloadAllowed(context: Context, key: String, @ArrayRes defaultValuesRes: Int): Set? { - return getStringSetPreference(context, key, HashSet(Arrays.asList(*context.resources.getStringArray(defaultValuesRes)))) - } - - @JvmStatic - fun getLogEncryptedSecret(context: Context): String? { - return getStringPreference(context, LOG_ENCRYPTED_SECRET, null) - } - - @JvmStatic - fun setLogEncryptedSecret(context: Context, base64Secret: String?) { - setStringPreference(context, LOG_ENCRYPTED_SECRET, base64Secret) - } - - @JvmStatic - fun getLogUnencryptedSecret(context: Context): String? { - return getStringPreference(context, LOG_UNENCRYPTED_SECRET, null) - } - - @JvmStatic - fun setLogUnencryptedSecret(context: Context, base64Secret: String?) { - setStringPreference(context, LOG_UNENCRYPTED_SECRET, base64Secret) - } - - @JvmStatic - fun getNotificationChannelVersion(context: Context): Int { - return getIntegerPreference(context, NOTIFICATION_CHANNEL_VERSION, 1) - } - - @JvmStatic - fun setNotificationChannelVersion(context: Context, version: Int) { - setIntegerPreference(context, NOTIFICATION_CHANNEL_VERSION, version) - } - - @JvmStatic - fun getNotificationMessagesChannelVersion(context: Context): Int { - return getIntegerPreference(context, NOTIFICATION_MESSAGES_CHANNEL_VERSION, 1) - } - - @JvmStatic - fun setNotificationMessagesChannelVersion(context: Context, version: Int) { - setIntegerPreference(context, NOTIFICATION_MESSAGES_CHANNEL_VERSION, version) - } - - @JvmStatic - fun hasForcedNewConfig(context: Context): Boolean { - return getBooleanPreference(context, HAS_FORCED_NEW_CONFIG, false) - } - - @JvmStatic - fun getBooleanPreference(context: Context, key: String?, defaultValue: Boolean): Boolean { - return getDefaultSharedPreferences(context).getBoolean(key, defaultValue) - } - - @JvmStatic - fun setBooleanPreference(context: Context, key: String?, value: Boolean) { - getDefaultSharedPreferences(context).edit().putBoolean(key, value).apply() - } - - @JvmStatic - fun getStringPreference(context: Context, key: String, defaultValue: String?): String? { - return getDefaultSharedPreferences(context).getString(key, defaultValue) - } - - @JvmStatic - fun setStringPreference(context: Context, key: String?, value: String?) { - getDefaultSharedPreferences(context).edit().putString(key, value).apply() - } - - fun getIntegerPreference(context: Context, key: String, defaultValue: Int): Int { - return getDefaultSharedPreferences(context).getInt(key, defaultValue) - } - - private fun setIntegerPreference(context: Context, key: String, value: Int) { - getDefaultSharedPreferences(context).edit().putInt(key, value).apply() - } - - private fun setIntegerPreferenceBlocking(context: Context, key: String, value: Int): Boolean { - return getDefaultSharedPreferences(context).edit().putInt(key, value).commit() - } - - private fun getLongPreference(context: Context, key: String, defaultValue: Long): Long { - return getDefaultSharedPreferences(context).getLong(key, defaultValue) - } - - private fun setLongPreference(context: Context, key: String, value: Long) { - getDefaultSharedPreferences(context).edit().putLong(key, value).apply() - } - - private fun removePreference(context: Context, key: String) { - getDefaultSharedPreferences(context).edit().remove(key).apply() - } - - private fun getStringSetPreference(context: Context, key: String, defaultValues: Set): Set? { - val prefs = getDefaultSharedPreferences(context) - return if (prefs.contains(key)) { - prefs.getStringSet(key, emptySet()) - } else { - defaultValues - } - } - - fun getHasViewedSeed(context: Context): Boolean { - return getBooleanPreference(context, "has_viewed_seed", false) - } - - fun setHasViewedSeed(context: Context, hasViewedSeed: Boolean) { - setBooleanPreference(context, "has_viewed_seed", hasViewedSeed) - } - - fun setRestorationTime(context: Context, time: Long) { - setLongPreference(context, "restoration_time", time) - } - - @JvmStatic - fun getLastProfilePictureUpload(context: Context): Long { - return getLongPreference(context, "last_profile_picture_upload", 0) - } - - @JvmStatic - fun setLastProfilePictureUpload(context: Context, newValue: Long) { - setLongPreference(context, "last_profile_picture_upload", newValue) - } - - fun getLastSnodePoolRefreshDate(context: Context?): Long { - return getLongPreference(context!!, "last_snode_pool_refresh_date", 0) - } - - fun setLastSnodePoolRefreshDate(context: Context?, date: Date) { - setLongPreference(context!!, "last_snode_pool_refresh_date", date.time) - } - - @JvmStatic - fun shouldUpdateProfile(context: Context, profileUpdateTime: Long): Boolean { - return profileUpdateTime > getLongPreference(context, LAST_PROFILE_UPDATE_TIME, 0) - } - - @JvmStatic - fun setLastProfileUpdateTime(context: Context, profileUpdateTime: Long) { - setLongPreference(context, LAST_PROFILE_UPDATE_TIME, profileUpdateTime) - } - - fun getLastOpenTimeDate(context: Context): Long { - return getLongPreference(context, LAST_OPEN_DATE, 0) - } - - fun setLastOpenDate(context: Context) { - setLongPreference(context, LAST_OPEN_DATE, System.currentTimeMillis()) - } - - @JvmStatic - fun hasHiddenMessageRequests(context: Context): Boolean { - return getBooleanPreference(context, HAS_HIDDEN_MESSAGE_REQUESTS, false) - } - - @JvmStatic - fun removeHasHiddenMessageRequests(context: Context) { - removePreference(context, HAS_HIDDEN_MESSAGE_REQUESTS) - } - - @JvmStatic - fun isCallNotificationsEnabled(context: Context): Boolean { - return getBooleanPreference(context, CALL_NOTIFICATIONS_ENABLED, false) - } - - @JvmStatic - fun getLastVacuumTime(context: Context): Long { - return getLongPreference(context, LAST_VACUUM_TIME, 0) - } - - @JvmStatic - fun setLastVacuumNow(context: Context) { - setLongPreference(context, LAST_VACUUM_TIME, System.currentTimeMillis()) - } - - @JvmStatic - fun getFingerprintKeyGenerated(context: Context): Boolean { - return getBooleanPreference(context, FINGERPRINT_KEY_GENERATED, false) - } - - @JvmStatic - fun setFingerprintKeyGenerated(context: Context) { - setBooleanPreference(context, FINGERPRINT_KEY_GENERATED, true) - } - - @JvmStatic - fun clearAll(context: Context) { - getDefaultSharedPreferences(context).edit().clear().commit() - } } fun getLastConfigurationSyncTime(): Long { - return getLongPreference(TextSecurePreferences.LAST_CONFIGURATION_SYNC_TIME, 0) + return getLongPreference(LAST_CONFIGURATION_SYNC_TIME, 0) } fun setLastConfigurationSyncTime(value: Long) { - setLongPreference(TextSecurePreferences.LAST_CONFIGURATION_SYNC_TIME, value) + setLongPreference(LAST_CONFIGURATION_SYNC_TIME, value) } fun getConfigurationMessageSynced(): Boolean { - return getBooleanPreference(TextSecurePreferences.CONFIGURATION_SYNCED, false) + return getBooleanPreference(CONFIGURATION_SYNCED, false) } fun setConfigurationMessageSynced(value: Boolean) { - setBooleanPreference(TextSecurePreferences.CONFIGURATION_SYNCED, value) - TextSecurePreferences._events.tryEmit(TextSecurePreferences.CONFIGURATION_SYNCED) + setBooleanPreference(CONFIGURATION_SYNCED, value) + _events.tryEmit(CONFIGURATION_SYNCED) } fun isPushEnabled(): Boolean { - return getBooleanPreference(TextSecurePreferences.IS_PUSH_ENABLED, false) + return getBooleanPreference(IS_PUSH_ENABLED, false) } fun setPushEnabled(value: Boolean) { - setBooleanPreference(TextSecurePreferences.IS_PUSH_ENABLED, value) + setBooleanPreference(IS_PUSH_ENABLED, value) } fun getPushToken(): String? { - return getStringPreference(TextSecurePreferences.PUSH_TOKEN, "") + return getStringPreference(PUSH_TOKEN, "") } fun setPushToken(value: String) { - setStringPreference(TextSecurePreferences.PUSH_TOKEN, value) + setStringPreference(PUSH_TOKEN, value) } fun getPushRegisterTime(): Long { - return getLongPreference(TextSecurePreferences.PUSH_REGISTER_TIME, 0) + return getLongPreference(PUSH_REGISTER_TIME, 0) } fun setPushRegisterTime(value: Long) { - setLongPreference(TextSecurePreferences.PUSH_REGISTER_TIME, value) + setLongPreference(PUSH_REGISTER_TIME, value) } fun isScreenLockEnabled(): Boolean { - return getBooleanPreference(TextSecurePreferences.SCREEN_LOCK, false) + return getBooleanPreference(SCREEN_LOCK, false) } fun setScreenLockEnabled(value: Boolean) { - setBooleanPreference(TextSecurePreferences.SCREEN_LOCK, value) + setBooleanPreference(SCREEN_LOCK, value) } fun getScreenLockTimeout(): Long { - return getLongPreference(TextSecurePreferences.SCREEN_LOCK_TIMEOUT, 0) + return getLongPreference(SCREEN_LOCK_TIMEOUT, 0) } fun setScreenLockTimeout(value: Long) { - setLongPreference(TextSecurePreferences.SCREEN_LOCK_TIMEOUT, value) + setLongPreference(SCREEN_LOCK_TIMEOUT, value) } fun setBackupPassphrase(passphrase: String?) { - setStringPreference(TextSecurePreferences.BACKUP_PASSPHRASE, passphrase) + setStringPreference(BACKUP_PASSPHRASE, passphrase) } fun getBackupPassphrase(): String? { - return getStringPreference(TextSecurePreferences.BACKUP_PASSPHRASE, null) + return getStringPreference(BACKUP_PASSPHRASE, null) } fun setEncryptedBackupPassphrase(encryptedPassphrase: String?) { - setStringPreference(TextSecurePreferences.ENCRYPTED_BACKUP_PASSPHRASE, encryptedPassphrase) + setStringPreference(ENCRYPTED_BACKUP_PASSPHRASE, encryptedPassphrase) } fun getEncryptedBackupPassphrase(): String? { - return getStringPreference(TextSecurePreferences.ENCRYPTED_BACKUP_PASSPHRASE, null) + return getStringPreference(ENCRYPTED_BACKUP_PASSPHRASE, null) } fun setBackupEnabled(value: Boolean) { - setBooleanPreference(TextSecurePreferences.BACKUP_ENABLED, value) + setBooleanPreference(BACKUP_ENABLED, value) } fun isBackupEnabled(): Boolean { - return getBooleanPreference(TextSecurePreferences.BACKUP_ENABLED, false) + return getBooleanPreference(BACKUP_ENABLED, false) } fun setNextBackupTime(time: Long) { - setLongPreference(TextSecurePreferences.BACKUP_TIME, time) + setLongPreference(BACKUP_TIME, time) } fun getNextBackupTime(): Long { - return getLongPreference(TextSecurePreferences.BACKUP_TIME, -1) + return getLongPreference(BACKUP_TIME, -1) } fun setBackupSaveDir(dirUri: String?) { - setStringPreference(TextSecurePreferences.BACKUP_SAVE_DIR, dirUri) + setStringPreference(BACKUP_SAVE_DIR, dirUri) } fun getBackupSaveDir(): String? { - return getStringPreference(TextSecurePreferences.BACKUP_SAVE_DIR, null) + return getStringPreference(BACKUP_SAVE_DIR, null) } fun getNeedsSqlCipherMigration(): Boolean { - return getBooleanPreference(TextSecurePreferences.NEEDS_SQLCIPHER_MIGRATION, false) + return getBooleanPreference(NEEDS_SQLCIPHER_MIGRATION, false) } fun setAttachmentEncryptedSecret(secret: String) { - setStringPreference(TextSecurePreferences.ATTACHMENT_ENCRYPTED_SECRET, secret) + setStringPreference(ATTACHMENT_ENCRYPTED_SECRET, secret) } fun setAttachmentUnencryptedSecret(secret: String?) { - setStringPreference(TextSecurePreferences.ATTACHMENT_UNENCRYPTED_SECRET, secret) + setStringPreference(ATTACHMENT_UNENCRYPTED_SECRET, secret) } fun getAttachmentEncryptedSecret(): String? { - return getStringPreference(TextSecurePreferences.ATTACHMENT_ENCRYPTED_SECRET, null) + return getStringPreference(ATTACHMENT_ENCRYPTED_SECRET, null) } fun getAttachmentUnencryptedSecret(): String? { - return getStringPreference(TextSecurePreferences.ATTACHMENT_UNENCRYPTED_SECRET, null) + return getStringPreference(ATTACHMENT_UNENCRYPTED_SECRET, null) } fun setDatabaseEncryptedSecret(secret: String) { - setStringPreference(TextSecurePreferences.DATABASE_ENCRYPTED_SECRET, secret) + setStringPreference(DATABASE_ENCRYPTED_SECRET, secret) } fun setDatabaseUnencryptedSecret(secret: String?) { - setStringPreference(TextSecurePreferences.DATABASE_UNENCRYPTED_SECRET, secret) + setStringPreference(DATABASE_UNENCRYPTED_SECRET, secret) } fun getDatabaseUnencryptedSecret(): String? { - return getStringPreference(TextSecurePreferences.DATABASE_UNENCRYPTED_SECRET, null) + return getStringPreference(DATABASE_UNENCRYPTED_SECRET, null) } fun getDatabaseEncryptedSecret(): String? { - return getStringPreference(TextSecurePreferences.DATABASE_ENCRYPTED_SECRET, null) + return getStringPreference(DATABASE_ENCRYPTED_SECRET, null) } fun isIncognitoKeyboardEnabled(): Boolean { - return getBooleanPreference(TextSecurePreferences.INCOGNITO_KEYBORAD_PREF, true) + return getBooleanPreference(INCOGNITO_KEYBORAD_PREF, true) } fun isReadReceiptsEnabled(): Boolean { - return getBooleanPreference(TextSecurePreferences.READ_RECEIPTS_PREF, false) + return getBooleanPreference(READ_RECEIPTS_PREF, false) } fun setReadReceiptsEnabled(enabled: Boolean) { - setBooleanPreference(TextSecurePreferences.READ_RECEIPTS_PREF, enabled) + setBooleanPreference(READ_RECEIPTS_PREF, enabled) } fun isTypingIndicatorsEnabled(): Boolean { - return getBooleanPreference(TextSecurePreferences.TYPING_INDICATORS, false) + return getBooleanPreference(TYPING_INDICATORS, false) } fun setTypingIndicatorsEnabled(enabled: Boolean) { - setBooleanPreference(TextSecurePreferences.TYPING_INDICATORS, enabled) + setBooleanPreference(TYPING_INDICATORS, enabled) } fun isLinkPreviewsEnabled(): Boolean { - return getBooleanPreference(TextSecurePreferences.LINK_PREVIEWS, false) + return getBooleanPreference(LINK_PREVIEWS, false) } fun setLinkPreviewsEnabled(enabled: Boolean) { - setBooleanPreference(TextSecurePreferences.LINK_PREVIEWS, enabled) + setBooleanPreference(LINK_PREVIEWS, enabled) } fun hasSeenGIFMetaDataWarning(): Boolean { - return getBooleanPreference(TextSecurePreferences.GIF_METADATA_WARNING, false) + return getBooleanPreference(GIF_METADATA_WARNING, false) } fun setHasSeenGIFMetaDataWarning() { - setBooleanPreference(TextSecurePreferences.GIF_METADATA_WARNING, true) + setBooleanPreference(GIF_METADATA_WARNING, true) } fun isGifSearchInGridLayout(): Boolean { - return getBooleanPreference(TextSecurePreferences.GIF_GRID_LAYOUT, false) + return getBooleanPreference(GIF_GRID_LAYOUT, false) } fun setIsGifSearchInGridLayout(isGrid: Boolean) { - setBooleanPreference(TextSecurePreferences.GIF_GRID_LAYOUT, isGrid) + setBooleanPreference(GIF_GRID_LAYOUT, isGrid) } fun getProfileKey(): String? { - return getStringPreference(TextSecurePreferences.PROFILE_KEY_PREF, null) + return getStringPreference(PROFILE_KEY_PREF, null) } fun setProfileKey(key: String?) { - setStringPreference(TextSecurePreferences.PROFILE_KEY_PREF, key) + setStringPreference(PROFILE_KEY_PREF, key) } fun setProfileName(name: String?) { - setStringPreference(TextSecurePreferences.PROFILE_NAME_PREF, name) - TextSecurePreferences._events.tryEmit(TextSecurePreferences.PROFILE_NAME_PREF) + setStringPreference(PROFILE_NAME_PREF, name) + _events.tryEmit(PROFILE_NAME_PREF) } fun getProfileName(): String? { - return getStringPreference(TextSecurePreferences.PROFILE_NAME_PREF, null) + return getStringPreference(PROFILE_NAME_PREF, null) } fun setProfileAvatarId(id: Int) { - setIntegerPreference(TextSecurePreferences.PROFILE_AVATAR_ID_PREF, id) + setIntegerPreference(PROFILE_AVATAR_ID_PREF, id) } fun getProfileAvatarId(): Int { - return getIntegerPreference(TextSecurePreferences.PROFILE_AVATAR_ID_PREF, 0) + return getIntegerPreference(PROFILE_AVATAR_ID_PREF, 0) } fun setProfilePictureURL(url: String?) { - setStringPreference(TextSecurePreferences.PROFILE_AVATAR_URL_PREF, url) + setStringPreference(PROFILE_AVATAR_URL_PREF, url) } fun getProfilePictureURL(): String? { - return getStringPreference(TextSecurePreferences.PROFILE_AVATAR_URL_PREF, null) + return getStringPreference(PROFILE_AVATAR_URL_PREF, null) } fun getNotificationPriority(): Int { return getStringPreference( - TextSecurePreferences.NOTIFICATION_PRIORITY_PREF, NotificationCompat.PRIORITY_HIGH.toString())!!.toInt() + NOTIFICATION_PRIORITY_PREF, NotificationCompat.PRIORITY_HIGH.toString())!!.toInt() } fun getMessageBodyTextSize(): Int { - return getStringPreference(TextSecurePreferences.MESSAGE_BODY_TEXT_SIZE_PREF, "16")!!.toInt() + return getStringPreference(MESSAGE_BODY_TEXT_SIZE_PREF, "16")!!.toInt() } fun setDirectCaptureCameraId(value: Int) { - setIntegerPreference(TextSecurePreferences.DIRECT_CAPTURE_CAMERA_ID, value) + setIntegerPreference(DIRECT_CAPTURE_CAMERA_ID, value) } fun getDirectCaptureCameraId(): Int { - return getIntegerPreference(TextSecurePreferences.DIRECT_CAPTURE_CAMERA_ID, Camera.CameraInfo.CAMERA_FACING_BACK) + return getIntegerPreference(DIRECT_CAPTURE_CAMERA_ID, Camera.CameraInfo.CAMERA_FACING_BACK) } fun getNotificationPrivacy(): NotificationPrivacyPreference { return NotificationPrivacyPreference(getStringPreference( - TextSecurePreferences.NOTIFICATION_PRIVACY_PREF, "all")) + NOTIFICATION_PRIVACY_PREF, "all")) } fun getRepeatAlertsCount(): Int { return try { - getStringPreference(TextSecurePreferences.REPEAT_ALERTS_PREF, "0")!!.toInt() + getStringPreference(REPEAT_ALERTS_PREF, "0")!!.toInt() } catch (e: NumberFormatException) { - Log.w(TextSecurePreferences.TAG, e) + Log.w(TAG, e) 0 } } fun getLocalRegistrationId(): Int { - return getIntegerPreference(TextSecurePreferences.LOCAL_REGISTRATION_ID_PREF, 0) + return getIntegerPreference(LOCAL_REGISTRATION_ID_PREF, 0) } fun setLocalRegistrationId(registrationId: Int) { - setIntegerPreference(TextSecurePreferences.LOCAL_REGISTRATION_ID_PREF, registrationId) + setIntegerPreference(LOCAL_REGISTRATION_ID_PREF, registrationId) } fun isInThreadNotifications(): Boolean { - return getBooleanPreference(TextSecurePreferences.IN_THREAD_NOTIFICATION_PREF, true) + return getBooleanPreference(IN_THREAD_NOTIFICATION_PREF, true) } fun isUniversalUnidentifiedAccess(): Boolean { - return getBooleanPreference(TextSecurePreferences.UNIVERSAL_UNIDENTIFIED_ACCESS, false) + return getBooleanPreference(UNIVERSAL_UNIDENTIFIED_ACCESS, false) } fun getUpdateApkRefreshTime(): Long { - return getLongPreference(TextSecurePreferences.UPDATE_APK_REFRESH_TIME_PREF, 0L) + return getLongPreference(UPDATE_APK_REFRESH_TIME_PREF, 0L) } fun setUpdateApkRefreshTime(value: Long) { - setLongPreference(TextSecurePreferences.UPDATE_APK_REFRESH_TIME_PREF, value) + setLongPreference(UPDATE_APK_REFRESH_TIME_PREF, value) } fun setUpdateApkDownloadId(value: Long) { - setLongPreference(TextSecurePreferences.UPDATE_APK_DOWNLOAD_ID, value) + setLongPreference(UPDATE_APK_DOWNLOAD_ID, value) } fun getUpdateApkDownloadId(): Long { - return getLongPreference(TextSecurePreferences.UPDATE_APK_DOWNLOAD_ID, -1) + return getLongPreference(UPDATE_APK_DOWNLOAD_ID, -1) } fun setUpdateApkDigest(value: String?) { - setStringPreference(TextSecurePreferences.UPDATE_APK_DIGEST, value) + setStringPreference(UPDATE_APK_DIGEST, value) } fun getUpdateApkDigest(): String? { - return getStringPreference(TextSecurePreferences.UPDATE_APK_DIGEST, null) + return getStringPreference(UPDATE_APK_DIGEST, null) } fun getLocalNumber(): String? { - return getStringPreference(TextSecurePreferences.LOCAL_NUMBER_PREF, null) + return getStringPreference(LOCAL_NUMBER_PREF, null) } fun getHasLegacyConfig(): Boolean { - return getBooleanPreference(TextSecurePreferences.HAS_RECEIVED_LEGACY_CONFIG, false) + return getBooleanPreference(HAS_RECEIVED_LEGACY_CONFIG, false) } fun setHasLegacyConfig(newValue: Boolean) { - setBooleanPreference(TextSecurePreferences.HAS_RECEIVED_LEGACY_CONFIG, newValue) - TextSecurePreferences._events.tryEmit(TextSecurePreferences.HAS_RECEIVED_LEGACY_CONFIG) + setBooleanPreference(HAS_RECEIVED_LEGACY_CONFIG, newValue) + _events.tryEmit(HAS_RECEIVED_LEGACY_CONFIG) } fun setLocalNumber(localNumber: String) { - setStringPreference(TextSecurePreferences.LOCAL_NUMBER_PREF, localNumber.toLowerCase()) + setStringPreference(LOCAL_NUMBER_PREF, localNumber.toLowerCase()) } fun removeLocalNumber() { - removePreference(TextSecurePreferences.LOCAL_NUMBER_PREF) + removePreference(LOCAL_NUMBER_PREF) } fun isEnterSendsEnabled(): Boolean { - return getBooleanPreference(TextSecurePreferences.ENTER_SENDS_PREF, false) + return getBooleanPreference(ENTER_SENDS_PREF, false) } - fun isPasswordDisabled(): Boolean { - return getBooleanPreference(TextSecurePreferences.DISABLE_PASSPHRASE_PREF, true) - } + fun isPasswordDisabled(): Boolean = sharedPreferences[DISABLE_PASSPHRASE_PREF] fun setPasswordDisabled(disabled: Boolean) { - setBooleanPreference(TextSecurePreferences.DISABLE_PASSPHRASE_PREF, disabled) + sharedPreferences[DISABLE_PASSPHRASE_PREF] = disabled } fun isScreenSecurityEnabled(): Boolean { - return getBooleanPreference(TextSecurePreferences.SCREEN_SECURITY_PREF, true) + return getBooleanPreference(SCREEN_SECURITY_PREF, true) } fun getLastVersionCode(): Int { - return getIntegerPreference(TextSecurePreferences.LAST_VERSION_CODE_PREF, 0) + return getIntegerPreference(LAST_VERSION_CODE_PREF, 0) } @Throws(IOException::class) fun setLastVersionCode(versionCode: Int) { - if (!setIntegerPreferenceBlocking(TextSecurePreferences.LAST_VERSION_CODE_PREF, versionCode)) { + if (!setIntegerPreferenceBlocking(LAST_VERSION_CODE_PREF, versionCode)) { throw IOException("couldn't write version code to sharedpreferences") } } fun isPassphraseTimeoutEnabled(): Boolean { - return getBooleanPreference(TextSecurePreferences.PASSPHRASE_TIMEOUT_PREF, false) + return getBooleanPreference(PASSPHRASE_TIMEOUT_PREF, false) } fun getPassphraseTimeoutInterval(): Int { - return getIntegerPreference(TextSecurePreferences.PASSPHRASE_TIMEOUT_INTERVAL_PREF, 5 * 60) + return getIntegerPreference(PASSPHRASE_TIMEOUT_INTERVAL_PREF, 5 * 60) } fun getLanguage(): String? { - return getStringPreference(TextSecurePreferences.LANGUAGE_PREF, "zz") + return getStringPreference(LANGUAGE_PREF, "zz") } fun isNotificationsEnabled(): Boolean { - return getBooleanPreference(TextSecurePreferences.NOTIFICATION_PREF, true) + return getBooleanPreference(NOTIFICATION_PREF, true) } fun getNotificationRingtone(): Uri { - var result = getStringPreference(TextSecurePreferences.RINGTONE_PREF, Settings.System.DEFAULT_NOTIFICATION_URI.toString()) + var result = getStringPreference(RINGTONE_PREF, Settings.System.DEFAULT_NOTIFICATION_URI.toString()) if (result != null && result.startsWith("file:")) { result = Settings.System.DEFAULT_NOTIFICATION_URI.toString() } @@ -1017,43 +514,43 @@ class TextSecurePreferences @Inject constructor( } fun removeNotificationRingtone() { - removePreference(TextSecurePreferences.RINGTONE_PREF) + removePreference(RINGTONE_PREF) } fun setNotificationRingtone(ringtone: String?) { - setStringPreference(TextSecurePreferences.RINGTONE_PREF, ringtone) + setStringPreference(RINGTONE_PREF, ringtone) } fun setNotificationVibrateEnabled(enabled: Boolean) { - setBooleanPreference(TextSecurePreferences.VIBRATE_PREF, enabled) + setBooleanPreference(VIBRATE_PREF, enabled) } fun isNotificationVibrateEnabled(): Boolean { - return getBooleanPreference(TextSecurePreferences.VIBRATE_PREF, true) + return getBooleanPreference(VIBRATE_PREF, true) } fun getNotificationLedColor(): Int { - return getIntegerPreference(TextSecurePreferences.LED_COLOR_PREF_PRIMARY, context.getColor(R.color.accent_green)) + return getIntegerPreference(LED_COLOR_PREF_PRIMARY, context.getColor(R.color.accent_green)) } fun isThreadLengthTrimmingEnabled(): Boolean { - return getBooleanPreference(TextSecurePreferences.THREAD_TRIM_ENABLED, true) + return getBooleanPreference(THREAD_TRIM_ENABLED, true) } fun isSystemEmojiPreferred(): Boolean { - return getBooleanPreference(TextSecurePreferences.SYSTEM_EMOJI_PREF, false) + return getBooleanPreference(SYSTEM_EMOJI_PREF, false) } fun getMobileMediaDownloadAllowed(): Set? { - return getMediaDownloadAllowed(TextSecurePreferences.MEDIA_DOWNLOAD_MOBILE_PREF, R.array.pref_media_download_mobile_data_default) + return getMediaDownloadAllowed(MEDIA_DOWNLOAD_MOBILE_PREF, R.array.pref_media_download_mobile_data_default) } fun getWifiMediaDownloadAllowed(): Set? { - return getMediaDownloadAllowed(TextSecurePreferences.MEDIA_DOWNLOAD_WIFI_PREF, R.array.pref_media_download_wifi_default) + return getMediaDownloadAllowed(MEDIA_DOWNLOAD_WIFI_PREF, R.array.pref_media_download_wifi_default) } fun getRoamingMediaDownloadAllowed(): Set? { - return getMediaDownloadAllowed(TextSecurePreferences.MEDIA_DOWNLOAD_ROAMING_PREF, R.array.pref_media_download_roaming_default) + return getMediaDownloadAllowed(MEDIA_DOWNLOAD_ROAMING_PREF, R.array.pref_media_download_roaming_default) } fun getMediaDownloadAllowed(key: String, @ArrayRes defaultValuesRes: Int): Set? { @@ -1061,39 +558,39 @@ class TextSecurePreferences @Inject constructor( } fun getLogEncryptedSecret(): String? { - return getStringPreference(TextSecurePreferences.LOG_ENCRYPTED_SECRET, null) + return getStringPreference(LOG_ENCRYPTED_SECRET, null) } fun setLogEncryptedSecret(base64Secret: String?) { - setStringPreference(TextSecurePreferences.LOG_ENCRYPTED_SECRET, base64Secret) + setStringPreference(LOG_ENCRYPTED_SECRET, base64Secret) } fun getLogUnencryptedSecret(): String? { - return getStringPreference(TextSecurePreferences.LOG_UNENCRYPTED_SECRET, null) + return getStringPreference(LOG_UNENCRYPTED_SECRET, null) } fun setLogUnencryptedSecret(base64Secret: String?) { - setStringPreference(TextSecurePreferences.LOG_UNENCRYPTED_SECRET, base64Secret) + setStringPreference(LOG_UNENCRYPTED_SECRET, base64Secret) } fun getNotificationChannelVersion(): Int { - return getIntegerPreference(TextSecurePreferences.NOTIFICATION_CHANNEL_VERSION, 1) + return getIntegerPreference(NOTIFICATION_CHANNEL_VERSION, 1) } fun setNotificationChannelVersion(version: Int) { - setIntegerPreference(TextSecurePreferences.NOTIFICATION_CHANNEL_VERSION, version) + setIntegerPreference(NOTIFICATION_CHANNEL_VERSION, version) } fun getNotificationMessagesChannelVersion(): Int { - return getIntegerPreference(TextSecurePreferences.NOTIFICATION_MESSAGES_CHANNEL_VERSION, 1) + return getIntegerPreference(NOTIFICATION_MESSAGES_CHANNEL_VERSION, 1) } fun setNotificationMessagesChannelVersion(version: Int) { - setIntegerPreference(TextSecurePreferences.NOTIFICATION_MESSAGES_CHANNEL_VERSION, version) + setIntegerPreference(NOTIFICATION_MESSAGES_CHANNEL_VERSION, version) } fun hasForcedNewConfig(): Boolean = - getBooleanPreference(TextSecurePreferences.HAS_FORCED_NEW_CONFIG, false) + getBooleanPreference(HAS_FORCED_NEW_CONFIG, false) fun getBooleanPreference(key: String?, defaultValue: Boolean): Boolean { return getDefaultSharedPreferences(context).getBoolean(key, defaultValue) @@ -1160,10 +657,6 @@ class TextSecurePreferences @Inject constructor( setLongPreference("restoration_time", time) } - fun getRestorationTime(): Long { - return getLongPreference("restoration_time", 0) - } - fun getLastProfilePictureUpload(): Long { return getLongPreference("last_profile_picture_upload", 0) } @@ -1181,19 +674,19 @@ class TextSecurePreferences @Inject constructor( } fun shouldUpdateProfile(profileUpdateTime: Long): Boolean { - return profileUpdateTime > getLongPreference(TextSecurePreferences.LAST_PROFILE_UPDATE_TIME, 0) + return profileUpdateTime > getLongPreference(LAST_PROFILE_UPDATE_TIME, 0) } fun setLastProfileUpdateTime(profileUpdateTime: Long) { - setLongPreference(TextSecurePreferences.LAST_PROFILE_UPDATE_TIME, profileUpdateTime) + setLongPreference(LAST_PROFILE_UPDATE_TIME, profileUpdateTime) } fun getLastOpenTimeDate(): Long { - return getLongPreference(TextSecurePreferences.LAST_OPEN_DATE, 0) + return getLongPreference(LAST_OPEN_DATE, 0) } fun setLastOpenDate() { - setLongPreference(TextSecurePreferences.LAST_OPEN_DATE, System.currentTimeMillis()) + setLongPreference(LAST_OPEN_DATE, System.currentTimeMillis()) } fun hasSeenLinkPreviewSuggestionDialog(): Boolean { @@ -1208,6 +701,14 @@ class TextSecurePreferences @Inject constructor( return getBooleanPreference(CALL_NOTIFICATIONS_ENABLED, false) } + fun setCallNotificationsEnabled(enabled: Boolean) { + setBooleanPreference(CALL_NOTIFICATIONS_ENABLED, enabled) + } + + fun getLastVacuumTime(): Long { + return getLongPreference(LAST_VACUUM_TIME, 0) + } + fun getLastVacuum(): Long { return getLongPreference(LAST_VACUUM_TIME, 0) } @@ -1240,19 +741,23 @@ class TextSecurePreferences @Inject constructor( } fun hasHiddenMessageRequests(): Boolean { - return getBooleanPreference(TextSecurePreferences.HAS_HIDDEN_MESSAGE_REQUESTS, false) + return getBooleanPreference(HAS_HIDDEN_MESSAGE_REQUESTS, false) } fun setHasHiddenMessageRequests() { - setBooleanPreference(TextSecurePreferences.HAS_HIDDEN_MESSAGE_REQUESTS, true) + setBooleanPreference(HAS_HIDDEN_MESSAGE_REQUESTS, true) + } + + fun removeHasHiddenMessageRequests() { + removePreference(HAS_HIDDEN_MESSAGE_REQUESTS) } fun getFingerprintKeyGenerated(): Boolean { - return getBooleanPreference(TextSecurePreferences.FINGERPRINT_KEY_GENERATED, false) + return getBooleanPreference(FINGERPRINT_KEY_GENERATED, false) } fun setFingerprintKeyGenerated() { - setBooleanPreference(TextSecurePreferences.FINGERPRINT_KEY_GENERATED, true) + setBooleanPreference(FINGERPRINT_KEY_GENERATED, true) } fun getSelectedAccentColor(): String? = @@ -1261,27 +766,27 @@ class TextSecurePreferences @Inject constructor( @StyleRes fun getAccentColorStyle(): Int? { return when (getSelectedAccentColor()) { - TextSecurePreferences.GREEN_ACCENT -> R.style.PrimaryGreen - TextSecurePreferences.BLUE_ACCENT -> R.style.PrimaryBlue - TextSecurePreferences.PURPLE_ACCENT -> R.style.PrimaryPurple - TextSecurePreferences.PINK_ACCENT -> R.style.PrimaryPink - TextSecurePreferences.RED_ACCENT -> R.style.PrimaryRed - TextSecurePreferences.ORANGE_ACCENT -> R.style.PrimaryOrange - TextSecurePreferences.YELLOW_ACCENT -> R.style.PrimaryYellow + GREEN_ACCENT -> R.style.PrimaryGreen + BLUE_ACCENT -> R.style.PrimaryBlue + PURPLE_ACCENT -> R.style.PrimaryPurple + PINK_ACCENT -> R.style.PrimaryPink + RED_ACCENT -> R.style.PrimaryRed + ORANGE_ACCENT -> R.style.PrimaryOrange + YELLOW_ACCENT -> R.style.PrimaryYellow else -> null } } fun setAccentColorStyle(@StyleRes newColorStyle: Int?) { setStringPreference( - TextSecurePreferences.SELECTED_ACCENT_COLOR, when (newColorStyle) { - R.style.PrimaryGreen -> TextSecurePreferences.GREEN_ACCENT - R.style.PrimaryBlue -> TextSecurePreferences.BLUE_ACCENT - R.style.PrimaryPurple -> TextSecurePreferences.PURPLE_ACCENT - R.style.PrimaryPink -> TextSecurePreferences.PINK_ACCENT - R.style.PrimaryRed -> TextSecurePreferences.RED_ACCENT - R.style.PrimaryOrange -> TextSecurePreferences.ORANGE_ACCENT - R.style.PrimaryYellow -> TextSecurePreferences.YELLOW_ACCENT + SELECTED_ACCENT_COLOR, when (newColorStyle) { + R.style.PrimaryGreen -> GREEN_ACCENT + R.style.PrimaryBlue -> BLUE_ACCENT + R.style.PrimaryPurple -> PURPLE_ACCENT + R.style.PrimaryPink -> PINK_ACCENT + R.style.PrimaryRed -> RED_ACCENT + R.style.PrimaryOrange -> ORANGE_ACCENT + R.style.PrimaryYellow -> YELLOW_ACCENT else -> null } ) diff --git a/libsession/src/main/java/org/session/libsession/utilities/Util.kt b/libsession/src/main/java/org/session/libsession/utilities/Util.kt index 6e254b9fab..d9592656b0 100644 --- a/libsession/src/main/java/org/session/libsession/utilities/Util.kt +++ b/libsession/src/main/java/org/session/libsession/utilities/Util.kt @@ -11,6 +11,7 @@ import android.text.Spannable import android.text.SpannableString import android.text.TextUtils import android.text.style.StyleSpan +import org.session.libsession.messaging.MessagingModuleConfiguration import org.session.libsignal.utilities.Log import org.session.libsignal.utilities.Base64 import java.io.* @@ -209,8 +210,8 @@ object Util { } @JvmStatic - fun isOwnNumber(context: Context, number: String): Boolean { - return TextSecurePreferences.getLocalNumber(context).equals(number) + fun isOwnNumber(number: String): Boolean { + return MessagingModuleConfiguration.shared.context.prefs.getLocalNumber().equals(number) } @JvmStatic diff --git a/libsession/src/main/java/org/session/libsession/utilities/recipients/Recipient.java b/libsession/src/main/java/org/session/libsession/utilities/recipients/Recipient.java index 2b233e1f3d..5c68b1f88b 100644 --- a/libsession/src/main/java/org/session/libsession/utilities/recipients/Recipient.java +++ b/libsession/src/main/java/org/session/libsession/utilities/recipients/Recipient.java @@ -17,6 +17,8 @@ */ package org.session.libsession.utilities.recipients; +import static org.session.libsession.utilities.TextSecurePreferencesKt.getPrefs; + import android.content.Context; import android.graphics.drawable.Drawable; import android.net.Uri; @@ -524,7 +526,7 @@ public class Recipient implements RecipientModifiedListener { } public synchronized @Nullable ContactPhoto getContactPhoto() { - if (isLocalNumber) return new ProfileContactPhoto(address, String.valueOf(TextSecurePreferences.getProfileAvatarId(context))); + if (isLocalNumber) return new ProfileContactPhoto(address, String.valueOf(getPrefs(MessagingModuleConfiguration.getShared().getContext()).getProfileAvatarId())); else if (isGroupRecipient() && groupAvatarId != null) return new GroupRecordContactPhoto(address, groupAvatarId); else if (systemContactPhoto != null) return new SystemContactPhoto(address, systemContactPhoto, 0); else if (profileAvatar != null) return new ProfileContactPhoto(address, profileAvatar); diff --git a/libsession/src/main/java/org/session/libsession/utilities/recipients/RecipientProvider.java b/libsession/src/main/java/org/session/libsession/utilities/recipients/RecipientProvider.java index 374956072b..f6488e2bcf 100644 --- a/libsession/src/main/java/org/session/libsession/utilities/recipients/RecipientProvider.java +++ b/libsession/src/main/java/org/session/libsession/utilities/recipients/RecipientProvider.java @@ -16,6 +16,8 @@ */ package org.session.libsession.utilities.recipients; +import static org.session.libsession.utilities.TextSecurePreferencesKt.getPrefs; + import android.content.Context; import android.net.Uri; import android.text.TextUtils; @@ -80,14 +82,16 @@ class RecipientProvider { return recipientCache.remove(address); } - private @NonNull Optional createPrefetchedRecipientDetails(@NonNull Context context, @NonNull Address address, + private @NonNull Optional createPrefetchedRecipientDetails(@NonNull Context context, + @NonNull Address address, @NonNull Optional settings, @NonNull Optional groupRecord) { if (address.isGroup() && settings.isPresent() && groupRecord.isPresent()) { return Optional.of(getGroupRecipientDetails(context, address, groupRecord, settings, true)); } else if (!address.isGroup() && settings.isPresent()) { - boolean isLocalNumber = address.serialize().equals(TextSecurePreferences.getLocalNumber(context)); + TextSecurePreferences prefs = getPrefs(context); + boolean isLocalNumber = address.serialize().equals(prefs.getLocalNumber()); return Optional.of(new RecipientDetails(null, null, !TextUtils.isEmpty(settings.get().getSystemDisplayName()), isLocalNumber, settings.get(), null)); } @@ -114,7 +118,8 @@ class RecipientProvider { } boolean systemContact = settings.isPresent() && !TextUtils.isEmpty(settings.get().getSystemDisplayName()); - boolean isLocalNumber = address.serialize().equals(TextSecurePreferences.getLocalNumber(context)); + TextSecurePreferences prefs = getPrefs(context); + boolean isLocalNumber = address.serialize().equals(prefs.getLocalNumber()); return new RecipientDetails(null, null, systemContact, isLocalNumber, settings.orNull(), null); }