fix(upload): keep the access to picked files until their upload is done
The photo picker and the file picker grant the read access to a picked file only to the chat that picked it, until it is closed or the process is killed. An upload that waited for the network, e.g. while the app was in the background, then couldn't read its file and failed with a SecurityException. The access is now persisted when the file is sent, and released when its upload ends or is cancelled, unless another upload of the file still needs it, and for leftovers when the app starts. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Marcel Hibbe <[email protected]>
This commit is contained in:
1 parent
9eb9693ea4
commit
95ca9f1b46
6 files changed
+264
-5
No files matched your search
@@ -62,6 +62,7 @@ import com.nextcloud.talk.utils.DeviceUtils
|
||||
import com.nextcloud.talk.utils.LiveActivities
|
||||
import com.nextcloud.talk.utils.NotificationUtils
|
||||
import com.nextcloud.talk.utils.SharedFileCopies
|
||||
import com.nextcloud.talk.utils.UploadSourceGrants
|
||||
import com.nextcloud.talk.utils.database.arbitrarystorage.ArbitraryStorageModule
|
||||
import com.nextcloud.talk.utils.database.user.UserModule
|
||||
import com.nextcloud.talk.utils.preferences.AppPreferences
|
||||
@@ -250,6 +251,8 @@ class NextcloudTalkApplication :
|
||||
appScope.launch { userManager.repairMultipleActiveUsers() }
|
||||
// the copies of shares that are done, also when no new share starts
|
||||
appScope.launch { SharedFileCopies.removeDoneShares(this@NextcloudTalkApplication) }
|
||||
// the read access to picked files whose uploads are done, also one that was cancelled before it started
|
||||
appScope.launch { UploadSourceGrants.releaseUnused(this@NextcloudTalkApplication) }
|
||||
|
||||
val accountRemovalWork = OneTimeWorkRequest.Builder(AccountRemovalWorker::class.java).build()
|
||||
val capabilitiesUpdateWork = OneTimeWorkRequest.Builder(CapabilitiesSyncWorker::class.java).build()
|
||||
|
||||
@@ -80,6 +80,7 @@ import com.nextcloud.talk.utils.Mimetype
|
||||
import com.nextcloud.talk.utils.MimetypeUtils
|
||||
import com.nextcloud.talk.utils.ParticipantPermissions
|
||||
import com.nextcloud.talk.utils.SpreedFeatures
|
||||
import com.nextcloud.talk.utils.UploadSourceGrants
|
||||
import com.nextcloud.talk.utils.UserIdUtils
|
||||
import com.nextcloud.talk.utils.throttleLatest
|
||||
import com.nextcloud.talk.utils.bundle.BundleKeys
|
||||
@@ -437,7 +438,7 @@ class ChatViewModel @AssistedInject constructor(
|
||||
// also cancel. Without this, cancel silently did nothing for any such placeholder, leaving
|
||||
// the user with no way to clear a permanently stuck upload.
|
||||
uploadReferenceToWorkId.remove(referenceId)?.let { workId ->
|
||||
UploadAndShareFilesWorker.cancelUpload(referenceId, workId)
|
||||
UploadAndShareFilesWorker.cancelUpload(referenceId, workId, _uploadedLocalPreviewMap.value[referenceId])
|
||||
}
|
||||
viewModelScope.launch {
|
||||
chatRepository.deleteTempMessageByReferenceId(referenceId)
|
||||
@@ -2400,6 +2401,8 @@ class ChatViewModel @AssistedInject constructor(
|
||||
|
||||
// enqueued right here, in the order of the calls: the queue of a conversation is chained, and the
|
||||
// slow lookup of the file info below must neither reorder the files nor die with the view model
|
||||
// the access the picker granted ends with the chat, while the upload can wait for the network
|
||||
UploadSourceGrants.keep(NextcloudTalkApplication.sharedApplication!!, fileUri)
|
||||
val workerId = enqueueUpload()
|
||||
if (!isVoiceMessage) {
|
||||
uploadReferenceToWorkId[referenceId] = workerId
|
||||
|
||||
@@ -50,6 +50,7 @@ import com.nextcloud.talk.utils.ImageCompressor
|
||||
import com.nextcloud.talk.utils.NotificationUtils
|
||||
import com.nextcloud.talk.utils.RemoteFileUtils
|
||||
import com.nextcloud.talk.utils.SharedFileCopies
|
||||
import com.nextcloud.talk.utils.UploadSourceGrants
|
||||
import com.nextcloud.talk.utils.VideoCompressor
|
||||
import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_INTERNAL_USER_ID
|
||||
import com.nextcloud.talk.utils.permissions.PlatformPermissionUtil
|
||||
@@ -130,7 +131,11 @@ class UploadAndShareFilesWorker(val context: Context, workerParameters: WorkerPa
|
||||
}
|
||||
|
||||
try {
|
||||
return doUpload()
|
||||
return doUpload().also { result ->
|
||||
// not for a retry, which reads the file again
|
||||
val sourceFile = inputData.getString(DEVICE_SOURCE_FILE)
|
||||
if (result !is Result.Retry && sourceFile != null) UploadSourceGrants.release(context, sourceFile, id)
|
||||
}
|
||||
} finally {
|
||||
referenceId?.let { cancelledReferenceIds.remove(it) }
|
||||
}
|
||||
@@ -579,6 +584,8 @@ class UploadAndShareFilesWorker(val context: Context, workerParameters: WorkerPa
|
||||
)
|
||||
// keeps a copy of a shared file until its upload is done
|
||||
.apply { SharedFileCopies.uploadTagOf(fileUri)?.let { addTag(it) } }
|
||||
// keeps the read access to a picked file until its upload is done
|
||||
.apply { UploadSourceGrants.uploadTagOf(fileUri)?.let { addTag(it) } }
|
||||
.build()
|
||||
// Chained per conversation (not enqueueUniqueWork(fileUri, ...), which ran every upload
|
||||
// fully independently) so multiple files - whether from one multi-file share or several
|
||||
@@ -602,9 +609,11 @@ class UploadAndShareFilesWorker(val context: Context, workerParameters: WorkerPa
|
||||
// Cancellation is by the WorkRequest's own id (not enqueueUniqueWork's name) since that name
|
||||
// is now shared by every file queued in the same conversation - cancelling by name would
|
||||
// cancel the whole queue instead of just this one upload.
|
||||
fun cancelUpload(referenceId: String, workerId: UUID) {
|
||||
fun cancelUpload(referenceId: String, workerId: UUID, fileUri: String?) {
|
||||
cancelledReferenceIds.add(referenceId)
|
||||
WorkManager.getInstance().cancelWorkById(workerId)
|
||||
// an upload that didn't start doesn't release the read access to its file itself
|
||||
fileUri?.let { UploadSourceGrants.releaseLater(it, exceptWorkId = workerId) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
/*
|
||||
* Nextcloud Talk - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*/
|
||||
package com.nextcloud.talk.utils
|
||||
|
||||
import android.content.ContentResolver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import androidx.core.net.toUri
|
||||
import androidx.work.WorkInfo
|
||||
import androidx.work.WorkManager
|
||||
import androidx.work.WorkQuery
|
||||
import com.nextcloud.talk.application.NextcloudTalkApplication
|
||||
import kotlinx.coroutines.launch
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.ExecutionException
|
||||
|
||||
/**
|
||||
* The read access to the files picked for an upload, e.g. in the photo picker or the file picker. The pickers grant it
|
||||
* only to the chat that picked them, until it is closed or the process is killed, while the upload can wait for the
|
||||
* network for days. So the access is persisted when the upload is queued, and released once no upload needs it.
|
||||
*
|
||||
* The app persists the access to files only for uploads: every persisted one without an unfinished upload is released.
|
||||
*/
|
||||
object UploadSourceGrants {
|
||||
|
||||
private val TAG = UploadSourceGrants::class.java.simpleName
|
||||
|
||||
private const val UPLOAD_TAG_PREFIX = "upload_source_"
|
||||
|
||||
/** The tag for the upload of [fileUri] if it is a content uri, whose read access is kept until it is done. */
|
||||
fun uploadTagOf(fileUri: String): String? =
|
||||
fileUri.takeIf { it.toUri().scheme == ContentResolver.SCHEME_CONTENT }?.let { UPLOAD_TAG_PREFIX + it }
|
||||
|
||||
/** Keeps the read access to [fileUri] for its upload, if its provider allows it. */
|
||||
fun keep(context: Context, fileUri: String) {
|
||||
if (uploadTagOf(fileUri) == null) return
|
||||
try {
|
||||
context.contentResolver.takePersistableUriPermission(fileUri.toUri(), Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
} catch (e: SecurityException) {
|
||||
// e.g. a file of the app itself, or of a provider that doesn't allow it
|
||||
Log.d(TAG, "The read access to $fileUri can't be kept", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases the persisted read access to [fileUri] unless an upload other than [exceptWorkId], the one that is just
|
||||
* ending, still needs it. Blocks while it asks WorkManager for its uploads.
|
||||
*/
|
||||
fun release(context: Context, fileUri: String, exceptWorkId: UUID) {
|
||||
val uri = fileUri.toUri()
|
||||
val isKept = context.contentResolver.persistedUriPermissions.any { it.isReadPermission && it.uri == uri }
|
||||
if (isKept) releaseUnless(context, listOf(uri), exceptWorkId)
|
||||
}
|
||||
|
||||
/** [release] in the scope of the app, e.g. for an upload that was cancelled before it started. */
|
||||
fun releaseLater(fileUri: String, exceptWorkId: UUID) {
|
||||
val application = NextcloudTalkApplication.sharedApplication!!
|
||||
application.appScope.launch { release(application, fileUri, exceptWorkId) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases the persisted read access to all files without an unfinished upload, e.g. of uploads that were removed
|
||||
* before they ran. Run when the app starts, before a file can be picked. Blocks while it asks WorkManager for their
|
||||
* uploads.
|
||||
*/
|
||||
fun releaseUnused(context: Context) {
|
||||
val kept = context.contentResolver.persistedUriPermissions.filter { it.isReadPermission }.map { it.uri }
|
||||
releaseUnless(context, kept, exceptWorkId = null)
|
||||
}
|
||||
|
||||
/** Releases the read access to those of [uris] without an unfinished upload other than [exceptWorkId]. */
|
||||
private fun releaseUnless(context: Context, uris: List<Uri>, exceptWorkId: UUID?) {
|
||||
val uploading = urisWithUnfinishedUpload(context, uris, exceptWorkId)
|
||||
uris.filterNot { it in uploading }.forEach { uri ->
|
||||
try {
|
||||
context.contentResolver.releasePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
} catch (e: SecurityException) {
|
||||
Log.w(TAG, "Failed to release the read access to $uri", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The ones of [uris] with an unfinished upload other than [exceptWorkId], all of them when WorkManager can't tell,
|
||||
* so the access is kept when in doubt. One query for all of them.
|
||||
*/
|
||||
private fun urisWithUnfinishedUpload(context: Context, uris: List<Uri>, exceptWorkId: UUID?): Set<Uri> {
|
||||
if (uris.isEmpty()) return emptySet()
|
||||
val query = WorkQuery.Builder.fromTags(uris.mapNotNull { uploadTagOf(it.toString()) })
|
||||
.addStates(listOf(WorkInfo.State.ENQUEUED, WorkInfo.State.RUNNING, WorkInfo.State.BLOCKED))
|
||||
.build()
|
||||
return try {
|
||||
WorkManager.getInstance(context).getWorkInfos(query).get()
|
||||
.filter { it.id != exceptWorkId }
|
||||
.flatMap { it.tags }
|
||||
.filter { it.startsWith(UPLOAD_TAG_PREFIX) }
|
||||
.map { it.removePrefix(UPLOAD_TAG_PREFIX).toUri() }
|
||||
.toSet()
|
||||
} catch (e: ExecutionException) {
|
||||
Log.w(TAG, "Failed to get the uploads of picked files", e)
|
||||
uris.toSet()
|
||||
} catch (e: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
uris.toSet()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,9 @@ import androidx.work.testing.WorkManagerTestInitHelper
|
||||
import com.nextcloud.talk.data.database.dao.ChatMessagesDao
|
||||
import com.nextcloud.talk.data.database.model.SendStatus
|
||||
import com.nextcloud.talk.users.UserManager
|
||||
import com.nextcloud.talk.utils.UploadSourceGrants
|
||||
import java.util.concurrent.Executor
|
||||
import java.util.concurrent.Executors
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
@@ -56,6 +59,17 @@ class UploadAndShareFilesWorkerTest {
|
||||
verify(chatDao).updateTempMessageSendStatus(CONVERSATION_ID, "ref-b", SendStatus.FAILED)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an upload that ended releases the read access to its file`() {
|
||||
// on a thread of its own, as in the app: the worker asks WorkManager for the other uploads of its file
|
||||
val workManager = initWorkManager(Executors.newSingleThreadExecutor())
|
||||
UploadSourceGrants.keep(context(), "content://media/ref-a")
|
||||
|
||||
awaitFinished(workManager, upload("ref-a"))
|
||||
|
||||
assertEquals(emptyList<Any>(), context().contentResolver.persistedUriPermissions)
|
||||
}
|
||||
|
||||
private fun upload(referenceId: String): UUID =
|
||||
UploadAndShareFilesWorker.upload(
|
||||
userId = ACCOUNT_ID,
|
||||
@@ -67,7 +81,7 @@ class UploadAndShareFilesWorkerTest {
|
||||
internalConversationId = CONVERSATION_ID
|
||||
)
|
||||
|
||||
private fun initWorkManager(): WorkManager {
|
||||
private fun initWorkManager(executor: Executor = SynchronousExecutor()): WorkManager {
|
||||
val factory = object : WorkerFactory() {
|
||||
override fun createWorker(
|
||||
appContext: Context,
|
||||
@@ -80,7 +94,7 @@ class UploadAndShareFilesWorkerTest {
|
||||
}
|
||||
}
|
||||
val configuration = Configuration.Builder()
|
||||
.setExecutor(SynchronousExecutor())
|
||||
.setExecutor(executor)
|
||||
.setWorkerFactory(factory)
|
||||
.build()
|
||||
WorkManagerTestInitHelper.initializeTestWorkManager(context(), configuration)
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
/*
|
||||
* Nextcloud Talk - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*/
|
||||
package com.nextcloud.talk.utils
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import androidx.core.net.toUri
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import androidx.work.Configuration
|
||||
import androidx.work.Constraints
|
||||
import androidx.work.NetworkType
|
||||
import androidx.work.OneTimeWorkRequest
|
||||
import androidx.work.WorkManager
|
||||
import androidx.work.Worker
|
||||
import androidx.work.WorkerParameters
|
||||
import androidx.work.testing.SynchronousExecutor
|
||||
import androidx.work.testing.WorkManagerTestInitHelper
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import java.util.UUID
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(application = Application::class, sdk = [33])
|
||||
class UploadSourceGrantsTest {
|
||||
|
||||
private val context: Context = ApplicationProvider.getApplicationContext()
|
||||
|
||||
private val picked = "content://media/picker/0/com.android.providers.media.photopicker/media/1"
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
val configuration = Configuration.Builder().setExecutor(SynchronousExecutor()).build()
|
||||
WorkManagerTestInitHelper.initializeTestWorkManager(context, configuration)
|
||||
}
|
||||
|
||||
private fun keptUris(): List<String> = context.contentResolver.persistedUriPermissions.map { it.uri.toString() }
|
||||
|
||||
// an upload of [fileUri] that waits for the network, as it does without one
|
||||
private fun enqueueUnfinishedUpload(fileUri: String): UUID {
|
||||
val upload = OneTimeWorkRequest.Builder(WaitingWorker::class.java)
|
||||
.setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
|
||||
.addTag(UploadSourceGrants.uploadTagOf(fileUri)!!)
|
||||
.build()
|
||||
WorkManager.getInstance(context).enqueue(upload).result.get()
|
||||
return upload.id
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the read access to a picked file is kept for its upload`() {
|
||||
UploadSourceGrants.keep(context, picked)
|
||||
|
||||
assertEquals(listOf(picked), keptUris())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `only the uploads of content uris are tagged`() {
|
||||
assertEquals("upload_source_$picked", UploadSourceGrants.uploadTagOf(picked))
|
||||
assertNull(UploadSourceGrants.uploadTagOf("file:///data/voice.mp3"))
|
||||
assertNull(UploadSourceGrants.uploadTagOf("/data/voice.mp3"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the read access is released when its upload ends`() {
|
||||
UploadSourceGrants.keep(context, picked)
|
||||
val upload = enqueueUnfinishedUpload(picked)
|
||||
|
||||
UploadSourceGrants.release(context, picked, exceptWorkId = upload)
|
||||
|
||||
assertEquals(emptyList<String>(), keptUris())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the read access is kept while another upload of the file is unfinished`() {
|
||||
UploadSourceGrants.keep(context, picked)
|
||||
val ending = enqueueUnfinishedUpload(picked)
|
||||
enqueueUnfinishedUpload(picked)
|
||||
|
||||
UploadSourceGrants.release(context, picked, exceptWorkId = ending)
|
||||
|
||||
assertEquals(listOf(picked), keptUris())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the read access without an unfinished upload is released when the app starts`() {
|
||||
val uploaded = "content://media/picker/0/com.android.providers.media.photopicker/media/2"
|
||||
UploadSourceGrants.keep(context, picked)
|
||||
UploadSourceGrants.keep(context, uploaded)
|
||||
enqueueUnfinishedUpload(picked)
|
||||
|
||||
UploadSourceGrants.releaseUnused(context)
|
||||
|
||||
assertEquals(listOf(picked), keptUris())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the access to a file that isn't released stays as it is`() {
|
||||
UploadSourceGrants.keep(context, picked)
|
||||
val other = picked.toUri().buildUpon().appendPath("other").toString()
|
||||
|
||||
UploadSourceGrants.release(context, other, UUID.randomUUID())
|
||||
|
||||
assertEquals(listOf(picked), keptUris())
|
||||
}
|
||||
|
||||
class WaitingWorker(context: Context, parameters: WorkerParameters) : Worker(context, parameters) {
|
||||
override fun doWork(): Result = Result.success()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user