Modern Apps git

← Modern-Apps.git

notes: deleting an image block no longer deletes shared image files

Commit
63cbc85f2ac3e3ebcb859427214e4eb96948d0e1
Author
Vayun Mathur <[email protected]>
When
2026-11-30 19:09 UTC (5 days ago)
Parents
eb708ae
Imported images are content-addressed (sha256.jpg) and deduped, so
the same photo in two notes — or twice in one — is one file with
several references. Deleting an image block deleted that file
unconditionally, leaving every other reference rendering blank and
silently dropped from markdown export.

Block deletion now removes the block locally, then deletes the file
only when nothing references it: the edited note's remaining blocks
are checked directly, and NotesRepository.isImageReferenced checks
every other note including tombstones (which sync can resurrect).
The edited note is excluded from the DB check because its stored
copy still contains the just-removed block until the debounced
save lands. New repository and ViewModel tests: shared file survives,
unshared file is deleted, tombstone references count. Verified:
:notes:testDevUnitTest + :notes:lint pass (241 tests; warnings are
pre-existing on untouched files).

Diff

notes/src/main/java/com/vayunmathur/notes/data/NotesRepository.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/data/NotesRepository.kt b/notes/src/main/java/com/vayunmathur/notes/data/NotesRepository.ktindex 8855075eef..1620cd37c8 100644--- a/notes/src/main/java/com/vayunmathur/notes/data/NotesRepository.kt+++ b/notes/src/main/java/com/vayunmathur/notes/data/NotesRepository.kt@@ -94,6 +94,21 @@ class NotesRepository private constructor(context: Context) :         return dao.purgeTombstonesOlderThan(cutoff)     } +    /**+     * True when any note other than [excludingNoteId] still references the+     * image file [fileName]. Image files are content-addressed, so identical+     * images in different notes (or twice in one note) share one file: that+     * file must not be deleted while another reference remains. Tombstones+     * count as references — a deleted note can be resurrected by sync, and+     * losing its image file would lose the image with it.+     */+    suspend fun isImageReferenced(fileName: String, excludingNoteId: Long): Boolean =+        dao.getAllIncludingDeleted().any { note ->+            note.id != excludingNoteId && note.body().blocks.any {+                it is NoteBlock.Image && it.fileName == fileName+            }+        }+     suspend fun getAllSnapshots(): List<SyncSnapshot> = snapshotDao.getAll()     suspend fun upsertSnapshot(snapshot: SyncSnapshot) = snapshotDao.upsert(snapshot)     suspend fun deleteSnapshotBySyncId(syncId: String) = snapshotDao.deleteBySyncId(syncId)
notes/src/main/java/com/vayunmathur/notes/platform/NotesViewModel.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/platform/NotesViewModel.kt b/notes/src/main/java/com/vayunmathur/notes/platform/NotesViewModel.ktindex 3c60b54714..a65c5dcbf9 100644--- a/notes/src/main/java/com/vayunmathur/notes/platform/NotesViewModel.kt+++ b/notes/src/main/java/com/vayunmathur/notes/platform/NotesViewModel.kt@@ -126,6 +126,25 @@ class NotesViewModel(         viewModelScope.launch(Dispatchers.IO) { repository.upsertAll(notes) }     } +    /**+     * Deletes the image file [fileName] only when nothing still references+     * it. Image files are content-addressed (see [NoteImageStore.import]):+     * identical images dedupe to one shared file, so deleting one image+     * block must not delete the file while another note — or another block+     * in the same note ([stillReferenced], computed by the caller after the+     * block is removed locally) — still points at it. The note being edited+     * is excluded from the database check because its stored copy still+     * contains the just-removed block until the debounced save lands.+     */+    fun deleteImageIfUnreferenced(fileName: String, excludingNoteId: Long, stillReferenced: Boolean) {+        if (stillReferenced) return+        viewModelScope.launch(Dispatchers.IO) {+            if (!repository.isImageReferenced(fileName, excludingNoteId)) {+                NoteImageStore.delete(getApplication(), fileName)+            }+        }+    }+     fun renameTag(from: String, to: String) {         viewModelScope.launch(Dispatchers.IO) { repository.renameTag(from, to) }     }
notes/src/main/java/com/vayunmathur/notes/ui/NotePage.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/ui/NotePage.kt b/notes/src/main/java/com/vayunmathur/notes/ui/NotePage.ktindex f4732cc62a..b6a09484dd 100644--- a/notes/src/main/java/com/vayunmathur/notes/ui/NotePage.kt+++ b/notes/src/main/java/com/vayunmathur/notes/ui/NotePage.kt@@ -190,9 +190,20 @@ fun NotePage(                 val i = blocks.indexOfFirst { it.id == id }                 if (i < 0) return                 val block = blocks[i]-                if (block is NoteBlock.Image) NoteImageStore.delete(context, block.fileName)                 blocks.removeAt(i)                 if (blocks.isEmpty()) blocks.add(NoteBlock.Text("", randomBlockId()))+                if (block is NoteBlock.Image) {+                    // Content-addressed images dedupe to one shared file:+                    // only delete it when no other block or note references+                    // it (see NotesViewModel.deleteImageIfUnreferenced).+                    notesViewModel.deleteImageIfUnreferenced(+                        fileName = block.fileName,+                        excludingNoteId = note.id,+                        stillReferenced = blocks.any {+                            it is NoteBlock.Image && it.fileName == block.fileName+                        },+                    )+                }                 commit()             } 
notes/src/test/java/com/vayunmathur/notes/data/NotesRepositoryTest.kt
diff --git a/notes/src/test/java/com/vayunmathur/notes/data/NotesRepositoryTest.kt b/notes/src/test/java/com/vayunmathur/notes/data/NotesRepositoryTest.ktindex ba31821b71..aaba5eea08 100644--- a/notes/src/test/java/com/vayunmathur/notes/data/NotesRepositoryTest.kt+++ b/notes/src/test/java/com/vayunmathur/notes/data/NotesRepositoryTest.kt@@ -146,6 +146,34 @@ class NotesRepositoryTest {         assertEquals("plain", repo.getBySyncId("plain")!!.title)     } +    @Test fun imageReferencedExcludesOnlyTheGivenNote() = runTest {+        // Content-addressed images are shared: the same file name can be+        // referenced by several notes (and by tombstones, which sync can+        // resurrect). The reference check must only exclude the edited note.+        val sharedBody = NoteBody(listOf(+            NoteBlock.Image("shared.jpg", id = "i1"),+            NoteBlock.Image("solo.jpg", id = "i2"),+        ))+        val aId = repo.upsert(Note(title = "A", content = "", syncId = "img-a").withBody(sharedBody))+        repo.upsert(Note(title = "B", content = "").withBody(+            NoteBody(listOf(NoteBlock.Image("shared.jpg", id = "i3"))),+        ).copy(syncId = "img-b"))+        repo.upsertRaw(Note(title = "gone", content = "", syncId = "img-gone", deleted = true).withBody(+            NoteBody(listOf(NoteBlock.Image("gone.jpg", id = "i4"))),+        ))++        // Another live note still references shared.jpg.+        assertTrue(repo.isImageReferenced("shared.jpg", excludingNoteId = aId))+        // solo.jpg is referenced only by the excluded note.+        assertTrue(!repo.isImageReferenced("solo.jpg", excludingNoteId = aId))+        assertTrue(repo.isImageReferenced("solo.jpg", excludingNoteId = 424242L))+        // A tombstone's image still counts: deleting it would lose the image+        // if the note is ever resurrected.+        assertTrue(repo.isImageReferenced("gone.jpg", excludingNoteId = aId))+        // An unreferenced file is not reported.+        assertTrue(!repo.isImageReferenced("missing.jpg", excludingNoteId = aId))+    }+     @Test fun readAndClearLegacyWithoutLegacyDbIsEmpty() = runTest {         assertTrue(repo.readAndClearLegacyNotes().isEmpty())     }
notes/src/test/java/com/vayunmathur/notes/platform/NotesViewModelTest.kt
diff --git a/notes/src/test/java/com/vayunmathur/notes/platform/NotesViewModelTest.kt b/notes/src/test/java/com/vayunmathur/notes/platform/NotesViewModelTest.ktindex 8a98892364..2847b35d7b 100644--- a/notes/src/test/java/com/vayunmathur/notes/platform/NotesViewModelTest.kt+++ b/notes/src/test/java/com/vayunmathur/notes/platform/NotesViewModelTest.kt@@ -4,6 +4,9 @@ import android.app.Application import android.net.Uri import androidx.test.core.app.ApplicationProvider import com.vayunmathur.notes.data.Note+import com.vayunmathur.notes.data.NoteBlock+import com.vayunmathur.notes.data.NoteBody+import com.vayunmathur.notes.data.withBody import com.vayunmathur.notes.seedNotesDb import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch@@ -180,6 +183,50 @@ class NotesViewModelTest {         assertTrue(titles.none { it.contains("oversized-skip") }, "titles=$titles")     } +    @Test fun deleteImageIfUnreferencedKeepsSharedFileAndDeletesUnshared() {+        // Regression: image files are content-addressed, so two notes that+        // imported the same photo reference ONE file. Deleting the image+        // block from one note used to delete that shared file, silently+        // blanking the image in the other note (and dropping it from its+        // export, which omits undecodable images).+        val vm = vm()+        val shared = NoteImageStore.fileFor(app, "vm-shared.jpg").apply { writeBytes(byteArrayOf(1, 2, 3)) }+        val solo = NoteImageStore.fileFor(app, "vm-solo.jpg").apply { writeBytes(byteArrayOf(4, 5, 6)) }+        val keptLocal = NoteImageStore.fileFor(app, "vm-kept-local.jpg").apply { writeBytes(byteArrayOf(7, 8, 9)) }+        val aId = runBlocking {+            repo.upsert(+                Note(title = "A", content = "", syncId = "vm-img-a").withBody(+                    NoteBody(listOf(+                        NoteBlock.Image("vm-shared.jpg", id = "a-shared"),+                        NoteBlock.Image("vm-solo.jpg", id = "a-solo"),+                        NoteBlock.Image("vm-kept-local.jpg", id = "a-kept"),+                    )),+                ),+            )+        }+        runBlocking {+            repo.upsert(+                Note(title = "B", content = "", syncId = "vm-img-b").withBody(+                    NoteBody(listOf(NoteBlock.Image("vm-shared.jpg", id = "b-shared"))),+                ),+            )+        }++        // Deleting A's copy of the shared image must keep the file for B;+        // deleting A's solo image (its last reference) must remove it; a+        // block still present in the edited note must keep its file.+        vm.deleteImageIfUnreferenced("vm-shared.jpg", excludingNoteId = aId, stillReferenced = false)+        vm.deleteImageIfUnreferenced("vm-kept-local.jpg", excludingNoteId = aId, stillReferenced = true)+        vm.deleteImageIfUnreferenced("vm-solo.jpg", excludingNoteId = aId, stillReferenced = false)++        // The solo deletion proves the IO work ran; the shared and locally+        // kept files must have survived it.+        await { !solo.exists() }+        assertTrue(shared.exists(), "shared image file must survive deletion from one note")+        assertTrue(keptLocal.exists(), "image still referenced in the edited note must survive")+        assertEquals("B", runBlocking { repo.getBySyncId("vm-img-b") }?.title)+    }+     @Test fun factoryCreatesAndRejects() {         val factory = NotesViewModelFactory(app, repo)         assertTrue(factory.create(NotesViewModel::class.java) is NotesViewModel)