Fix local network
This commit is contained in:
6 files changed
+173
-14
No files matched your search
@@ -4,6 +4,7 @@
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_LOCAL_NETWORK" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<uses-feature
|
||||
android:name="android.hardware.camera"
|
||||
|
||||
@@ -42,6 +42,7 @@ import net.helcel.cowspent.persistence.CowspentServerSyncHelper
|
||||
import net.helcel.cowspent.theme.ThemeUtils
|
||||
import net.helcel.cowspent.util.CospendClientUtil
|
||||
import net.helcel.cowspent.util.CospendClientUtil.LoginStatus
|
||||
import net.helcel.cowspent.util.LocalNetworkPermissionHelper
|
||||
import net.helcel.cowspent.util.SecureStorage
|
||||
import java.net.URLDecoder
|
||||
import java.util.Locale
|
||||
@@ -72,6 +73,7 @@ class AccountActivity : AppCompatActivity() {
|
||||
private lateinit var preferences: SharedPreferences
|
||||
private var useWebLogin = true
|
||||
private var showLoginDialog by mutableStateOf(false)
|
||||
private val localNetworkPermissionHelper = LocalNetworkPermissionHelper(this)
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
enableEdgeToEdge()
|
||||
@@ -101,7 +103,9 @@ class AccountActivity : AppCompatActivity() {
|
||||
AccountScreen(
|
||||
viewModel = viewModel,
|
||||
onBack = { finish() },
|
||||
onConnect = { login() },
|
||||
onConnect = {
|
||||
withLocalNetworkPermission(CospendClientUtil.formatURL(viewModel.serverUrl)) { login() }
|
||||
},
|
||||
onSsoClick = { isChecked ->
|
||||
if (isChecked) {
|
||||
showLoginDialog = true
|
||||
@@ -194,6 +198,13 @@ class AccountActivity : AppCompatActivity() {
|
||||
.cowspentServerSyncHelper.runAccountProjectsSync()
|
||||
}
|
||||
|
||||
private fun withLocalNetworkPermission(serverUrl: String, action: () -> Unit) {
|
||||
localNetworkPermissionHelper.runWithAccess(
|
||||
listOf(serverUrl),
|
||||
action = action
|
||||
)
|
||||
}
|
||||
|
||||
@Deprecated("Deprecated in Java")
|
||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||
super.onActivityResult(requestCode, resultCode, data)
|
||||
@@ -213,12 +224,14 @@ class AccountActivity : AppCompatActivity() {
|
||||
viewModel.serverUrl = ssoAccount.url
|
||||
viewModel.username = ssoAccount.userId
|
||||
|
||||
startInitialAccountSync()
|
||||
withLocalNetworkPermission(ssoAccount.url) {
|
||||
startInitialAccountSync()
|
||||
|
||||
val resultData = Intent()
|
||||
resultData.putExtra(MainConstants.CREDENTIALS_CHANGED, CREDENTIALS_CHANGED)
|
||||
setResult(RESULT_OK, resultData)
|
||||
finish()
|
||||
val resultData = Intent()
|
||||
resultData.putExtra(MainConstants.CREDENTIALS_CHANGED, CREDENTIALS_CHANGED)
|
||||
setResult(RESULT_OK, resultData)
|
||||
finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
|
||||
@@ -55,6 +55,7 @@ import net.helcel.cowspent.util.CospendClientUtil
|
||||
import net.helcel.cowspent.util.ExportUtil
|
||||
import net.helcel.cowspent.util.ICallback
|
||||
import net.helcel.cowspent.util.IRefreshBillsListCallback
|
||||
import net.helcel.cowspent.util.LocalNetworkPermissionHelper
|
||||
import net.helcel.cowspent.util.SyncSettings
|
||||
import net.helcel.cowspent.util.SupportUtil
|
||||
import net.helcel.cowspent.util.VersatileProjectSyncClient
|
||||
@@ -90,6 +91,7 @@ class BillsListViewActivity :
|
||||
|
||||
private var mActionMode: ActionMode? = null
|
||||
private lateinit var db: CowspentSQLiteOpenHelper
|
||||
private val localNetworkPermissionHelper = LocalNetworkPermissionHelper(this)
|
||||
|
||||
private val syncCallBack = object : ICallback {
|
||||
override fun onFinish() {
|
||||
@@ -341,15 +343,23 @@ class BillsListViewActivity :
|
||||
}
|
||||
viewModel.isRefreshing = false
|
||||
|
||||
synchronize(SyncTrigger.APP_OPEN)
|
||||
|
||||
lifecycleScope.launch {
|
||||
syncNewlyDiscoveredProjects(withContext(Dispatchers.IO) { db.projects })
|
||||
}
|
||||
|
||||
registerBroadcastReceiver()
|
||||
updateAvatarInDrawer(CowspentServerSyncHelper.isNextcloudAccountConfigured(this))
|
||||
isActivityVisible = true
|
||||
|
||||
synchronize(SyncTrigger.APP_OPEN)
|
||||
}
|
||||
|
||||
private fun configuredServerUrls(projects: List<DBProject>): List<String> = buildList {
|
||||
addAll(projects.filterNot { it.isLocal }.mapNotNull { it.serverUrl })
|
||||
if (CowspentServerSyncHelper.isNextcloudAccountConfigured(applicationContext)) {
|
||||
val preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext)
|
||||
val accountUrl = if (preferences.getBoolean(AccountActivity.SETTINGS_USE_SSO, false)) {
|
||||
preferences.getString(AccountActivity.SETTINGS_SSO_URL, null)
|
||||
} else {
|
||||
preferences.getString(AccountActivity.SETTINGS_URL, null)
|
||||
}
|
||||
accountUrl?.let(::add)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
@@ -802,6 +812,24 @@ class BillsListViewActivity :
|
||||
|
||||
@VisibleForTesting
|
||||
internal fun synchronize(trigger: SyncTrigger) {
|
||||
lifecycleScope.launch {
|
||||
val projects = withContext(Dispatchers.IO) { db.projects }
|
||||
localNetworkPermissionHelper.runWithAccess(
|
||||
configuredServerUrls(projects),
|
||||
action = {
|
||||
synchronizeAfterPermission(trigger)
|
||||
if (trigger == SyncTrigger.APP_OPEN) {
|
||||
lifecycleScope.launch {
|
||||
syncNewlyDiscoveredProjects(withContext(Dispatchers.IO) { db.projects })
|
||||
}
|
||||
updateAvatarInDrawer(CowspentServerSyncHelper.isNextcloudAccountConfigured(this))
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun synchronizeAfterPermission(trigger: SyncTrigger) {
|
||||
val preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext)
|
||||
// isSyncPossible is networkConnected && !offlineMode, so offline mode is already covered
|
||||
// here - including for a manual refresh, which cannot currently override it.
|
||||
|
||||
@@ -31,6 +31,7 @@ class NewProjectActivity : AppCompatActivity() {
|
||||
|
||||
internal val viewModel: NewProjectViewModel by viewModels()
|
||||
private lateinit var db: CowspentSQLiteOpenHelper
|
||||
private val localNetworkPermissionHelper = LocalNetworkPermissionHelper(this)
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
enableEdgeToEdge()
|
||||
@@ -136,7 +137,16 @@ class NewProjectActivity : AppCompatActivity() {
|
||||
viewModel.isAuthenticatedAccount = db.cowspentServerSyncHelper.canCreateAuthenticatedProject(fakeProj)
|
||||
}
|
||||
|
||||
private fun onPressOk() = createProject()
|
||||
private fun onPressOk() {
|
||||
if (viewModel.projectType == ProjectType.LOCAL) {
|
||||
createProject()
|
||||
} else {
|
||||
localNetworkPermissionHelper.runWithAccess(
|
||||
listOf(getFormattedUrl()),
|
||||
action = { createProject() }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun getFormattedUrl(): String {
|
||||
var url = viewModel.projectUrl.trim()
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package net.helcel.cowspent.util
|
||||
|
||||
import android.Manifest
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.widget.Toast
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.appcompat.app.AlertDialog
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import net.helcel.cowspent.R
|
||||
import java.net.Inet6Address
|
||||
import java.net.InetAddress
|
||||
|
||||
/** Handles the Android 17 permission for servers that resolve to the local network. */
|
||||
class LocalNetworkPermissionHelper(private val activity: AppCompatActivity) {
|
||||
private var onAllowed: (() -> Unit)? = null
|
||||
private var requestInProgress = false
|
||||
|
||||
private val permissionLauncher = activity.registerForActivityResult(
|
||||
ActivityResultContracts.RequestPermission()
|
||||
) { granted ->
|
||||
requestInProgress = false
|
||||
onAllowed?.takeIf { granted }?.invoke()
|
||||
onAllowed = null
|
||||
if (!granted) showDeniedMessage()
|
||||
}
|
||||
|
||||
fun runWithAccess(serverUrls: Collection<String>, action: () -> Unit) {
|
||||
if (Build.VERSION.SDK_INT < ANDROID_17 || hasPermission()) {
|
||||
action()
|
||||
return
|
||||
}
|
||||
|
||||
activity.lifecycleScope.launch {
|
||||
val isLocalServer = withContext(Dispatchers.IO) {
|
||||
serverUrls.any(::resolvesToLocalNetwork)
|
||||
}
|
||||
if (!isLocalServer || hasPermission()) {
|
||||
action()
|
||||
} else if (!requestInProgress) {
|
||||
onAllowed = action
|
||||
requestInProgress = true
|
||||
if (activity.shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_LOCAL_NETWORK)) {
|
||||
AlertDialog.Builder(activity)
|
||||
.setTitle(R.string.local_network_permission_title)
|
||||
.setMessage(R.string.local_network_permission_rationale)
|
||||
.setPositiveButton(R.string.local_network_permission_continue) { _, _ ->
|
||||
permissionLauncher.launch(Manifest.permission.ACCESS_LOCAL_NETWORK)
|
||||
}
|
||||
.setNegativeButton(android.R.string.cancel) { _, _ -> cancelRequest() }
|
||||
.setOnCancelListener { cancelRequest() }
|
||||
.show()
|
||||
} else {
|
||||
permissionLauncher.launch(Manifest.permission.ACCESS_LOCAL_NETWORK)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun cancelRequest() {
|
||||
requestInProgress = false
|
||||
onAllowed = null
|
||||
showDeniedMessage()
|
||||
}
|
||||
|
||||
private fun hasPermission() = ContextCompat.checkSelfPermission(
|
||||
activity,
|
||||
Manifest.permission.ACCESS_LOCAL_NETWORK
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
private fun resolvesToLocalNetwork(url: String): Boolean {
|
||||
val host = Uri.parse(url).host?.trim('[', ']')?.lowercase() ?: return false
|
||||
if (host == "localhost" || host.endsWith(".localhost") || host.endsWith(".local") ||
|
||||
host.endsWith(".lan") || host.endsWith(".home") || host.endsWith(".internal")
|
||||
) return true
|
||||
|
||||
return try {
|
||||
InetAddress.getAllByName(host).any { address ->
|
||||
address.isAnyLocalAddress || address.isLoopbackAddress || address.isLinkLocalAddress ||
|
||||
address.isSiteLocalAddress || (address is Inet6Address && (address.address[0].toInt() and 0xfe) == 0xfc)
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun showDeniedMessage() = Toast.makeText(
|
||||
activity,
|
||||
R.string.local_network_permission_denied,
|
||||
Toast.LENGTH_LONG
|
||||
).show()
|
||||
|
||||
private companion object {
|
||||
const val ANDROID_17 = 37
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,11 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<string name="local_network_permission_title">Allow local network access?</string>
|
||||
<string name="local_network_permission_rationale">Cowspent needs local network access to sync Cospend and Nextcloud servers hosted on your network.</string>
|
||||
<string name="local_network_permission_continue">Continue</string>
|
||||
<string name="local_network_permission_denied">Local network access was denied. Remote server sync is paused.</string>
|
||||
|
||||
<string name="app_name" translatable="false">Cowspent</string>
|
||||
|
||||
<!-- Actions -->
|
||||
|
||||
Reference in new issue
Block a user