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 all 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,20 +202,19 @@ public void onCreate() {
TextSecurePreferences.setPushSuffix(BuildConfig.PUSH_KEY_SUFFIX);

DatabaseModule.init(this);
MessagingModuleConfiguration.configure(this);
super.onCreate();

// we need to clear the snode and onionrequest databases once on first launch
// in order to apply a patch that adds a version number to the Snode objects.
if(!TextSecurePreferences.hasAppliedPatchSnodeVersion(this)) {
if(!getPrefs().getHasAppliedPatchSnodeVersion()) {
ThreadUtils.queue(() -> {
lokiAPIDatabase.clearSnodePool();
lokiAPIDatabase.clearOnionRequestPaths();
TextSecurePreferences.setHasAppliedPatchSnodeVersion(this, true);
getPrefs().setHasAppliedPatchSnodeVersion(true);
});
}

messagingModuleConfiguration = new MessagingModuleConfiguration(
MessagingModuleConfiguration.shared = new MessagingModuleConfiguration(
this,
storage,
device,
Expand Down Expand Up @@ -440,12 +429,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 @@ -472,15 +461,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 @@ -495,7 +484,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 @@ -527,7 +516,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()));
}
}
35 changes: 0 additions & 35 deletions app/src/main/java/org/thoughtcrime/securesms/BaseActivity.java

This file was deleted.

33 changes: 33 additions & 0 deletions app/src/main/java/org/thoughtcrime/securesms/BaseActivity.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package org.thoughtcrime.securesms

import android.app.ActivityManager.TaskDescription
import android.content.Context
import android.graphics.BitmapFactory
import androidx.fragment.app.FragmentActivity
import network.loki.messenger.R
import org.session.libsession.messaging.MessagingModuleConfiguration.Companion.shared
import org.session.libsession.utilities.dynamiclanguage.DynamicLanguageActivityHelper
import org.session.libsession.utilities.dynamiclanguage.DynamicLanguageContextWrapper

abstract class BaseActivity : FragmentActivity() {
override fun onResume() {
super.onResume()
DynamicLanguageActivityHelper.recreateIfNotInCorrectLanguage(
this,
shared.prefs.getLanguage()
)
val name = resources.getString(R.string.app_name)
val icon = BitmapFactory.decodeResource(resources, R.drawable.ic_launcher_foreground)
val color = resources.getColor(R.color.app_icon_background)
setTaskDescription(TaskDescription(name, icon, color))
}

override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(
DynamicLanguageContextWrapper.updateContext(
newBase,
shared.prefs.getLanguage()
)
)
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* Copyright (C) 2013 Open Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>.
*/
package org.thoughtcrime.securesms

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import org.thoughtcrime.securesms.util.Util
import org.thoughtcrime.securesms.util.VersionTracker.getLastSeenVersion
import org.thoughtcrime.securesms.util.VersionTracker.updateLastSeenVersion

class DatabaseUpgradeActivity : BaseActivity() {
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
updateLastSeenVersion(this)
lifecycleScope.launch {
ApplicationContext.getInstance(this@DatabaseUpgradeActivity)
.messageNotifier.updateNotification(this@DatabaseUpgradeActivity)
}
startActivity(intent.getParcelableExtra<Parcelable>("next_intent") as? Intent)
finish()
}

companion object {
@JvmStatic
fun isUpdate(context: Context?): Boolean {
val currentVersionCode = Util.getCanonicalVersionCode()
val previousVersionCode = getLastSeenVersion(context!!)

return previousVersionCode < currentVersionCode
}
}
}
Loading