Modern Apps git

← Modern-Apps.git

share: multi-file shares no longer silently drop a file on a name collision

Commit
8369eca00a32ce918c52d6588bc8aa155ff7397d
Author
Vayun Mathur <[email protected]>
When
2026-12-01 00:10 UTC (5 days ago)
Parents
b690502
uriToTempFile staged every URI to
cache/share_send/<displayName> with overwrite = true, so
two distinct files sharing a display name (photo.jpg from
two folders, IMG_0001.jpg from two apps) staged onto the
same path: the second copy overwrote the first, the returned
list held the same file twice, and the receiver got the
second file twice while the first never left the device —
no error anywhere. The receive side already dedupes names
(ReceivedFileStore.uniqueFile); the send side did not.

Staging now goes through uniqueFile for both the file://
copy and the content:// stream branches, an empty staging
copy is deleted instead of consuming a name, and the
self-copy guard for staged text is preserved. New regression
tests cover file-URI and content-URI collisions plus
single-file stability (2 of 3 failed pre-fix). Manifest
filters, shortcuts, notification intents, the save
trampoline and retention were audited and cleared. Verified:
:share:testDevUnitTest 228 tests pass; the one lint error
is pre-existing in another agent's in-flight lint work.

Diff

share/src/main/java/com/vayunmathur/share/platform/ShareViewModel.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/ShareViewModel.kt b/share/src/main/java/com/vayunmathur/share/platform/ShareViewModel.ktindex 49cf988cca..e779c8aa3d 100644--- a/share/src/main/java/com/vayunmathur/share/platform/ShareViewModel.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/ShareViewModel.kt@@ -371,21 +371,29 @@ internal fun uriToTempFile(context: Context, uri: Uri): File? {     return try {         val name = resolveDisplayName(context, uri) ?: "share_file_${System.currentTimeMillis()}"         val safeName = name.replace("/", "_").replace("\\", "_")-        val dest = File(context.cacheDir, "share_send/$safeName")-        dest.parentFile?.mkdirs()+        val stagingDir = File(context.cacheDir, "share_send")+        stagingDir.mkdirs()+        val candidate = File(stagingDir, safeName)         if (uri.scheme == "file") {             val src = File(uri.path ?: "")             if (src.exists() && src.isFile) {                 // Copying a file onto itself truncates it, and shared text is staged here.-                if (src.canonicalPath == dest.canonicalPath) return src+                if (src.canonicalPath == candidate.canonicalPath) return src                 if (src.length() > MAX_SHARED_FILE_BYTES) {                     Log.status(TAG, "uriToTempFile skipped oversized file (> $MAX_SHARED_FILE_BYTES bytes): $uri")                     return null                 }-                src.copyTo(dest, overwrite = true)+                // Distinct sources can share one display name (two `photo.jpg` in a+                // SEND_MULTIPLE batch): staging both onto `candidate` made the second+                // copy overwrite the first, so the transfer sent the second file+                // twice and the first never left the device. Dedupe like the+                // receive side (`ReceivedFileStore.uniqueFile`) instead.+                val dest = ReceivedFileStore.uniqueFile(stagingDir, safeName)+                src.copyTo(dest, overwrite = false)                 return dest             }         }+        val dest = ReceivedFileStore.uniqueFile(stagingDir, safeName)         // Size pre-check, enforced again while streaming below because a         // provider may omit or understate its declared size.         declaredSharedSize(context, uri)?.let { size ->@@ -417,7 +425,12 @@ internal fun uriToTempFile(context: Context, uri: Uri): File? {             Log.status(TAG, "uriToTempFile skipped oversized file (> $MAX_SHARED_FILE_BYTES bytes): $uri")             return null         }-        if (dest.exists() && dest.length() > 0) dest else null+        if (dest.exists() && dest.length() > 0) dest else {+            // No bytes arrived; leaving the empty staging copy would consume the+            // name and force the next same-named file onto a suffixed one.+            dest.delete()+            null+        }     } catch (e: Exception) {         Log.status(TAG, "uriToTempFile failed for $uri", e)         null
share/src/test/java/com/vayunmathur/share/platform/UriToTempFileDedupTest.kt
diff --git a/share/src/test/java/com/vayunmathur/share/platform/UriToTempFileDedupTest.kt b/share/src/test/java/com/vayunmathur/share/platform/UriToTempFileDedupTest.ktnew file mode 100644index 0000000000..ff0abf2f51--- /dev/null+++ b/share/src/test/java/com/vayunmathur/share/platform/UriToTempFileDedupTest.kt@@ -0,0 +1,123 @@+package com.vayunmathur.share.platform++import android.app.Application+import android.content.ContentProvider+import android.content.ContentValues+import android.database.Cursor+import android.database.MatrixCursor+import android.net.Uri+import android.os.ParcelFileDescriptor+import android.provider.OpenableColumns+import androidx.test.core.app.ApplicationProvider+import java.io.ByteArrayInputStream+import java.io.File+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotEquals+import org.junit.Assert.assertNotNull+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.shadows.ShadowContentResolver++/**+ * Regression: two outgoing URIs that share one display name (two `photo.jpg`+ * from different folders in a SEND_MULTIPLE batch, say) must stage to two+ * distinct copies. Before the fix both staged onto the same+ * `cache/share_send/<name>` file, the second copy overwrote the first, and+ * the transfer streamed the second file twice while the first never left+ * the device.+ */+@RunWith(RobolectricTestRunner::class)+class UriToTempFileDedupTest {+    private val app: Application get() = ApplicationProvider.getApplicationContext()++    private fun cleanStaging(namePrefix: String) {+        File(app.cacheDir, "share_send").listFiles()+            ?.filter { it.name.startsWith(namePrefix) }+            ?.forEach { it.delete() }+    }++    @Test+    fun `two file uris with same display name stage to distinct copies`() {+        cleanStaging("dedup-photo")+        val dirA = File(app.cacheDir, "dedup-a").apply { mkdirs() }+        val dirB = File(app.cacheDir, "dedup-b").apply { mkdirs() }+        val a = File(dirA, "dedup-photo.jpg").apply { writeText("first-photo") }+        val b = File(dirB, "dedup-photo.jpg").apply { writeText("second-photo") }++        val outA = uriToTempFile(app, Uri.fromFile(a))+        val outB = uriToTempFile(app, Uri.fromFile(b))++        assertNotNull(outA)+        assertNotNull(outB)+        assertNotEquals(outA!!.absolutePath, outB!!.absolutePath)+        assertEquals("first-photo", outA.readText())+        assertEquals("second-photo", outB.readText())+        assertEquals(+            setOf("dedup-photo.jpg", "dedup-photo_1.jpg"),+            setOf(outA.name, outB.name),+        )+    }++    /** Every item reports the same display name, like two `IMG_0001.jpg` exports. */+    class SameNameProvider : ContentProvider() {+        override fun onCreate(): Boolean = true+        override fun query(+            uri: Uri,+            projection: Array<out String>?,+            selection: String?,+            selectionArgs: Array<out String>?,+            sortOrder: String?,+        ): Cursor {+            val columns = projection ?: arrayOf(OpenableColumns.DISPLAY_NAME)+            val cursor = MatrixCursor(columns)+            cursor.addRow(Array<Any?>(columns.size) { i -> if (columns[i] == OpenableColumns.DISPLAY_NAME) "dedup-doc.txt" else -1L })+            return cursor+        }+        override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor =+            throw UnsupportedOperationException("streams are shadow-registered instead")+        override fun getType(uri: Uri): String = "text/plain"+        override fun insert(uri: Uri, values: ContentValues?): Uri? = null+        override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0+        override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int = 0+    }++    @Test+    fun `two content uris with same display name stage to distinct copies`() {+        cleanStaging("dedup-doc")+        ShadowContentResolver.registerProviderInternal(+            "com.example.dedup",+            SameNameProvider().apply { attachInfo(app, null) },+        )+        Shadows.shadowOf(app.contentResolver)+            .registerInputStream(+                Uri.parse("content://com.example.dedup/item/1"),+                ByteArrayInputStream("first-doc".toByteArray()),+            )+        Shadows.shadowOf(app.contentResolver)+            .registerInputStream(+                Uri.parse("content://com.example.dedup/item/2"),+                ByteArrayInputStream("second-doc".toByteArray()),+            )++        val outA = uriToTempFile(app, Uri.parse("content://com.example.dedup/item/1"))+        val outB = uriToTempFile(app, Uri.parse("content://com.example.dedup/item/2"))++        assertNotNull(outA)+        assertNotNull(outB)+        assertNotEquals(outA!!.absolutePath, outB!!.absolutePath)+        assertEquals("first-doc", outA.readText())+        assertEquals("second-doc", outB.readText())+    }++    @Test+    fun `single file uri still stages under its own name`() {+        cleanStaging("dedup-solo")+        val src = File(app.cacheDir, "dedup-solo.txt").apply { writeText("solo") }+        val out = uriToTempFile(app, Uri.fromFile(src))+        assertNotNull(out)+        assertEquals("dedup-solo.txt", out!!.name)+        assertEquals("solo", out.readText())+    }+}