Skip to content
Merged
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
23 changes: 14 additions & 9 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import java.util.Properties

plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.compose.compiler)
alias(libs.plugins.kotlin.parcelize)
}

java {
Expand Down Expand Up @@ -176,8 +178,8 @@ android {
}
buildFeatures {
buildConfig = true
compose = true
resValues = true
viewBinding = true
}
splits {
// Split by ABI because compiled golang code is huge and a universal APK is nearly 200 MiB
Expand Down Expand Up @@ -228,13 +230,15 @@ kotlin {
}

dependencies {
implementation(libs.activity.ktx)
implementation(libs.appcompat)
implementation(libs.biometric)
implementation(libs.core.ktx)
implementation(libs.exifinterface)
implementation(libs.fragment.ktx)
implementation(libs.preference.ktx)
implementation(libs.androidx.activity.compose)
implementation(libs.androidx.biometric.compose)
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.compose.material3)
implementation(libs.androidx.compose.ui.tooling.preview)
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.exifinterface)
implementation(libs.androidx.lifecycle.viewmodel.compose)
implementation(libs.androidx.preference.ktx)
implementation(libs.material)
implementation(libs.tink.android)
implementation(files(rcbridgeAar))
Expand All @@ -243,8 +247,9 @@ dependencies {
// the Tink transitive dependency
implementation(libs.spotbugs)

debugImplementation(libs.androidx.compose.ui.tooling)
androidTestImplementation(libs.junit)
androidTestImplementation(libs.espresso.core)
androidTestImplementation(libs.androidx.test.espresso.core)
}

val archive = tasks.register("archive") {
Expand Down
9 changes: 7 additions & 2 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"
tools:ignore="ForegroundServicesPolicy" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE"
android:minSdkVersion="34" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />
tools:ignore="AllFilesAccessPolicy,ScopedStorage" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="29" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
Expand Down Expand Up @@ -60,6 +61,10 @@
android:name=".settings.EditRemoteActivity"
android:exported="false" />

<activity
android:name=".settings.InteractiveConfigurationActivity"
android:exported="false" />

<service
android:name=".rclone.KeepAliveService"
android:foregroundServiceType="specialUse"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,166 +11,105 @@ import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.ManagedActivityResultLauncher
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.biometric.BiometricManager.Authenticators
import androidx.biometric.AuthenticationRequest
import androidx.biometric.AuthenticationRequest.Companion.biometricRequest
import androidx.biometric.AuthenticationResult
import androidx.biometric.AuthenticationResultLauncher
import androidx.biometric.BiometricPrompt
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updateLayoutParams
import com.chiller3.rsaf.databinding.SettingsActivityBinding

abstract class PreferenceBaseActivity : AppCompatActivity() {
import androidx.biometric.compose.rememberAuthenticationLauncher
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.lifecycle.compose.LifecycleResumeEffect

abstract class BaseActivity : ComponentActivity() {
companion object {
private fun supportsModernDeviceCredential() =
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R
}

protected abstract val actionBarTitle: CharSequence?

protected abstract val showUpButton: Boolean

protected abstract fun createFragment(): PreferenceBaseFragment

private val tag = javaClass.simpleName

private lateinit var prefs: Preferences
private lateinit var bioPrompt: BiometricPrompt
private lateinit var activityManager: ActivityManager
private var isCoveredBySafeActivity = false

private val requestLegacyDeviceCredential =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == RESULT_OK) {
onAuthenticationSucceeded()
} else {
// We can't know the reason.
onAuthenticationError(
BiometricPrompt.ERROR_USER_CANCELED,
getString(R.string.biometric_error_cancelled),
)
}
}

override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)

val binding = SettingsActivityBinding.inflate(layoutInflater)
setContentView(binding.root)

val transaction = supportFragmentManager.beginTransaction()

// https://issuetracker.google.com/issues/181805603
val bioFragment = supportFragmentManager
.findFragmentByTag("androidx.biometric.BiometricFragment")
if (bioFragment != null) {
transaction.remove(bioFragment)
}

val fragment: PreferenceBaseFragment

if (savedInstanceState == null) {
fragment = createFragment()
transaction.replace(R.id.settings, fragment)
} else {
fragment = supportFragmentManager.findFragmentById(R.id.settings)
as PreferenceBaseFragment
}

transaction.commit()
prefs = Preferences(this)
activityManager = getSystemService(ActivityManager::class.java)

supportFragmentManager.setFragmentResultListener(fragment.requestTag, this) { _, result ->
setResult(RESULT_OK, Intent().apply { putExtras(result) })
}
setContent {
var startedOnce by rememberSaveable { mutableStateOf(false) }

ViewCompat.setOnApplyWindowInsetsListener(binding.toolbar) { v, windowInsets ->
val insets = windowInsets.getInsets(
WindowInsetsCompat.Type.systemBars()
or WindowInsetsCompat.Type.displayCutout()
)
val modernLauncher = rememberAuthenticationLauncher { authResult ->
startedOnce = false

v.updateLayoutParams<ViewGroup.MarginLayoutParams> {
leftMargin = insets.left
topMargin = insets.top
rightMargin = insets.right
when (authResult) {
is AuthenticationResult.Success -> onAuthenticationSucceeded()
is AuthenticationResult.Error -> {
// Ignore cancellation due to eg. orientation change.
if (authResult.errorCode != BiometricPrompt.ERROR_CANCELED) {
onAuthenticationError(authResult.errorCode, authResult.errString)
}
}
}
}

// Consuming the insets here prevents PreferenceBaseFragment's RecyclerView's insets
// callback from being called on older versions of Android, despite it not being a child
// of this view.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
WindowInsetsCompat.CONSUMED
} else {
windowInsets
val legacyLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {
startedOnce = false

if (it.resultCode == RESULT_OK) {
onAuthenticationSucceeded()
} else {
// We can't know the reason.
onAuthenticationError(
BiometricPrompt.ERROR_USER_CANCELED,
getString(R.string.biometric_error_cancelled),
)
}
}
}

setSupportActionBar(binding.toolbar)
supportActionBar!!.setDisplayHomeAsUpEnabled(showUpButton)
LifecycleResumeEffect(Unit) {
Log.d(tag, "onResume()")
AppLock.onAppResume()

actionBarTitle?.let {
title = it
}

prefs = Preferences(this)

bioPrompt = BiometricPrompt(
this,
mainExecutor,
object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) =
this@PreferenceBaseActivity.onAuthenticationError(errorCode, errString)

override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) =
this@PreferenceBaseActivity.onAuthenticationSucceeded()

override fun onAuthenticationFailed() {
// Ignore. This is called when a single biometric authentication attempt fails,
// but the user is still allowed to retry.
if (AppLock.isLocked && !startedOnce) {
startedOnce = true
startAuth(modernLauncher, legacyLauncher)
}
},
)

activityManager = getSystemService(ActivityManager::class.java)
}
refreshTaskState()
refreshGlobalVisibility()

override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
onBackPressedDispatcher.onBackPressed()
true
onPauseOrDispose {
Log.d(tag, "onPause()")
AppLock.onAppPause()
}
}
else -> super.onOptionsItemSelected(item)
}
}

override fun onResume() {
super.onResume()
Log.d(tag, "onResume()")

AppLock.onAppResume()

if (AppLock.isLocked) {
startAuth()
ActivityContent()
}

refreshTaskState()
refreshGlobalVisibility()
}

override fun onPause() {
super.onPause()
Log.d(tag, "onPause()")

AppLock.onAppPause()
}
@Composable
abstract fun ActivityContent()

override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
Expand Down Expand Up @@ -213,26 +152,33 @@ abstract class PreferenceBaseActivity : AppCompatActivity() {
super.onWindowAttributesChanged(params)
}

private fun startAuth() {
private fun startAuth(
modernLauncher: AuthenticationResultLauncher,
legacyLauncher: ManagedActivityResultLauncher<Intent, ActivityResult>,
) {
if (supportsModernDeviceCredential()) {
startBiometricAuth()
startBiometricAuth(modernLauncher)
} else {
startLegacyDeviceCredentialAuth()
startLegacyDeviceCredentialAuth(legacyLauncher)
}
}

private fun startBiometricAuth() {
private fun startBiometricAuth(launcher: AuthenticationResultLauncher) {
Log.d(tag, "Starting biometric authentication")

val promptInfo = BiometricPrompt.PromptInfo.Builder()
.setAllowedAuthenticators(Authenticators.BIOMETRIC_STRONG or Authenticators.DEVICE_CREDENTIAL)
.setTitle(getString(R.string.biometric_title))
.build()

bioPrompt.authenticate(promptInfo)
launcher.launch(
biometricRequest(
title = getString(R.string.biometric_title),
AuthenticationRequest.Biometric.Fallback.DeviceCredential,
) {
setMinStrength(AuthenticationRequest.Biometric.Strength.Class3())
}
)
}

private fun startLegacyDeviceCredentialAuth() {
private fun startLegacyDeviceCredentialAuth(
launcher: ManagedActivityResultLauncher<Intent, ActivityResult>,
) {
Log.d(tag, "Starting legacy device credential authentication")

val keyguardManager = getSystemService(KeyguardManager::class.java)
Expand All @@ -243,7 +189,7 @@ abstract class PreferenceBaseActivity : AppCompatActivity() {
)

if (intent != null) {
requestLegacyDeviceCredential.launch(intent)
launcher.launch(intent)
} else {
onAuthenticationError(
BiometricPrompt.ERROR_NO_DEVICE_CREDENTIAL,
Expand Down
7 changes: 2 additions & 5 deletions app/src/main/java/com/chiller3/rsaf/MainApplication.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* SPDX-FileCopyrightText: 2023-2024 Andrew Gunnerson
* SPDX-FileCopyrightText: 2023-2026 Andrew Gunnerson
* SPDX-License-Identifier: GPL-3.0-only
*/

Expand All @@ -9,7 +9,6 @@ import android.app.Application
import android.app.backup.BackupManager
import android.content.SharedPreferences
import android.util.Log
import com.google.android.material.color.DynamicColors
import java.io.File

class MainApplication : Application(), SharedPreferences.OnSharedPreferenceChangeListener {
Expand Down Expand Up @@ -38,16 +37,14 @@ class MainApplication : Application(), SharedPreferences.OnSharedPreferenceChang
}

prefs = Preferences(this)
prefs.migrate()
prefs.registerListener(this)

backupManager = BackupManager(this)

AppLock.init(this)

Notifications(this).updateChannels()

// Enable Material You colors
DynamicColors.applyToActivitiesIfAvailable(this)
}

override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
Expand Down
Loading