Remove static preferences methods

This commit is contained in:
bemusementpark 2024-07-10 16:49:41 +09:30
parent 5855bcd17f
commit f23a0fb5d8
97 changed files with 597 additions and 1090 deletions

View File

@ -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()))

View File

@ -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

View File

@ -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.");

View File

@ -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()));
}
}

View File

@ -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()));
}
}

View File

@ -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;
}

View File

@ -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;

View File

@ -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);
}
}

View File

@ -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() {

View File

@ -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);
}
}

View File

@ -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

View File

@ -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;

View File

@ -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
)
}

View File

@ -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,

View File

@ -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

View File

@ -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()
}

View File

@ -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)
}

View File

@ -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

View File

@ -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."

View File

@ -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)

View File

@ -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 =

View File

@ -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<Tuple2<Range<Int>, 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

View File

@ -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
}
}

View File

@ -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());
}
}

View File

@ -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)

View File

@ -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;
}

View File

@ -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<Recipient> 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<Address> getGroupMemberAddresses(String groupId, boolean includeSelf) {
List<Address> 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);

View File

@ -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 {

View File

@ -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 ->

View File

@ -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;

View File

@ -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)

View File

@ -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;

View File

@ -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;
}

View File

@ -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) {

View File

@ -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;
}

View File

@ -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();
}
}
},

View File

@ -13,6 +13,7 @@ import org.thoughtcrime.securesms.repository.DefaultConversationRepository
@InstallIn(SingletonComponent::class)
abstract class AppModule {
@Binds
abstract fun bindConversationRepository(repository: DefaultConversationRepository): ConversationRepository
}

View File

@ -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<ConfigFactoryUpdateListener> = mutableListOf()
fun registerListener(listener: ConfigFactoryUpdateListener) {

View File

@ -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)
}

View File

@ -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

View File

@ -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);

View File

@ -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);
}
}

View File

@ -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)
}

View File

@ -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());

View File

@ -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 ->

View File

@ -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))) {

View File

@ -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,

View File

@ -56,7 +56,7 @@ public class GroupManager {
final Recipient groupRecipient = Recipient.from(context, Address.fromSerialized(groupId), false);
final Set<Address> 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);

View File

@ -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
}

View File

@ -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;
}

View File

@ -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);

View File

@ -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;

View File

@ -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());

View File

@ -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);
}

View File

@ -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<Unit, Exception> = 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...

View File

@ -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<NotificationItem> 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<NotificationItem> 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;
}

View File

@ -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<MarkedMessageInfo>
) {
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<String, MarkedMessageInfo>
) {
@Suppress("UNCHECKED_CAST")
val expiries = SnodeAPI.getExpiries(hashToMessage.keys.toList(), TextSecurePreferences.getLocalNumber(context)!!).get()["expiries"] as Map<String, Long>
val expiries = SnodeAPI.getExpiries(hashToMessage.keys.toList(), context.prefs.getLocalNumber()!!).get()["expiries"] as Map<String, Long>
hashToMessage.forEach { (hash, info) -> expiries[hash]?.let { scheduleDeletion(context, info.expirationInfo, it - info.expirationInfo.expireStarted) } }
}

View File

@ -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());
}
}

View File

@ -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);
}

View File

@ -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());
}
}
}

View File

@ -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());
}
}

View File

@ -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()
}

View File

@ -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())
}

View File

@ -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) }

View File

@ -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)

View File

@ -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
}
}

View File

@ -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
)

View File

@ -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<Promise<*, Exception>>()
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)

View File

@ -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()
}

View File

@ -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;

View File

@ -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() {

View File

@ -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<GroupRecord> queryConversations(@NonNull String query, List<String> matchingAddresses) {
List<String> numbers = contactAccessor.getNumbersForThreadSearchFilter(context, query);
String localUserNumber = TextSecurePreferences.getLocalNumber(context);
String localUserNumber = MessagingModuleConfiguration.getShared().getPrefs().getLocalNumber();
if (localUserNumber != null) {
matchingAddresses.remove(localUserNumber);
}

View File

@ -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

View File

@ -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;
}

View File

@ -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);

View File

@ -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?");

View File

@ -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) {

View File

@ -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<Long>, readTimestamp: Long) {
if (TextSecurePreferences.isReadReceiptsEnabled(context)) {
if (context.prefs.isReadReceiptsEnabled()) {
// Redirect message to master device conversation
var address = Address.fromSerialized(fromRecipientId)

View File

@ -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;
}

View File

@ -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

View File

@ -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<String> 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();
}

View File

@ -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<Unit, Exception> {
// 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)

View File

@ -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)

View File

@ -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
}
}

View File

@ -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)

View File

@ -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) {

View File

@ -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<ClosedGroup>, 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) {

View File

@ -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<String, Boolean>()
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)

View File

@ -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

View File

@ -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

View File

@ -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<String> = 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)

View File

@ -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);
}
}

View File

@ -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

View File

@ -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

View File

@ -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);

View File

@ -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<RecipientDetails> createPrefetchedRecipientDetails(@NonNull Context context, @NonNull Address address,
private @NonNull Optional<RecipientDetails> createPrefetchedRecipientDetails(@NonNull Context context,
@NonNull Address address,
@NonNull Optional<RecipientSettings> settings,
@NonNull Optional<GroupRecord> 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);
}