Fix local network
This commit is contained in:
6 files changed
+167
-8
No files matched your search
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
<uses-permission android:name="android.permission.INTERNET" />
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
<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-permission android:name="android.permission.CAMERA" />
|
||||||
<uses-feature
|
<uses-feature
|
||||||
android:name="android.hardware.camera"
|
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.theme.ThemeUtils
|
||||||
import net.helcel.cowspent.util.CospendClientUtil
|
import net.helcel.cowspent.util.CospendClientUtil
|
||||||
import net.helcel.cowspent.util.CospendClientUtil.LoginStatus
|
import net.helcel.cowspent.util.CospendClientUtil.LoginStatus
|
||||||
|
import net.helcel.cowspent.util.LocalNetworkPermissionHelper
|
||||||
import net.helcel.cowspent.util.SecureStorage
|
import net.helcel.cowspent.util.SecureStorage
|
||||||
import java.net.URLDecoder
|
import java.net.URLDecoder
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
@@ -72,6 +73,7 @@ class AccountActivity : AppCompatActivity() {
|
|||||||
private lateinit var preferences: SharedPreferences
|
private lateinit var preferences: SharedPreferences
|
||||||
private var useWebLogin = true
|
private var useWebLogin = true
|
||||||
private var showLoginDialog by mutableStateOf(false)
|
private var showLoginDialog by mutableStateOf(false)
|
||||||
|
private val localNetworkPermissionHelper = LocalNetworkPermissionHelper(this)
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
enableEdgeToEdge()
|
enableEdgeToEdge()
|
||||||
@@ -101,7 +103,9 @@ class AccountActivity : AppCompatActivity() {
|
|||||||
AccountScreen(
|
AccountScreen(
|
||||||
viewModel = viewModel,
|
viewModel = viewModel,
|
||||||
onBack = { finish() },
|
onBack = { finish() },
|
||||||
onConnect = { login() },
|
onConnect = {
|
||||||
|
withLocalNetworkPermission(CospendClientUtil.formatURL(viewModel.serverUrl)) { login() }
|
||||||
|
},
|
||||||
onSsoClick = { isChecked ->
|
onSsoClick = { isChecked ->
|
||||||
if (isChecked) {
|
if (isChecked) {
|
||||||
showLoginDialog = true
|
showLoginDialog = true
|
||||||
@@ -194,6 +198,13 @@ class AccountActivity : AppCompatActivity() {
|
|||||||
.cowspentServerSyncHelper.runAccountProjectsSync()
|
.cowspentServerSyncHelper.runAccountProjectsSync()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun withLocalNetworkPermission(serverUrl: String, action: () -> Unit) {
|
||||||
|
localNetworkPermissionHelper.runWithAccess(
|
||||||
|
listOf(serverUrl),
|
||||||
|
action = action
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
@Deprecated("Deprecated in Java")
|
@Deprecated("Deprecated in Java")
|
||||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||||
super.onActivityResult(requestCode, resultCode, data)
|
super.onActivityResult(requestCode, resultCode, data)
|
||||||
@@ -213,6 +224,7 @@ class AccountActivity : AppCompatActivity() {
|
|||||||
viewModel.serverUrl = ssoAccount.url
|
viewModel.serverUrl = ssoAccount.url
|
||||||
viewModel.username = ssoAccount.userId
|
viewModel.username = ssoAccount.userId
|
||||||
|
|
||||||
|
withLocalNetworkPermission(ssoAccount.url) {
|
||||||
startInitialAccountSync()
|
startInitialAccountSync()
|
||||||
|
|
||||||
val resultData = Intent()
|
val resultData = Intent()
|
||||||
@@ -221,6 +233,7 @@ class AccountActivity : AppCompatActivity() {
|
|||||||
finish()
|
finish()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.e(TAG, "SSO account selection failed", e)
|
Log.e(TAG, "SSO account selection failed", e)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -55,6 +55,7 @@ import net.helcel.cowspent.util.CospendClientUtil
|
|||||||
import net.helcel.cowspent.util.ExportUtil
|
import net.helcel.cowspent.util.ExportUtil
|
||||||
import net.helcel.cowspent.util.ICallback
|
import net.helcel.cowspent.util.ICallback
|
||||||
import net.helcel.cowspent.util.IRefreshBillsListCallback
|
import net.helcel.cowspent.util.IRefreshBillsListCallback
|
||||||
|
import net.helcel.cowspent.util.LocalNetworkPermissionHelper
|
||||||
import net.helcel.cowspent.util.SyncSettings
|
import net.helcel.cowspent.util.SyncSettings
|
||||||
import net.helcel.cowspent.util.SupportUtil
|
import net.helcel.cowspent.util.SupportUtil
|
||||||
import net.helcel.cowspent.util.VersatileProjectSyncClient
|
import net.helcel.cowspent.util.VersatileProjectSyncClient
|
||||||
@@ -90,6 +91,7 @@ class BillsListViewActivity :
|
|||||||
|
|
||||||
private var mActionMode: ActionMode? = null
|
private var mActionMode: ActionMode? = null
|
||||||
private lateinit var db: CowspentSQLiteOpenHelper
|
private lateinit var db: CowspentSQLiteOpenHelper
|
||||||
|
private val localNetworkPermissionHelper = LocalNetworkPermissionHelper(this)
|
||||||
|
|
||||||
private val syncCallBack = object : ICallback {
|
private val syncCallBack = object : ICallback {
|
||||||
override fun onFinish() {
|
override fun onFinish() {
|
||||||
@@ -341,15 +343,23 @@ class BillsListViewActivity :
|
|||||||
}
|
}
|
||||||
viewModel.isRefreshing = false
|
viewModel.isRefreshing = false
|
||||||
|
|
||||||
synchronize(SyncTrigger.APP_OPEN)
|
registerBroadcastReceiver()
|
||||||
|
isActivityVisible = true
|
||||||
|
|
||||||
lifecycleScope.launch {
|
synchronize(SyncTrigger.APP_OPEN)
|
||||||
syncNewlyDiscoveredProjects(withContext(Dispatchers.IO) { db.projects })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
registerBroadcastReceiver()
|
private fun configuredServerUrls(projects: List<DBProject>): List<String> = buildList {
|
||||||
updateAvatarInDrawer(CowspentServerSyncHelper.isNextcloudAccountConfigured(this))
|
addAll(projects.filterNot { it.isLocal }.mapNotNull { it.serverUrl })
|
||||||
isActivityVisible = true
|
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() {
|
override fun onPause() {
|
||||||
@@ -802,6 +812,24 @@ class BillsListViewActivity :
|
|||||||
|
|
||||||
@VisibleForTesting
|
@VisibleForTesting
|
||||||
internal fun synchronize(trigger: SyncTrigger) {
|
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)
|
val preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext)
|
||||||
// isSyncPossible is networkConnected && !offlineMode, so offline mode is already covered
|
// isSyncPossible is networkConnected && !offlineMode, so offline mode is already covered
|
||||||
// here - including for a manual refresh, which cannot currently override it.
|
// here - including for a manual refresh, which cannot currently override it.
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ class NewProjectActivity : AppCompatActivity() {
|
|||||||
|
|
||||||
internal val viewModel: NewProjectViewModel by viewModels()
|
internal val viewModel: NewProjectViewModel by viewModels()
|
||||||
private lateinit var db: CowspentSQLiteOpenHelper
|
private lateinit var db: CowspentSQLiteOpenHelper
|
||||||
|
private val localNetworkPermissionHelper = LocalNetworkPermissionHelper(this)
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
enableEdgeToEdge()
|
enableEdgeToEdge()
|
||||||
@@ -136,7 +137,16 @@ class NewProjectActivity : AppCompatActivity() {
|
|||||||
viewModel.isAuthenticatedAccount = db.cowspentServerSyncHelper.canCreateAuthenticatedProject(fakeProj)
|
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 {
|
private fun getFormattedUrl(): String {
|
||||||
var url = viewModel.projectUrl.trim()
|
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"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
<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>
|
<string name="app_name" translatable="false">Cowspent</string>
|
||||||
|
|
||||||
<!-- Actions -->
|
<!-- Actions -->
|
||||||
|
|||||||
Reference in new issue
Block a user