Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SES-2107] Optimise SharedPreferences #1554

Open
wants to merge 12 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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()))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import org.session.libsession.messaging.MessagingModuleConfiguration
import org.session.libsession.snode.SnodeAPI
import org.session.libsession.utilities.Address
import org.session.libsession.utilities.TextSecurePreferences
import org.session.libsession.utilities.prefs
import org.session.libsignal.utilities.KeyHelper
import org.session.libsignal.utilities.hexEncodedPublicKey
import org.thoughtcrime.securesms.ApplicationContext
Expand Down Expand Up @@ -82,18 +83,14 @@ class LibSessionTests {

@Before
fun setupUser() {
PreferenceManager.getDefaultSharedPreferences(InstrumentationRegistry.getInstrumentation().targetContext.applicationContext).edit {
putBoolean(TextSecurePreferences.HAS_FORCED_NEW_CONFIG, true).apply()
}
val newBytes = randomSeedBytes().toByteArray()
val context = InstrumentationRegistry.getInstrumentation().targetContext.applicationContext
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(registrationID)
context.prefs.setLocalNumber(kp.x25519KeyPair.hexEncodedPublicKey)
context.prefs.setHasViewedSeed(false)
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,6 @@
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;
Expand Down Expand Up @@ -152,18 +151,9 @@ public class ApplicationContext extends Application implements DefaultLifecycleO
@Inject ConfigFactory configFactory;
@Inject LastSentTimestampCache lastSentTimestampCache;
CallMessageProcessor callMessageProcessor;
MessagingModuleConfiguration messagingModuleConfiguration;

private volatile boolean isAppVisible;

@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();
}
Expand Down Expand Up @@ -212,9 +202,8 @@ public void onCreate() {
TextSecurePreferences.setPushSuffix(BuildConfig.PUSH_KEY_SUFFIX);

DatabaseModule.init(this);
MessagingModuleConfiguration.configure(this);
super.onCreate();
messagingModuleConfiguration = new MessagingModuleConfiguration(
MessagingModuleConfiguration.shared = new MessagingModuleConfiguration(
this,
storage,
device,
Expand Down Expand Up @@ -429,12 +418,12 @@ private void initializeBlobProvider() {
@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);
Expand All @@ -461,15 +450,15 @@ public void retrieveUserProfile() {
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));
Expand All @@ -484,7 +473,7 @@ private void resubmitProfilePictureIfNeeded() {
// 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;
});
Expand Down Expand Up @@ -516,7 +505,7 @@ private void loadEmojiSearchIndexIfNeeded() {
*/
@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.");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package org.thoughtcrime.securesms;

import static android.os.Build.VERSION.SDK_INT;
import static org.session.libsession.utilities.TextSecurePreferences.SELECTED_ACCENT_COLOR;

import android.app.ActivityManager;
import android.content.Context;
Expand All @@ -16,6 +15,7 @@
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;
Expand Down Expand Up @@ -61,7 +61,7 @@ private int getDesiredTheme() {

@StyleRes @Nullable
private Integer getAccentTheme() {
if (!getPreferences().hasPreference(SELECTED_ACCENT_COLOR)) return null;
if (!getPreferences().hasSelectedAccentColor()) return null;
ThemeState themeState = ActivityUtilitiesKt.themeState(getPreferences());
return themeState.getAccentStyle();
}
Expand Down Expand Up @@ -97,7 +97,7 @@ protected void onCreate(Bundle savedInstanceState) {
protected void onResume() {
super.onResume();
initializeScreenshotSecurity(true);
DynamicLanguageActivityHelper.recreateIfNotInCorrectLanguage(this, TextSecurePreferences.getLanguage(this));
DynamicLanguageActivityHelper.recreateIfNotInCorrectLanguage(this, MessagingModuleConfiguration.getShared().getPrefs().getLanguage());
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it worth putting a... what's the word, um, convenience getter (? I can't think of it - but what I'm after is syntactic sugar!) on this so we can just call MessagingModuleConfiguration.getLanguage() or something?

Same for anything else that calls MessagingModuleConfiguration.getShared().getPrefs() before it's final "give me the thing".

It looks like you have this further down where you just call context.prefs.<something> - is that the same thing?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, though ideally this is injected, I'll see if I can do that.

haha, yeah context.prefs should be the same thing, but again, if prefs is injected, that's more correct.

I'll look into it.

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);
Expand Down Expand Up @@ -130,7 +130,7 @@ private void initializeScreenshotSecurity(boolean isResume) {
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);
Expand All @@ -140,6 +140,6 @@ private void initializeScreenshotSecurity(boolean isResume) {

@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(DynamicLanguageContextWrapper.updateContext(newBase, TextSecurePreferences.getLanguage(newBase)));
super.attachBaseContext(DynamicLanguageContextWrapper.updateContext(newBase, MessagingModuleConfiguration.getShared().getPrefs().getLanguage()));
}
}
11 changes: 4 additions & 7 deletions app/src/main/java/org/thoughtcrime/securesms/BaseActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,10 @@
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 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;
Expand All @@ -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);
Expand All @@ -30,6 +27,6 @@ protected void onResume() {

@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(DynamicLanguageContextWrapper.updateContext(newBase, TextSecurePreferences.getLanguage(newBase)));
super.attachBaseContext(DynamicLanguageContextWrapper.updateContext(newBase, MessagingModuleConfiguration.getShared().getPrefs().getLanguage()));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,13 @@
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;
Expand Down Expand Up @@ -103,7 +102,7 @@ public void onResume() {

setLockTypeVisibility();

if (TextSecurePreferences.isScreenLockEnabled(this) && !authenticated && !failure) {
if (MessagingModuleConfiguration.getShared().getPrefs().isScreenLockEnabled() && !authenticated && !failure) {
resumeScreenLock();
}

Expand All @@ -114,7 +113,7 @@ public void onResume() {
public void onPause() {
super.onPause();

if (TextSecurePreferences.isScreenLockEnabled(this)) {
if (MessagingModuleConfiguration.getShared().getPrefs().isScreenLockEnabled()) {
pauseScreenLock();
}
}
Expand Down Expand Up @@ -176,7 +175,7 @@ private void initializeResources() {
}

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);
Expand All @@ -197,8 +196,8 @@ private void resumeScreenLock() {

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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
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;
Expand All @@ -39,8 +39,8 @@ protected final void onCreate(Bundle savedInstanceState) {
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);
Expand Down Expand Up @@ -125,7 +125,7 @@ private Intent getIntentForState(int state) {
}

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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ import org.thoughtcrime.securesms.webrtc.CallViewModel.State.CALL_RINGING
import org.thoughtcrime.securesms.webrtc.Orientation
import org.thoughtcrime.securesms.webrtc.audio.SignalAudioManager.AudioDevice.EARPIECE
import org.thoughtcrime.securesms.webrtc.audio.SignalAudioManager.AudioDevice.SPEAKER_PHONE
import javax.inject.Inject
import kotlin.math.asin

@AndroidEntryPoint
Expand All @@ -69,6 +70,8 @@ class WebRtcCallActivity : PassphraseRequiredActionBarActivity() {
private const val CALL_DURATION_FORMAT = "HH:mm:ss"
}

@Inject lateinit var prefs: TextSecurePreferences

private val viewModel by viewModels<CallViewModel>()
private val glide by lazy { GlideApp.with(this) }
private lateinit var binding: ActivityWebrtcBinding
Expand Down Expand Up @@ -204,11 +207,10 @@ class WebRtcCallActivity : PassphraseRequiredActionBarActivity() {
clipFloatingInsets()

// set up the user avatar
TextSecurePreferences.getLocalNumber(this)?.let{
val username = TextSecurePreferences.getProfileName(this) ?: truncateIdForDisplay(it)
prefs.getLocalNumber()?.let{
binding.userAvatar.apply {
publicKey = it
displayName = username
displayName = prefs.getProfileName() ?: truncateIdForDisplay(it)
update()
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
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;
Expand Down Expand Up @@ -108,8 +109,8 @@ public void setCursorPositionChangedListener(@Nullable CursorPositionChangedList
}

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();
Expand All @@ -132,7 +133,7 @@ public void setTransport() {
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;
}

Expand All @@ -149,7 +150,7 @@ public void setMediaListener(@Nullable InputPanel.MediaListener mediaListener) {
}

private void initialize() {
if (TextSecurePreferences.isIncognitoKeyboardEnabled(getContext())) {
if (MessagingModuleConfiguration.getShared().getPrefs().isIncognitoKeyboardEnabled()) {
setImeOptions(getImeOptions() | 16777216);
}
}
Expand Down
Loading