photos: face-data cleanup, hide/delete people, strip GPS on share
- Commit
bb9dfc7d43811b0fdeca55786dbc2324022f95a0- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 08:51 UTC (15 days ago)
- Parents
67ab4b6
Deleted photos left their face embeddings (and faceless person rows) behind for clustering to keep reading - the sync deletion path now removes them transactionally. People had no controls at all: a person can now be named, hidden (persisted Person.hidden, v23 - hidden clusters leave the grid, data retained) or deleted (cluster assignments nulled, photos and embeddings untouched). Sharing sent the original file with GPS EXIF intact. The share path now copies stills to a stripped copy (31 GPS tags removed, other EXIF preserved) and shares that; videos still share originals. The extraction-rules comment claiming people have no user-assigned names was stale and is corrected. Verified: :photos:testDevUnitTest 797 tests pass incl. three new privacy tests.
Diff
photos/schemas/com.vayunmathur.photos.data.PhotoDatabase/23.json
diff --git a/photos/schemas/com.vayunmathur.photos.data.PhotoDatabase/23.json b/photos/schemas/com.vayunmathur.photos.data.PhotoDatabase/23.jsonnew file mode 100644index 0000000000..6a877f795f--- /dev/null+++ b/photos/schemas/com.vayunmathur.photos.data.PhotoDatabase/23.json@@ -0,0 +1,399 @@+{+ "formatVersion": 1,+ "database": {+ "version": 23,+ "identityHash": "d7d506989bb6e663fcfd98968d379ebb",+ "entities": [+ {+ "tableName": "Photo",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `uri` TEXT NOT NULL, `date` INTEGER NOT NULL, `width` INTEGER NOT NULL, `height` INTEGER NOT NULL, `dateModified` INTEGER NOT NULL, `exifSet` INTEGER NOT NULL, `lat` REAL, `long` REAL, `isTrashed` INTEGER NOT NULL, `faceScanned` INTEGER NOT NULL, `ocrText` TEXT, `ocrScanned` INTEGER NOT NULL, `clipEmbedding` BLOB, `clipScanned` INTEGER NOT NULL, `mimeType` TEXT, `ocrBoxes` TEXT, `album` TEXT, `isFavorite` INTEGER NOT NULL, `duration` INTEGER, `fullWidth` INTEGER, `fullHeight` INTEGER, `croppedWidth` INTEGER, `croppedHeight` INTEGER, `croppedLeft` INTEGER, `croppedTop` INTEGER, `projectionType` TEXT)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "uri",+ "columnName": "uri",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "date",+ "columnName": "date",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "width",+ "columnName": "width",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "height",+ "columnName": "height",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "dateModified",+ "columnName": "dateModified",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "exifSet",+ "columnName": "exifSet",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lat",+ "columnName": "lat",+ "affinity": "REAL"+ },+ {+ "fieldPath": "long",+ "columnName": "long",+ "affinity": "REAL"+ },+ {+ "fieldPath": "isTrashed",+ "columnName": "isTrashed",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "faceScanned",+ "columnName": "faceScanned",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "ocrText",+ "columnName": "ocrText",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "ocrScanned",+ "columnName": "ocrScanned",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "clipEmbedding",+ "columnName": "clipEmbedding",+ "affinity": "BLOB"+ },+ {+ "fieldPath": "clipScanned",+ "columnName": "clipScanned",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "mimeType",+ "columnName": "mimeType",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "ocrBoxes",+ "columnName": "ocrBoxes",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "album",+ "columnName": "album",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isFavorite",+ "columnName": "isFavorite",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "videoData.duration",+ "columnName": "duration",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "panoData.fullWidth",+ "columnName": "fullWidth",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "panoData.fullHeight",+ "columnName": "fullHeight",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "panoData.croppedWidth",+ "columnName": "croppedWidth",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "panoData.croppedHeight",+ "columnName": "croppedHeight",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "panoData.croppedLeft",+ "columnName": "croppedLeft",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "panoData.croppedTop",+ "columnName": "croppedTop",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "panoData.projectionType",+ "columnName": "projectionType",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_Photo_date",+ "unique": false,+ "columnNames": [+ "date"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_Photo_date` ON `${TABLE_NAME}` (`date`)"+ },+ {+ "name": "index_Photo_isTrashed_duration",+ "unique": false,+ "columnNames": [+ "isTrashed",+ "duration"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_Photo_isTrashed_duration` ON `${TABLE_NAME}` (`isTrashed`, `duration`)"+ },+ {+ "name": "index_Photo_uri",+ "unique": false,+ "columnNames": [+ "uri"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_Photo_uri` ON `${TABLE_NAME}` (`uri`)"+ },+ {+ "name": "index_Photo_isFavorite_isTrashed_date",+ "unique": false,+ "columnNames": [+ "isFavorite",+ "isTrashed",+ "date"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_Photo_isFavorite_isTrashed_date` ON `${TABLE_NAME}` (`isFavorite`, `isTrashed`, `date`)"+ }+ ]+ },+ {+ "tableName": "Person",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `centroid` BLOB NOT NULL, `faceCount` INTEGER NOT NULL, `name` TEXT, `hidden` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "centroid",+ "columnName": "centroid",+ "affinity": "BLOB",+ "notNull": true+ },+ {+ "fieldPath": "faceCount",+ "columnName": "faceCount",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "hidden",+ "columnName": "hidden",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "PhotoFace",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `photoId` INTEGER NOT NULL, `clusterId` INTEGER, `embedding` BLOB NOT NULL, `clusterable` INTEGER NOT NULL, `left` REAL NOT NULL, `top` REAL NOT NULL, `right` REAL NOT NULL, `bottom` REAL NOT NULL, `srcWidth` INTEGER NOT NULL, `srcHeight` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "photoId",+ "columnName": "photoId",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "clusterId",+ "columnName": "clusterId",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "embedding",+ "columnName": "embedding",+ "affinity": "BLOB",+ "notNull": true+ },+ {+ "fieldPath": "clusterable",+ "columnName": "clusterable",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "left",+ "columnName": "left",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "top",+ "columnName": "top",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "right",+ "columnName": "right",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "bottom",+ "columnName": "bottom",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "srcWidth",+ "columnName": "srcWidth",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "srcHeight",+ "columnName": "srcHeight",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_PhotoFace_photoId",+ "unique": false,+ "columnNames": [+ "photoId"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_PhotoFace_photoId` ON `${TABLE_NAME}` (`photoId`)"+ },+ {+ "name": "index_PhotoFace_clusterId",+ "unique": false,+ "columnNames": [+ "clusterId"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_PhotoFace_clusterId` ON `${TABLE_NAME}` (`clusterId`)"+ }+ ]+ },+ {+ "tableName": "PhotoFts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`ocrText` TEXT, `name` TEXT NOT NULL, tokenize=unicode61 `remove_diacritics=1`, content=`Photo`)",+ "fields": [+ {+ "fieldPath": "ocrText",+ "columnName": "ocrText",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "rowid"+ ]+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "unicode61",+ "tokenizerArgs": [+ "remove_diacritics=1"+ ],+ "contentTable": "Photo",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_PhotoFts_BEFORE_UPDATE BEFORE UPDATE ON `Photo` BEGIN DELETE FROM `PhotoFts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_PhotoFts_BEFORE_DELETE BEFORE DELETE ON `Photo` BEGIN DELETE FROM `PhotoFts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_PhotoFts_AFTER_UPDATE AFTER UPDATE ON `Photo` BEGIN INSERT INTO `PhotoFts`(`docid`, `ocrText`, `name`) VALUES (NEW.`rowid`, NEW.`ocrText`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_PhotoFts_AFTER_INSERT AFTER INSERT ON `Photo` BEGIN INSERT INTO `PhotoFts`(`docid`, `ocrText`, `name`) VALUES (NEW.`rowid`, NEW.`ocrText`, NEW.`name`); END"+ ]+ }+ ],+ "setupQueries": [+ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'd7d506989bb6e663fcfd98968d379ebb')"+ ]+ }+}\ No newline at end of file
photos/src/main/java/com/vayunmathur/photos/data/FaceData.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/FaceData.kt b/photos/src/main/java/com/vayunmathur/photos/data/FaceData.ktindex 449c08f76e..b93c2d64ea 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/FaceData.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/FaceData.kt@@ -20,6 +20,10 @@ import kotlinx.coroutines.flow.Flow * picker, and the only one that cannot be regenerated by re-scanning. It is null * until a name is chosen. There is no representative face here: the cluster's * best face is a pure function of the [PhotoFace] rows, picked at read time.+ *+ * [hidden] is the user's opt-out for one cluster: hidden persons are excluded+ * from the People grid, but their faces and name are retained so unhiding (or+ * a re-grouping that keeps this row's id) restores them exactly. */ @Entity data class Person(@@ -27,6 +31,7 @@ data class Person( val centroid: ByteArray, val faceCount: Int, val name: String?,+ val hidden: Boolean = false, ) /**@@ -108,6 +113,18 @@ interface FaceDao { @Query("UPDATE Person SET name = :name WHERE id = :id") suspend fun setPersonName(id: Long, name: String?) + /** Hide (or un-hide) a cluster in the People grid; rows and faces are retained. */+ @Query("UPDATE Person SET hidden = :hidden WHERE id = :id")+ suspend fun setPersonHidden(id: Long, hidden: Boolean)++ /** Drop a cluster's face assignments; the face rows (and photos) themselves stay. */+ @Query("UPDATE PhotoFace SET clusterId = NULL WHERE clusterId = :clusterId")+ suspend fun clearAssignmentsForCluster(clusterId: Long)++ /** Persons no face points at any more (e.g. after their photos were deleted). */+ @Query("DELETE FROM Person WHERE NOT EXISTS (SELECT 1 FROM PhotoFace WHERE PhotoFace.clusterId = Person.id)")+ suspend fun deletePersonsWithNoFaces()+ /** * Update only the columns the clustering pass owns. *
photos/src/main/java/com/vayunmathur/photos/data/FaceRepository.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/FaceRepository.kt b/photos/src/main/java/com/vayunmathur/photos/data/FaceRepository.ktindex 22fe7e0365..9ffb56ebc0 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/FaceRepository.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/FaceRepository.kt@@ -22,6 +22,21 @@ class FaceRepository private constructor(context: Context) : suspend fun getPersons(): List<Person> = faceDao.getPersons() suspend fun clearPersons() = faceDao.clearPersons() suspend fun setPersonName(id: Long, name: String?) = faceDao.setPersonName(id, name)+ suspend fun setPersonHidden(id: Long, hidden: Boolean) = faceDao.setPersonHidden(id, hidden)++ /**+ * Remove one cluster and its face assignments, in one transaction so the+ * People view never sees a person whose faces are half-unassigned. The+ * [PhotoFace] rows keep their embeddings (a later grouping pass may form+ * a new cluster from them) and the photos themselves are untouched.+ */+ suspend fun deletePersonCluster(id: Long) = db.withWriteTransaction {+ faceDao.clearAssignmentsForCluster(id)+ faceDao.deletePerson(id)+ }++ /** Delete every face row belonging to [photoIds] (their photos are gone). */+ suspend fun deletePhotoFaces(photoIds: List<Long>) = faceDao.deletePhotoFacesByPhotoIds(photoIds) suspend fun clearPhotoFaces() = faceDao.clearPhotoFaces() suspend fun getClusterRows(): List<FaceClusterRow> = faceDao.getClusterRows() suspend fun photoIdsForCluster(clusterId: Long): List<Long> = faceDao.photoIdsForCluster(clusterId)
photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt b/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.ktindex 67ef296050..b5dad4758f 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt@@ -364,7 +364,7 @@ data class ExifResult( ) /** Photo Database: a room database implementation for photo database. */-@Database(entities = [Photo::class, Person::class, PhotoFace::class, PhotoFts::class], version = 22, exportSchema = true)+@Database(entities = [Photo::class, Person::class, PhotoFace::class, PhotoFts::class], version = 23, exportSchema = true) abstract class PhotoDatabase : RoomDatabase() { abstract fun photoDao(): PhotoDao abstract fun photoScanDao(): PhotoScanDao@@ -377,11 +377,17 @@ abstract class PhotoDatabase : RoomDatabase() { MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16, MIGRATION_16_17, MIGRATION_17_18, MIGRATION_18_19, MIGRATION_19_20, MIGRATION_20_21,- MIGRATION_21_22,+ MIGRATION_21_22, MIGRATION_22_23, ) } } +val MIGRATION_22_23 = Migration(22, 23) {+ // User control over face grouping: a hidden flag on each person cluster.+ // Existing clusters start visible. SQL mirrors Room's generated schema.+ it.execSQL("ALTER TABLE Person ADD COLUMN hidden INTEGER NOT NULL DEFAULT 0")+}+ val MIGRATION_21_22 = Migration(21, 22) { // Index uri (sync/MediaStore lookups by content URI) and the favourites // predicate (isFavorite + isTrashed, date-ordered for the album).
photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt b/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.ktindex 03fc9a7fb4..b3213ec8b1 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt@@ -1,6 +1,7 @@ package com.vayunmathur.photos.data import android.content.Context+import androidx.room3.withWriteTransaction import com.vayunmathur.library.room.RoomRepository import kotlinx.coroutines.flow.Flow @@ -15,6 +16,7 @@ open class PhotosRepository internal constructor(context: Context) : RoomRepository<PhotoDatabase>(context, PhotoDatabase::class) { private val photoDao: PhotoDao get() = db.photoDao()+ private val faceDao: FaceDao get() = db.faceDao() // ------------------------------------------------------------------ // PhotoDao read Flows@@ -36,8 +38,33 @@ open class PhotosRepository internal constructor(context: Context) : open suspend fun getAll(): List<Photo> = photoDao.getAll() suspend fun getByUri(uri: String): List<Photo> = photoDao.getByUri(uri) open suspend fun upsertAll(photos: List<Photo>) = photoDao.upsertAll(photos)- open suspend fun delete(value: Photo): Int = photoDao.delete(value)- open suspend fun deleteByIds(ids: List<Long>) = photoDao.deleteByIds(ids)+ open suspend fun delete(value: Photo): Int {+ var deleted = 0+ db.withWriteTransaction {+ faceDao.deletePhotoFacesByPhotoIds(listOf(value.id))+ faceDao.deletePersonsWithNoFaces()+ deleted = photoDao.delete(value)+ }+ return deleted+ }++ /**+ * Delete photos and, in the same transaction, every face/embedding row+ * that belonged to them. Without this the PhotoFace rows are orphaned+ * when sync removes a photo MediaStore no longer reports, and every+ * later clustering pass keeps reading (and re-grouping) embeddings of a+ * deleted photo. Persons left with no faces are removed too. Explicit+ * deletes, not a foreign-key cascade, so no schema change is needed+ * for this cleanup.+ */+ open suspend fun deleteByIds(ids: List<Long>) {+ if (ids.isEmpty()) return+ db.withWriteTransaction {+ faceDao.deletePhotoFacesByPhotoIds(ids)+ faceDao.deletePersonsWithNoFaces()+ photoDao.deleteByIds(ids)+ }+ } suspend fun setTrashed(id: Long) = photoDao.setTrashed(id) suspend fun setAlbum(ids: List<Long>, album: String?) = photoDao.setAlbum(ids, album) open suspend fun setFavorite(ids: List<Long>, value: Boolean) = photoDao.setFavorite(ids, value)
photos/src/main/java/com/vayunmathur/photos/platform/GalleryViewModel.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/platform/GalleryViewModel.kt b/photos/src/main/java/com/vayunmathur/photos/platform/GalleryViewModel.ktindex 13bd271d14..4a6225d342 100644--- a/photos/src/main/java/com/vayunmathur/photos/platform/GalleryViewModel.kt+++ b/photos/src/main/java/com/vayunmathur/photos/platform/GalleryViewModel.kt@@ -170,6 +170,9 @@ class GalleryViewModel( val byId = allPhotos.filter { !it.isTrashed }.associateBy { it.id } val facesByCluster = faces.groupBy { it.clusterId } persons.mapNotNull { person ->+ // Hidden clusters are the user's opt-out: excluded from+ // the grid, but their rows and faces are retained.+ if (person.hidden) return@mapNotNull null val clusterFaces = facesByCluster[person.id].orEmpty() .mapNotNull { face -> byId[face.photoId]?.let { face to it } } if (clusterFaces.isEmpty()) return@mapNotNull null@@ -475,6 +478,24 @@ class GalleryViewModel( } } + /** Hide a person-cluster from the People grid; its faces and name are retained. */+ fun hidePerson(id: Long) {+ viewModelScope.launch {+ faceRepository.setPersonHidden(id, true)+ }+ }++ /**+ * Delete a person-cluster and its face assignments. The photos (and the+ * face embeddings, which a later grouping pass may re-cluster) are+ * untouched; only the grouping the user rejected is removed.+ */+ fun deletePerson(id: Long) {+ viewModelScope.launch {+ faceRepository.deletePersonCluster(id)+ }+ }+ // ------------------------------------------------------------------ // Albums (MediaStore folder moves) // ------------------------------------------------------------------@@ -594,6 +615,9 @@ interface FaceStore { fun faceGeometryFlow(): Flow<List<com.vayunmathur.photos.data.FaceGeometry>> suspend fun photoIdsForCluster(clusterId: Long): List<Long> suspend fun setPersonName(id: Long, name: String?)+ /** Default no-ops keep existing test fakes source-compatible. */+ suspend fun setPersonHidden(id: Long, hidden: Boolean) {}+ suspend fun deletePersonCluster(id: Long) {} } private class PhotoStoreRepository(@@ -634,6 +658,8 @@ private class FaceStoreRepository( faceRepository.faceGeometryFlow() override suspend fun photoIdsForCluster(clusterId: Long): List<Long> = faceRepository.photoIdsForCluster(clusterId) override suspend fun setPersonName(id: Long, name: String?) = faceRepository.setPersonName(id, name)+ override suspend fun setPersonHidden(id: Long, hidden: Boolean) = faceRepository.setPersonHidden(id, hidden)+ override suspend fun deletePersonCluster(id: Long) = faceRepository.deletePersonCluster(id) } /**
photos/src/main/java/com/vayunmathur/photos/platform/SharePhotoCopy.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/platform/SharePhotoCopy.kt b/photos/src/main/java/com/vayunmathur/photos/platform/SharePhotoCopy.ktnew file mode 100644index 0000000000..716e78596c--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/platform/SharePhotoCopy.kt@@ -0,0 +1,108 @@+package com.vayunmathur.photos.platform++import android.content.Context+import android.net.Uri+import androidx.core.content.FileProvider+import androidx.exifinterface.media.ExifInterface+import com.vayunmathur.library.log.Log+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import java.io.File+import java.io.IOException++/**+ * Prepares the copy of a photo that leaves the device through the app's own+ * share entry.+ *+ * Sharing the MediaStore URI directly ships the original file, GPS EXIF+ * included. For stills this instead copies the bytes into the app cache,+ * removes every GPS EXIF tag from the copy, and hands out a FileProvider URI+ * for the copy. The original is never modified. Videos return the original+ * URI: their location metadata is not EXIF and is out of scope here.+ *+ * Stripping is unconditional (always on) for this share path: there is no+ * photos settings screen to host an opt-out toggle, and a share that keeps+ * the sender's location should not be one tap away from the default. If a+ * still cannot be copied or stripped, callers fall back to the original URI+ * so a share still works; the failure is logged.+ */+object SharePhotoCopy {++ private const val TAG = "SharePhotoCopy"++ /** EXIF tags that carry location; every one is removed from a shared copy. */+ internal val GPS_TAGS: List<String> = listOf(+ ExifInterface.TAG_GPS_LATITUDE,+ ExifInterface.TAG_GPS_LATITUDE_REF,+ ExifInterface.TAG_GPS_LONGITUDE,+ ExifInterface.TAG_GPS_LONGITUDE_REF,+ ExifInterface.TAG_GPS_ALTITUDE,+ ExifInterface.TAG_GPS_ALTITUDE_REF,+ ExifInterface.TAG_GPS_TIMESTAMP,+ ExifInterface.TAG_GPS_DATESTAMP,+ ExifInterface.TAG_GPS_PROCESSING_METHOD,+ ExifInterface.TAG_GPS_AREA_INFORMATION,+ ExifInterface.TAG_GPS_SPEED,+ ExifInterface.TAG_GPS_SPEED_REF,+ ExifInterface.TAG_GPS_TRACK,+ ExifInterface.TAG_GPS_TRACK_REF,+ ExifInterface.TAG_GPS_IMG_DIRECTION,+ ExifInterface.TAG_GPS_IMG_DIRECTION_REF,+ ExifInterface.TAG_GPS_DEST_LATITUDE,+ ExifInterface.TAG_GPS_DEST_LATITUDE_REF,+ ExifInterface.TAG_GPS_DEST_LONGITUDE,+ ExifInterface.TAG_GPS_DEST_LONGITUDE_REF,+ ExifInterface.TAG_GPS_DEST_BEARING,+ ExifInterface.TAG_GPS_DEST_BEARING_REF,+ ExifInterface.TAG_GPS_DEST_DISTANCE,+ ExifInterface.TAG_GPS_DEST_DISTANCE_REF,+ ExifInterface.TAG_GPS_DIFFERENTIAL,+ ExifInterface.TAG_GPS_H_POSITIONING_ERROR,+ ExifInterface.TAG_GPS_MEASURE_MODE,+ ExifInterface.TAG_GPS_DOP,+ ExifInterface.TAG_GPS_MAP_DATUM,+ ExifInterface.TAG_GPS_SATELLITES,+ ExifInterface.TAG_GPS_STATUS,+ ExifInterface.TAG_GPS_VERSION_ID,+ )++ /** Remove every [GPS_TAGS] entry from [file]'s EXIF, in place. Non-GPS tags are kept. */+ internal fun stripGpsExif(file: File) {+ val exif = ExifInterface(file)+ for (tag in GPS_TAGS) exif.setAttribute(tag, null)+ exif.saveAttributes()+ }++ /** True when the shared copy for [file] no longer reports a GPS position. */+ internal fun hasGpsExif(file: File): Boolean = ExifInterface(file).latLong != null++ /**+ * The URI to put in a share intent for [source]: a GPS-stripped cache copy+ * for stills, the original for videos (or anything not an image). Null if+ * a still's copy could not be made, so the caller can decide its fallback.+ */+ suspend fun shareUri(context: Context, source: Uri, displayName: String, mimeType: String?): Uri? =+ withContext(Dispatchers.IO) {+ if (mimeType != null && !mimeType.startsWith("image/")) return@withContext source+ try {+ val dir = File(context.cacheDir, "share_stripped").apply { mkdirs() }+ val safeName = displayName.substringAfterLast('/').ifBlank { "photo" }+ .replace(Regex("[^A-Za-z0-9._-]"), "_")+ val copy = File(dir, safeName)+ context.contentResolver.openInputStream(source)?.use { input ->+ copy.outputStream().use { output -> input.copyTo(output) }+ } ?: return@withContext null+ stripGpsExif(copy)+ FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", copy)+ } catch (e: IOException) {+ Log.error(TAG, "Could not prepare a location-stripped copy for sharing", e)+ null+ } catch (e: IllegalArgumentException) {+ Log.error(TAG, "Could not prepare a location-stripped copy for sharing", e)+ null+ } catch (e: SecurityException) {+ Log.error(TAG, "Could not prepare a location-stripped copy for sharing", e)+ null+ }+ }+}
photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt b/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.ktindex 974e50872b..4be636a032 100644--- a/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt+++ b/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt@@ -245,6 +245,9 @@ suspend fun syncPhotos( } if (toDelete.isNotEmpty()) {+ // deleteByIds also removes these photos' face/embedding rows (and any+ // person left faceless), so a deleted photo leaves nothing behind for+ // the clustering pass to keep reading. toDelete.chunked(DELETE_ID_CHUNK_SIZE).forEach { chunk -> repository.deleteByIds(chunk) }
photos/src/main/java/com/vayunmathur/photos/ui/PeoplePage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/PeoplePage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/PeoplePage.ktindex b3bda21ce1..47cbd38996 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PeoplePage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PeoplePage.kt@@ -17,7 +17,16 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.foundation.shape.CircleShape+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.DropdownMenu+import com.vayunmathur.library.ui.DropdownMenuItem import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.IconEdit+import com.vayunmathur.library.ui.IconMoreVert+import com.vayunmathur.library.ui.IconVisibilityOff+import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.ui.adaptiveGridCells import com.vayunmathur.library.ui.LinearProgressIndicator import com.vayunmathur.library.ui.MaterialTheme@@ -109,6 +118,8 @@ fun PeoplePage( pendingClusterId = person.id pickContact.launch(null) },+ onHideClick = { person -> galleryViewModel.hidePerson(person.id) },+ onDeleteClick = { person -> galleryViewModel.deletePerson(person.id) }, ) } @@ -158,8 +169,14 @@ internal fun PeopleGrid( modifier: Modifier = Modifier, faceThumbnail: @Composable (PersonCluster, Modifier) -> Unit, onNameClick: (PersonCluster) -> Unit,+ onHideClick: (PersonCluster) -> Unit = {},+ onDeleteClick: (PersonCluster) -> Unit = {}, onClick: (PersonCluster) -> Unit, ) {+ // Cluster whose overflow menu is open, and cluster awaiting the delete+ // confirmation — the same pending-state shape as the album delete flow.+ var menuPersonId by remember { mutableStateOf<Long?>(null) }+ var pendingDelete by remember { mutableStateOf<PersonCluster?>(null) } LazyVerticalGrid( columns = adaptiveGridCells(100.dp), horizontalArrangement = Arrangement.spacedBy(8.dp),@@ -170,14 +187,50 @@ internal fun PeopleGrid( // instead of recreating (and re-loading) them during indexing. items(people, key = { it.id }) { person -> Column(horizontalAlignment = Alignment.CenterHorizontally) {- faceThumbnail(- person,- Modifier- .fillMaxWidth()- .aspectRatio(1f)- .clip(CircleShape)- .invisibleClickable { onClick(person) },- )+ Box {+ faceThumbnail(+ person,+ Modifier+ .fillMaxWidth()+ .aspectRatio(1f)+ .clip(CircleShape)+ .invisibleClickable { onClick(person) },+ )+ Box(Modifier.align(Alignment.TopEnd)) {+ IconButton(onClick = { menuPersonId = person.id }) {+ IconMoreVert()+ }+ DropdownMenu(+ expanded = menuPersonId == person.id,+ onDismissRequest = { menuPersonId = null },+ ) {+ DropdownMenuItem(+ text = { Text(stringResource(R.string.people_name)) },+ leadingIcon = { IconEdit() },+ onClick = {+ menuPersonId = null+ onNameClick(person)+ },+ )+ DropdownMenuItem(+ text = { Text(stringResource(R.string.people_hide)) },+ leadingIcon = { IconVisibilityOff() },+ onClick = {+ menuPersonId = null+ onHideClick(person)+ },+ )+ DropdownMenuItem(+ text = { Text(stringResource(R.string.people_delete)) },+ leadingIcon = { IconDelete() },+ onClick = {+ menuPersonId = null+ pendingDelete = person+ },+ )+ }+ }+ } // The name is its own tap target: the avatar keeps opening the // person's photos, and tapping an existing name is how renaming // works (it just reopens the picker).@@ -199,6 +252,33 @@ internal fun PeopleGrid( } } }+ pendingDelete?.let { person ->+ AlertDialog(+ onDismissRequest = { pendingDelete = null },+ title = { Text(stringResource(R.string.people_delete)) },+ text = {+ Text(+ stringResource(+ R.string.people_delete_confirm,+ person.name ?: stringResource(R.string.people_unnamed),+ )+ )+ },+ confirmButton = {+ TextButton(onClick = {+ pendingDelete = null+ onDeleteClick(person)+ }) {+ Text(stringResource(R.string.people_delete))+ }+ },+ dismissButton = {+ TextButton(onClick = { pendingDelete = null }) {+ Text(stringResource(R.string.action_cancel))+ }+ },+ )+ } } /** The representative face of a cluster, cropped from its cover photo. */
photos/src/main/java/com/vayunmathur/photos/ui/PeopleScreen.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/PeopleScreen.kt b/photos/src/main/java/com/vayunmathur/photos/ui/PeopleScreen.ktindex 9c1bb49e1d..99c6c9e1a4 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PeopleScreen.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PeopleScreen.kt@@ -75,6 +75,10 @@ fun PeopleScreen( * labels fine with the no-op default. */ onNameClick: (PersonCluster) -> Unit = {},+ /** Hide a cluster from this grid (data retained). Binder persists it. */+ onHideClick: (PersonCluster) -> Unit = {},+ /** Delete a cluster and its face assignments (photos untouched). */+ onDeleteClick: (PersonCluster) -> Unit = {}, ) { // Show progress while there are still photos left to scan (or the worker is // actively running); it disappears on its own once everything is scanned.@@ -104,6 +108,8 @@ fun PeopleScreen( modifier = Modifier.weight(1f), faceThumbnail = faceThumbnail, onNameClick = onNameClick,+ onHideClick = onHideClick,+ onDeleteClick = onDeleteClick, ) { person -> backStack.pushPhoto(Route.PhotoPage(person.coverPhoto.id, com.vayunmathur.photos.PhotoSource.Person(person.id))) }
photos/src/main/java/com/vayunmathur/photos/ui/PhotoMetadataCard.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoMetadataCard.kt b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoMetadataCard.ktindex 14a36be41d..777b208087 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoMetadataCard.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoMetadataCard.kt@@ -10,6 +10,7 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color@@ -32,6 +33,8 @@ import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.photos.R import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.platform.SharePhotoCopy+import kotlinx.coroutines.launch import kotlin.time.Instant /**@@ -54,6 +57,7 @@ internal fun PhotoMetadataCard( isFavorite: Boolean = false, onToggleFavorite: (Photo) -> Unit = {}, ) {+ val shareScope = rememberCoroutineScope() Column( modifier = Modifier.fillMaxWidth()@@ -134,15 +138,24 @@ internal fun PhotoMetadataCard( IconButton(onClick = onEditPhoto) { IconEdit(tint = Color.White) } IconButton( onClick = {- val intent =- Intent(Intent.ACTION_SEND).apply {- type =- if (photo.videoData != null) "video/*"- else "image/*"- putExtra(Intent.EXTRA_STREAM, photo.uri.toUri())- addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)- }- ExternalIntents.launch(context, Intent.createChooser(intent, context.getString(UiR.string.share)))+ // Share a GPS-stripped cache copy for stills, never the+ // original MediaStore URI with its EXIF location intact.+ // Copying is IO, so the chooser launches once it is ready;+ // a failed copy falls back to the original so share works.+ shareScope.launch {+ val shareUri = SharePhotoCopy.shareUri(+ context, photo.uri.toUri(), photo.name, photo.mimeType,+ ) ?: photo.uri.toUri()+ val intent =+ Intent(Intent.ACTION_SEND).apply {+ type =+ if (photo.videoData != null) "video/*"+ else "image/*"+ putExtra(Intent.EXTRA_STREAM, shareUri)+ addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)+ }+ ExternalIntents.launch(context, Intent.createChooser(intent, context.getString(UiR.string.share)))+ } } ) { IconShare(tint = Color.White) } IconButton(onClick = { onDelete(photo) }) {
photos/src/main/res/values/strings.xml
diff --git a/photos/src/main/res/values/strings.xml b/photos/src/main/res/values/strings.xmlindex b26a9cd835..a606ebae37 100644--- a/photos/src/main/res/values/strings.xml+++ b/photos/src/main/res/values/strings.xml@@ -101,6 +101,14 @@ <string name="people_model_missing">Face grouping needs a face model that is not installed.</string> <!-- Label under a person grid cell with no name yet; tapping it opens the contact picker. Adjective --> <string name="people_unnamed">Unnamed</string>+ <!-- Overflow action on a person cluster: name it via the contact picker. Verb -->+ <string name="people_name">Name person</string>+ <!-- Overflow action on a person cluster: hide it from the People grid, keeping its data. Verb -->+ <string name="people_hide">Hide person</string>+ <!-- Overflow action / confirmation title: delete a person cluster and its face assignments. Verb -->+ <string name="people_delete">Delete person</string>+ <!-- Confirmation body for deleting a person cluster. %1$s = person name -->+ <string name="people_delete_confirm">Remove the person \"<xliff:g id="name" example="Ada">%1$s</xliff:g>\"? Your photos will be kept; only this grouping is removed.</string> <!-- Photo detail badge: number of people in this photo. Plural handling. %1$d = count --> <plurals name="people_in_photo"> <!-- Singular: one person in photo -->
photos/src/main/res/xml/data_extraction_rules.xml
diff --git a/photos/src/main/res/xml/data_extraction_rules.xml b/photos/src/main/res/xml/data_extraction_rules.xmlindex 6e1f4044ca..0d38898917 100644--- a/photos/src/main/res/xml/data_extraction_rules.xml+++ b/photos/src/main/res/xml/data_extraction_rules.xml@@ -4,10 +4,14 @@ Storage audited: database/passwords-db PhotoDatabase (Photo/Person/PhotoFace): a derived index over MediaStore. EXIF, lat/long, OCR text of every image, CLIP- embeddings and face-cluster centroids. No user edits are- stored here - the cropped*/projection* columns are panorama- projection metadata, and Person has no user-assigned name.- Regenerable by re-running SyncWorker, and privacy-heavy.+ embeddings and face-cluster centroids. Almost everything+ here is regenerable by re-running SyncWorker, but not all:+ Person.name IS a user-assigned name (picked from contacts+ for a face cluster) and Person.hidden is a user-set flag,+ and neither can be re-derived by re-scanning. The+ cropped*/projection* columns are panorama projection+ metadata, not user edits. Still privacy-heavy (OCR text,+ geotags, face vectors, and those user-supplied names). database/vault-db VaultDatabase for the secure folder, opened with a user-supplied password rather than the keystore passphrase. file/secure_vault the secure folder's stored photos. User content the user@@ -15,11 +19,12 @@ file/datastore_default.preferences_pb grid column count and model-version markers. cache/image_cache Coil disk cache; Android never backs up cacheDir. - Cloud backup carries the grid preference only. The index is regenerable and would- ship OCR text, geotags and face vectors off the device; the secure folder is hidden- by intent and stays local. Device transfer carries both databases and the vault so a- new phone does not have to re-index the whole library, and so hidden photos survive- the move without passing through Google. -->+ Cloud backup carries the grid preference only. The index is largely regenerable and+ would ship OCR text, geotags and face vectors off the device (person names and+ hidden flags would be lost on a cloud-only restore, accepted); the secure folder is+ hidden by intent and stays local. Device transfer carries both databases and the+ vault so a new phone does not have to re-index the whole library or lose person+ names, and so hidden photos survive the move without passing through Google. --> <data-extraction-rules> <cloud-backup disableIfNoEncryptionCapabilities="true"> <include domain="file" path="datastore_default.preferences_pb" />
photos/src/test/java/com/vayunmathur/photos/data/PhotosFavoritesDataTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/data/PhotosFavoritesDataTest.kt b/photos/src/test/java/com/vayunmathur/photos/data/PhotosFavoritesDataTest.ktindex e2b6473a0a..a528f3fac2 100644--- a/photos/src/test/java/com/vayunmathur/photos/data/PhotosFavoritesDataTest.kt+++ b/photos/src/test/java/com/vayunmathur/photos/data/PhotosFavoritesDataTest.kt@@ -104,9 +104,9 @@ class PhotosFavoritesDataTest { } @Test- fun migrationListEndsAtVersion22() {+ fun migrationListEndsAtVersion23() { val last = PhotoDatabase.migrations.last()- assertEquals(21 to 22, last.startVersion to last.endVersion)+ assertEquals(22 to 23, last.startVersion to last.endVersion) } @Test
photos/src/test/java/com/vayunmathur/photos/util/PhotosPrivacyFixesTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosPrivacyFixesTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosPrivacyFixesTest.ktnew file mode 100644index 0000000000..3da9cfa729--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosPrivacyFixesTest.kt@@ -0,0 +1,143 @@+package com.vayunmathur.photos.util++import android.app.Application+import android.os.Looper+import android.util.Base64+import androidx.exifinterface.media.ExifInterface+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.photos.data.Person+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.data.PhotoFace+import com.vayunmathur.photos.data.TestPhotosRepository+import com.vayunmathur.photos.data.awaitPhotosCondition+import com.vayunmathur.photos.platform.GalleryViewModel+import com.vayunmathur.photos.platform.SharePhotoCopy+import com.vayunmathur.photos.platform.workInfosOverride+import java.io.File+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.setMain+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Privacy fixes: face rows die with their photo, people clusters can be+ * hidden/deleted by the user, and shared stills lose their GPS EXIF.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class PhotosPrivacyFixesTest {++ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private lateinit var installed: TestPhotosRepository.Installed++ @BeforeTest+ fun setup() {+ Dispatchers.setMain(Dispatchers.Unconfined)+ workInfosOverride = { _, _ -> flowOf(emptyList()) }+ installed = TestPhotosRepository.install(app)+ }++ private fun photo(name: String, date: Long) = Photo(+ name = name, uri = "content://media/$name", date = date, width = 100, height = 100,+ dateModified = date, exifSet = true, lat = null, long = null,+ videoData = null, panoData = null,+ )++ private fun face(photoId: Long, clusterId: Long?) = PhotoFace(+ photoId = photoId, clusterId = clusterId, embedding = byteArrayOf(1, 2, 3),+ clusterable = true, left = 0f, top = 0f, right = 0.5f, bottom = 0.5f,+ srcWidth = 100, srcHeight = 100,+ )++ @Test fun deleteByIdsRemovesFaceRowsAndFacelessPersons() = runBlocking {+ installed.photos.upsertAll(listOf(photo("a", 200L), photo("b", 100L)))+ val (a, b) = installed.photos.getAll().sortedBy { it.name }+ val dao = installed.database.faceDao()+ val ada = dao.insertPerson(Person(centroid = byteArrayOf(1), faceCount = 1, name = "Ada"))+ val shared = dao.insertPerson(Person(centroid = byteArrayOf(2), faceCount = 2, name = "Shared"))+ dao.insertPhotoFaces(listOf(face(a.id, ada), face(a.id, shared), face(b.id, shared)))++ installed.photos.deleteByIds(listOf(a.id))++ // a's faces (embeddings included) are gone; b's face and person survive.+ val geometry = dao.faceGeometryFlow().first()+ assertEquals(listOf(b.id), geometry.map { it.photoId })+ assertEquals(listOf("Shared"), installed.faces.getPersons().map { it.name })+ assertEquals(listOf("b"), installed.photos.getAll().map { it.name })+ Unit+ }++ @Test fun hideExcludesPersonFromPeopleAndDeleteRemovesOnlyTheCluster() = runBlocking {+ installed.photos.upsertAll(listOf(photo("a", 200L)))+ val a = installed.photos.getAll().single()+ val dao = installed.database.faceDao()+ val ada = dao.insertPerson(Person(centroid = byteArrayOf(1), faceCount = 1, name = "Ada"))+ dao.insertPhotoFaces(listOf(face(a.id, ada)))++ val vm = GalleryViewModel(app).also { it.runSyncHook = {} }+ val peopleJob: kotlinx.coroutines.Job =+ kotlinx.coroutines.CoroutineScope(Dispatchers.Default).launch { vm.people.collect {} }+ val photosJob: kotlinx.coroutines.Job =+ kotlinx.coroutines.CoroutineScope(Dispatchers.Default).launch { vm.photos.collect {} }+ val jobs = listOf(peopleJob, photosJob)+ assertTrue(+ awaitPhotosCondition { Shadows.shadowOf(Looper.getMainLooper()).idle(); vm.people.value.size == 1 },+ "person projected before hide",+ )++ vm.hidePerson(ada)+ assertTrue(+ awaitPhotosCondition { Shadows.shadowOf(Looper.getMainLooper()).idle(); vm.people.value.isEmpty() },+ "hidden person excluded from people",+ )+ // Hidden, not deleted: row, name and face assignment are retained.+ val hidden = installed.faces.getPersons().single()+ assertTrue(hidden.hidden)+ assertEquals("Ada", hidden.name)++ vm.deletePerson(ada)+ assertTrue(+ awaitPhotosCondition { installed.faces.getPersons().isEmpty() },+ "cluster deleted",+ )+ // Assignments cleared, but the face row and the photo itself survive.+ assertEquals(null, dao.faceGeometryFlow().first().single().clusterId)+ assertEquals(listOf("a"), installed.photos.getAll().map { it.name })+ jobs.forEach { it.cancel() }+ Unit+ }++ @Test fun stripGpsExifRemovesLocationButKeepsOtherTags() {+ // A 4x3 white JPEG (222 bytes) generated with ffmpeg.+ val bytes = Base64.decode(TINY_JPEG_BASE64, Base64.DEFAULT)+ val file = File(app.cacheDir, "gps-test.jpg").apply { writeBytes(bytes) }+ val exif = ExifInterface(file)+ exif.setLatLong(37.4215, -122.0840)+ exif.setAttribute(ExifInterface.TAG_MAKE, "TestCamera")+ exif.saveAttributes()+ assertTrue(SharePhotoCopy.hasGpsExif(file), "seeded GPS is readable")++ SharePhotoCopy.stripGpsExif(file)++ assertFalse(SharePhotoCopy.hasGpsExif(file), "GPS removed from the shared copy")+ assertEquals(null, ExifInterface(file).getAttribute(ExifInterface.TAG_GPS_LATITUDE))+ assertEquals("TestCamera", ExifInterface(file).getAttribute(ExifInterface.TAG_MAKE))+ Unit+ }++ private companion object {+ const val TINY_JPEG_BASE64 =+ "/9j/4AAQSkZJRgABAgAAAQABAAD//gAQTGF2YzYyLjExLjEwMwD/2wBDAAgEBAQEBAUFBQUFBQYGBgYGBgYGBgYGBgYHBwcICAgHBwcGBgcHCAgICAkJCQgICAgJCQoKCgwMCwsODg4RERT/xABLAAEBAAAAAAAAAAAAAAAAAAAABwEBAAAAAAAAAAAAAAAAAAAAABABAAAAAAAAAAAAAAAAAAAAABEBAAAAAAAAAAAAAAAAAAAAAP/AABEIAAMABAMBIgACEQADEQD/2gAMAwEAAhEDEQA/AL+AD//Z"+ }+}
photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1WorkersTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1WorkersTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1WorkersTest.ktindex bcbd195608..f813fa10ea 100644--- a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1WorkersTest.kt+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1WorkersTest.kt@@ -25,6 +25,7 @@ import com.vayunmathur.photos.data.MIGRATION_18_19 import com.vayunmathur.photos.data.MIGRATION_19_20 import com.vayunmathur.photos.data.MIGRATION_20_21 import com.vayunmathur.photos.data.MIGRATION_21_22+import com.vayunmathur.photos.data.MIGRATION_22_23 import com.vayunmathur.photos.data.MIGRATION_1_2 import com.vayunmathur.photos.data.MIGRATION_2_3 import com.vayunmathur.photos.data.MIGRATION_3_4@@ -96,9 +97,9 @@ class PhotosSlice1WorkersTest { MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16, MIGRATION_16_17, MIGRATION_17_18, MIGRATION_18_19, MIGRATION_19_20, MIGRATION_20_21,- MIGRATION_21_22,+ MIGRATION_21_22, MIGRATION_22_23, )- assertEquals(21, PhotoDatabase.migrations.size)+ assertEquals(22, PhotoDatabase.migrations.size) for (migration in migrations) migration.migrate(connection) fun queryStrings(sql: String): List<String> = connection.prepare(sql).use { statement ->@@ -131,6 +132,13 @@ class PhotosSlice1WorkersTest { )) { assertTrue(column in columnNames, "missing $column in $columnNames") }+ // v23 adds the person hidden flag.+ val personColumns = connection.prepare("PRAGMA table_info(Person)").use { statement ->+ val names = mutableSetOf<String>()+ while (statement.step()) names += statement.getText(1) ?: ""+ names+ }+ assertTrue("hidden" in personColumns, "missing hidden in $personColumns") // Rows survived the whole chain (drop/recreate only touched face tables). assertEquals(2L, queryLong("SELECT COUNT(*) FROM Photo")) // The face reset left both photos unscanned for the new indexer.@@ -141,9 +149,9 @@ class PhotosSlice1WorkersTest { } @Test- fun migrationListIsContiguousFrom1To22() {+ fun migrationListIsContiguousFrom1To23() { val versions = PhotoDatabase.migrations.map { it.startVersion to it.endVersion }- assertEquals((1..21).map { it to it + 1 }, versions)+ assertEquals((1..22).map { it to it + 1 }, versions) } // ---- Worker scheduling ----