diff --git a/README.md b/README.md index b59f652..a89293c 100644 --- a/README.md +++ b/README.md @@ -20,9 +20,9 @@ Paperize is an Android app that changes your home and lock screen wallpaper on a 01. Albums, on rotation. The library with two albums, and an album open showing its wallpapers. -An album holds single images, whole folders, or both. Paperize rescans folders each time you open the app, and every hour while a schedule is running, so new files join the rotation and deleted ones leave it by themselves; **Refresh folder** rescans one straight away. Open an album's options menu to rename or delete it, or rescan all its folders. Removing something from an album never touches the file on your device. +An album holds single images, whole folders, or both. Paperize rescans folders each time you open the app, and every hour while a schedule is running, so new files join the rotation and deleted ones leave it by themselves; **Refresh folder** rescans one straight away. Open an album's options menu to rename or delete it, filter it (encrypted albums), or rescan all its folders. Removing something from an album never touches the file on your device. -When creating an album, you can mark it encrypted; this choice is permanent and imports only `.jpg_enc` files made by wallpaper_changer. Set the same passphrase in **Settings → Encrypted albums**. It is protected by Android Keystore and remains available for scheduled changes. Encrypted previews are off by default; enabling them decrypts images in memory without caching them to disk. Turning previews off removes them from the app's display. Android may still retain the applied wallpaper, and wallpaper_changer's encryption format does not authenticate its contents. +When creating an album, you can mark it encrypted; this choice is permanent and imports only `.jpg_enc` files made by wallpaper_changer. Set the same passphrase in **Settings → Encrypted albums**. **Filter wallpapers** in the album menu takes a regular expression matched (ignoring case) against each line of the folder's `naming_table.enc` (`name;encrypted file;hash`), as wallpaper_changer does; every image is imported but only matching ones are picked as wallpaper, and images in folders without a naming table never match. It is protected by Android Keystore and remains available for scheduled changes. Encrypted previews are off by default; enabling them decrypts images in memory without caching them to disk. Turning previews off removes them from the app's display. Android may still retain the applied wallpaper, and wallpaper_changer's encryption format does not authenticate its contents. Supported formats: JPG, PNG, WEBP, AVIF, HEIC/HEIF, BMP, GIF and TIFF. diff --git a/app/schemas/com.anthonyla.paperize.data.database.PaperizeDatabase/7.json b/app/schemas/com.anthonyla.paperize.data.database.PaperizeDatabase/7.json new file mode 100644 index 0000000..c29f588 --- /dev/null +++ b/app/schemas/com.anthonyla.paperize.data.database.PaperizeDatabase/7.json @@ -0,0 +1,524 @@ +{ + "formatVersion": 1, + "database": { + "version": 7, + "identityHash": "dd85d0b5892ec87e1bc8906b1f42a004", + "entities": [ + { + "tableName": "albums", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `coverUri` TEXT, `createdAt` INTEGER NOT NULL, `modifiedAt` INTEGER NOT NULL, `isEncrypted` INTEGER NOT NULL DEFAULT 0, `filter` TEXT, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coverUri", + "columnName": "coverUri", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "modifiedAt", + "columnName": "modifiedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isEncrypted", + "columnName": "isEncrypted", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "filter", + "columnName": "filter", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + } + }, + { + "tableName": "wallpapers", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `albumId` TEXT NOT NULL, `folderId` TEXT, `uri` TEXT NOT NULL, `fileName` TEXT NOT NULL, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `sourceType` TEXT NOT NULL, `addedAt` INTEGER NOT NULL, `mediaType` TEXT NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`folderId`) REFERENCES `folders`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "albumId", + "columnName": "albumId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "folderId", + "columnName": "folderId", + "affinity": "TEXT" + }, + { + "fieldPath": "uri", + "columnName": "uri", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "fileName", + "columnName": "fileName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dateModified", + "columnName": "dateModified", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "displayOrder", + "columnName": "displayOrder", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "sourceType", + "columnName": "sourceType", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "addedAt", + "columnName": "addedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mediaType", + "columnName": "mediaType", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_wallpapers_albumId", + "unique": false, + "columnNames": [ + "albumId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_albumId` ON `${TABLE_NAME}` (`albumId`)" + }, + { + "name": "index_wallpapers_folderId", + "unique": false, + "columnNames": [ + "folderId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_folderId` ON `${TABLE_NAME}` (`folderId`)" + }, + { + "name": "index_wallpapers_uri", + "unique": false, + "columnNames": [ + "uri" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_uri` ON `${TABLE_NAME}` (`uri`)" + } + ], + "foreignKeys": [ + { + "table": "albums", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "albumId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "folders", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "folderId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "folders", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `albumId` TEXT NOT NULL, `name` TEXT NOT NULL, `uri` TEXT NOT NULL, `coverUri` TEXT, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "albumId", + "columnName": "albumId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "uri", + "columnName": "uri", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coverUri", + "columnName": "coverUri", + "affinity": "TEXT" + }, + { + "fieldPath": "dateModified", + "columnName": "dateModified", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "displayOrder", + "columnName": "displayOrder", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "addedAt", + "columnName": "addedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_folders_albumId", + "unique": false, + "columnNames": [ + "albumId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_folders_albumId` ON `${TABLE_NAME}` (`albumId`)" + }, + { + "name": "index_folders_uri", + "unique": false, + "columnNames": [ + "uri" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_folders_uri` ON `${TABLE_NAME}` (`uri`)" + } + ], + "foreignKeys": [ + { + "table": "albums", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "albumId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "wallpaper_queue", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `albumId` TEXT NOT NULL, `wallpaperId` TEXT NOT NULL, `screenType` TEXT NOT NULL, `queuePosition` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`wallpaperId`) REFERENCES `wallpapers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "albumId", + "columnName": "albumId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "wallpaperId", + "columnName": "wallpaperId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "screenType", + "columnName": "screenType", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "queuePosition", + "columnName": "queuePosition", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "addedAt", + "columnName": "addedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_wallpaper_queue_albumId_screenType", + "unique": false, + "columnNames": [ + "albumId", + "screenType" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_albumId_screenType` ON `${TABLE_NAME}` (`albumId`, `screenType`)" + }, + { + "name": "index_wallpaper_queue_wallpaperId", + "unique": false, + "columnNames": [ + "wallpaperId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_wallpaperId` ON `${TABLE_NAME}` (`wallpaperId`)" + }, + { + "name": "index_wallpaper_queue_queuePosition", + "unique": false, + "columnNames": [ + "queuePosition" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_queuePosition` ON `${TABLE_NAME}` (`queuePosition`)" + } + ], + "foreignKeys": [ + { + "table": "albums", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "albumId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "wallpapers", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "wallpaperId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "wallpaper_current", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`albumId` TEXT NOT NULL, `screenType` TEXT NOT NULL, `wallpaperId` TEXT NOT NULL, `appliedAt` INTEGER NOT NULL, PRIMARY KEY(`albumId`, `screenType`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`wallpaperId`) REFERENCES `wallpapers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "albumId", + "columnName": "albumId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "screenType", + "columnName": "screenType", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "wallpaperId", + "columnName": "wallpaperId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "appliedAt", + "columnName": "appliedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "albumId", + "screenType" + ] + }, + "indices": [ + { + "name": "index_wallpaper_current_wallpaperId", + "unique": false, + "columnNames": [ + "wallpaperId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_current_wallpaperId` ON `${TABLE_NAME}` (`wallpaperId`)" + } + ], + "foreignKeys": [ + { + "table": "albums", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "albumId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "wallpapers", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "wallpaperId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "excluded_wallpapers", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`folderId` TEXT NOT NULL, `uri` TEXT NOT NULL, `id` TEXT NOT NULL, `fileName` TEXT NOT NULL, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, PRIMARY KEY(`folderId`, `uri`), FOREIGN KEY(`folderId`) REFERENCES `folders`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "folderId", + "columnName": "folderId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "uri", + "columnName": "uri", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "fileName", + "columnName": "fileName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dateModified", + "columnName": "dateModified", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "displayOrder", + "columnName": "displayOrder", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "addedAt", + "columnName": "addedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "folderId", + "uri" + ] + }, + "foreignKeys": [ + { + "table": "folders", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "folderId" + ], + "referencedColumns": [ + "id" + ] + } + ] + } + ], + "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, 'dd85d0b5892ec87e1bc8906b1f42a004')" + ] + } +} \ No newline at end of file diff --git a/app/src/androidTest/java/com/anthonyla/paperize/data/repository/AlbumRepositoryInstrumentedTest.kt b/app/src/androidTest/java/com/anthonyla/paperize/data/repository/AlbumRepositoryInstrumentedTest.kt index ecd4b6b..ad3fd13 100644 --- a/app/src/androidTest/java/com/anthonyla/paperize/data/repository/AlbumRepositoryInstrumentedTest.kt +++ b/app/src/androidTest/java/com/anthonyla/paperize/data/repository/AlbumRepositoryInstrumentedTest.kt @@ -29,8 +29,9 @@ import org.junit.runner.RunWith class AlbumRepositoryInstrumentedTest { private val context = ApplicationProvider.getApplicationContext() private val db = Room.inMemoryDatabaseBuilder(context, PaperizeDatabase::class.java).build() - private val wallpapers = WallpaperRepositoryImpl(db) - private val albums = AlbumRepositoryImpl(com.anthonyla.paperize.data.source.AndroidDocumentSource(context), db) + private val documents = com.anthonyla.paperize.data.source.AndroidDocumentSource(context) + private val wallpapers = WallpaperRepositoryImpl(db, documents, com.anthonyla.paperize.data.source.EncryptedImageStore(context)) + private val albums = AlbumRepositoryImpl(documents, db) @After fun close() = db.close() diff --git a/app/src/androidTest/java/com/anthonyla/paperize/presentation/AlbumUiInstrumentedTest.kt b/app/src/androidTest/java/com/anthonyla/paperize/presentation/AlbumUiInstrumentedTest.kt index d2432a5..92e415f 100644 --- a/app/src/androidTest/java/com/anthonyla/paperize/presentation/AlbumUiInstrumentedTest.kt +++ b/app/src/androidTest/java/com/anthonyla/paperize/presentation/AlbumUiInstrumentedTest.kt @@ -121,7 +121,7 @@ class AlbumUiInstrumentedTest { AlbumViewTopBar( title = "Album", isSelectionMode = false, selectedCount = 0, allSelected = false, onBackClick = {}, onSortClick = {}, onDeleteAlbum = { action = "delete" }, - onRenameAlbum = { action = "rename" }, onRefreshFolders = { action = "refresh" }, + onRenameAlbum = { action = "rename" }, onFilterAlbum = null, onRefreshFolders = { action = "refresh" }, albumActionsEnabled = true, hasFolders = hasFolders.value, onSelectAll = {}, onDeleteSelected = {}, onClearSelection = {} ) diff --git a/app/src/main/java/com/anthonyla/paperize/core/constants/Constants.kt b/app/src/main/java/com/anthonyla/paperize/core/constants/Constants.kt index 6420916..53c9717 100644 --- a/app/src/main/java/com/anthonyla/paperize/core/constants/Constants.kt +++ b/app/src/main/java/com/anthonyla/paperize/core/constants/Constants.kt @@ -2,7 +2,7 @@ package com.anthonyla.paperize.core.constants object Constants { const val DATABASE_NAME = "paperize_database" - const val DATABASE_VERSION = 6 + const val DATABASE_VERSION = 7 const val PREFERENCES_NAME = "paperize_preferences" diff --git a/app/src/main/java/com/anthonyla/paperize/data/database/PaperizeDatabase.kt b/app/src/main/java/com/anthonyla/paperize/data/database/PaperizeDatabase.kt index 61cfa25..c91e28f 100644 --- a/app/src/main/java/com/anthonyla/paperize/data/database/PaperizeDatabase.kt +++ b/app/src/main/java/com/anthonyla/paperize/data/database/PaperizeDatabase.kt @@ -28,7 +28,7 @@ import com.anthonyla.paperize.core.constants.Constants ], version = Constants.DATABASE_VERSION, exportSchema = true, - autoMigrations = [AutoMigration(from = 4, to = 5)] + autoMigrations = [AutoMigration(from = 4, to = 5), AutoMigration(from = 6, to = 7)] ) abstract class PaperizeDatabase : RoomDatabase() { abstract fun albumDao(): AlbumDao diff --git a/app/src/main/java/com/anthonyla/paperize/data/database/dao/AlbumDao.kt b/app/src/main/java/com/anthonyla/paperize/data/database/dao/AlbumDao.kt index 742b295..faf403f 100644 --- a/app/src/main/java/com/anthonyla/paperize/data/database/dao/AlbumDao.kt +++ b/app/src/main/java/com/anthonyla/paperize/data/database/dao/AlbumDao.kt @@ -42,6 +42,9 @@ interface AlbumDao { @Query("UPDATE albums SET name = :name, modifiedAt = :modifiedAt WHERE id = :albumId") suspend fun renameAlbum(albumId: String, name: String, modifiedAt: Long): Int + @Query("UPDATE albums SET filter = :filter, modifiedAt = :modifiedAt WHERE id = :albumId") + suspend fun setFilter(albumId: String, filter: String?, modifiedAt: Long): Int + @Query("UPDATE albums SET coverUri = :coverUri, modifiedAt = :modifiedAt WHERE id = :albumId") suspend fun updateAlbumCover(albumId: String, coverUri: String?, modifiedAt: Long) diff --git a/app/src/main/java/com/anthonyla/paperize/data/database/dao/WallpaperDao.kt b/app/src/main/java/com/anthonyla/paperize/data/database/dao/WallpaperDao.kt index e9ba205..8ba7564 100644 --- a/app/src/main/java/com/anthonyla/paperize/data/database/dao/WallpaperDao.kt +++ b/app/src/main/java/com/anthonyla/paperize/data/database/dao/WallpaperDao.kt @@ -35,6 +35,9 @@ interface WallpaperDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertWallpapers(wallpapers: List) + @Query("SELECT * FROM wallpapers WHERE folderId = :folderId") + suspend fun getFolderWallpapers(folderId: String): List + @Query("SELECT id FROM wallpapers WHERE albumId = :albumId") suspend fun getWallpaperIdsByAlbum(albumId: String): List diff --git a/app/src/main/java/com/anthonyla/paperize/data/database/entities/AlbumEntity.kt b/app/src/main/java/com/anthonyla/paperize/data/database/entities/AlbumEntity.kt index 4392a46..8cbe1fa 100644 --- a/app/src/main/java/com/anthonyla/paperize/data/database/entities/AlbumEntity.kt +++ b/app/src/main/java/com/anthonyla/paperize/data/database/entities/AlbumEntity.kt @@ -12,5 +12,6 @@ data class AlbumEntity( val coverUri: String?, val createdAt: Long = System.currentTimeMillis(), val modifiedAt: Long = System.currentTimeMillis(), - @ColumnInfo(defaultValue = "0") val isEncrypted: Boolean = false + @ColumnInfo(defaultValue = "0") val isEncrypted: Boolean = false, + val filter: String? = null ) diff --git a/app/src/main/java/com/anthonyla/paperize/data/mapper/AlbumMapper.kt b/app/src/main/java/com/anthonyla/paperize/data/mapper/AlbumMapper.kt index 27d97e2..c75dbd4 100644 --- a/app/src/main/java/com/anthonyla/paperize/data/mapper/AlbumMapper.kt +++ b/app/src/main/java/com/anthonyla/paperize/data/mapper/AlbumMapper.kt @@ -19,7 +19,8 @@ fun AlbumEntity.toDomainModel( folders = folders, createdAt = createdAt, modifiedAt = modifiedAt, - isEncrypted = isEncrypted + isEncrypted = isEncrypted, + filter = filter ) fun Album.toEntity(): AlbumEntity = AlbumEntity( @@ -28,7 +29,8 @@ fun Album.toEntity(): AlbumEntity = AlbumEntity( coverUri = coverUri, createdAt = createdAt, modifiedAt = modifiedAt, - isEncrypted = isEncrypted + isEncrypted = isEncrypted, + filter = filter ) fun AlbumWithDetails.toDomainModel(): Album { diff --git a/app/src/main/java/com/anthonyla/paperize/data/repository/AlbumRepositoryImpl.kt b/app/src/main/java/com/anthonyla/paperize/data/repository/AlbumRepositoryImpl.kt index 84be764..f2744e4 100644 --- a/app/src/main/java/com/anthonyla/paperize/data/repository/AlbumRepositoryImpl.kt +++ b/app/src/main/java/com/anthonyla/paperize/data/repository/AlbumRepositoryImpl.kt @@ -63,6 +63,11 @@ class AlbumRepositoryImpl @Inject constructor( true } + override suspend fun setAlbumFilter(albumId: String, filter: String?) = database.withTransaction { + check(albumDao.setFilter(albumId, filter?.takeIf { it.isNotBlank() }, System.currentTimeMillis()) == 1) + database.wallpaperQueueDao().clearAllQueues(albumId) + } + override suspend fun addWallpapersToAlbum( albumId: String, wallpapers: List, diff --git a/app/src/main/java/com/anthonyla/paperize/data/repository/WallpaperRepositoryImpl.kt b/app/src/main/java/com/anthonyla/paperize/data/repository/WallpaperRepositoryImpl.kt index 066dd26..3025630 100644 --- a/app/src/main/java/com/anthonyla/paperize/data/repository/WallpaperRepositoryImpl.kt +++ b/app/src/main/java/com/anthonyla/paperize/data/repository/WallpaperRepositoryImpl.kt @@ -7,7 +7,11 @@ import com.anthonyla.paperize.data.database.PaperizeDatabase import com.anthonyla.paperize.data.database.entities.WallpaperCurrentEntity import com.anthonyla.paperize.data.mapper.toDomainModel import com.anthonyla.paperize.domain.model.Wallpaper +import com.anthonyla.paperize.data.source.EncryptedImageStore import com.anthonyla.paperize.domain.repository.WallpaperRepository +import com.anthonyla.paperize.domain.source.DocumentSource +import com.anthonyla.paperize.domain.source.albumFilterRegex +import com.anthonyla.paperize.domain.source.matchingNamingTableFiles import javax.inject.Inject import javax.inject.Singleton import kotlinx.coroutines.flow.Flow @@ -16,7 +20,9 @@ import kotlinx.coroutines.flow.map @Singleton class WallpaperRepositoryImpl @Inject constructor( - private val database: PaperizeDatabase + private val database: PaperizeDatabase, + private val documents: DocumentSource, + private val encryptedImages: EncryptedImageStore ) : WallpaperRepository { private val wallpaperDao = database.wallpaperDao() @@ -50,6 +56,8 @@ class WallpaperRepositoryImpl @Inject constructor( screenType: ScreenType, shuffle: Boolean ) { + if (wallpaperQueueDao.getNextWallpaperInQueue(albumId, screenType) != null) return + val allowed = allowedWallpaperIds(albumId) database.withTransaction { // Recheck inside the transaction: another caller may already have filled it. if (wallpaperQueueDao.getNextWallpaperInQueue(albumId, screenType) != null) return@withTransaction @@ -60,11 +68,11 @@ class WallpaperRepositoryImpl @Inject constructor( } else null val otherQueue = otherScreen?.let { wallpaperQueueDao.getQueueItems(albumId, it) }.orEmpty() val ids = if (shuffle) { - val available = wallpaperDao.getWallpaperIdsByAlbum(albumId) + val available = wallpaperDao.getWallpaperIdsByAlbum(albumId).allowed(allowed) if (otherQueue.isEmpty()) available.shuffled() else QueueBuilder.mergeWithExistingQueue(otherQueue.map { it.wallpaperId }, available) } else { - wallpaperDao.getOrderedWallpaperIdsByAlbum(albumId) + wallpaperDao.getOrderedWallpaperIdsByAlbum(albumId).allowed(allowed) } wallpaperQueueDao.rebuildQueue(albumId, screenType, ids) if (otherScreen != null && otherQueue.isEmpty()) { @@ -78,12 +86,31 @@ class WallpaperRepositoryImpl @Inject constructor( screenType: ScreenType, wallpaperId: String ) { + val allowed = allowedWallpaperIds(albumId) database.withTransaction { val ordered = wallpaperDao.getOrderedWallpaperIdsByAlbum(albumId) - wallpaperQueueDao.rebuildQueue(albumId, screenType, QueueBuilder.idsAfter(ordered, wallpaperId)) + wallpaperQueueDao.rebuildQueue( + albumId, screenType, QueueBuilder.idsAfter(ordered, wallpaperId).allowed(allowed) + ) } } + private fun List.allowed(allowed: Set?) = if (allowed == null) this else filter { it in allowed } + + /** Ids passing the album filter, or null without one. Images outside a folder with a naming table never pass. */ + private suspend fun allowedWallpaperIds(albumId: String): Set? { + val filter = database.albumDao().getAlbumById(albumId)?.filter?.let(::albumFilterRegex) ?: return null + val allowed = HashSet() + database.folderDao().getFoldersByAlbum(albumId).forEach { folder -> + val table = documents.readNamingTable(folder.uri) ?: return@forEach + val files = matchingNamingTableFiles(encryptedImages.decrypt(table).decodeToString(), filter) + wallpaperDao.getFolderWallpapers(folder.id) + .filter { it.fileName.substringAfterLast('/') in files } + .mapTo(allowed) { it.id } + } + return allowed + } + override suspend fun clearAllQueues() { wallpaperQueueDao.deleteAllQueueItems() } diff --git a/app/src/main/java/com/anthonyla/paperize/data/source/AndroidDocumentSource.kt b/app/src/main/java/com/anthonyla/paperize/data/source/AndroidDocumentSource.kt index a8e93b7..c15048f 100644 --- a/app/src/main/java/com/anthonyla/paperize/data/source/AndroidDocumentSource.kt +++ b/app/src/main/java/com/anthonyla/paperize/data/source/AndroidDocumentSource.kt @@ -12,6 +12,7 @@ import androidx.core.net.toUri import androidx.documentfile.provider.DocumentFile import com.anthonyla.paperize.core.runCatchingCancellable import com.anthonyla.paperize.domain.source.DocumentSource +import com.anthonyla.paperize.domain.source.NAMING_TABLE_FILE import com.anthonyla.paperize.domain.source.SourceFolder import com.anthonyla.paperize.domain.source.SourceImage import com.anthonyla.paperize.domain.source.isSupportedSourceName @@ -45,6 +46,19 @@ class AndroidDocumentSource @Inject constructor( ) } + override suspend fun readNamingTable(folderUri: String): ByteArray? = withContext(Dispatchers.IO) { + val tree = folderUri.toUri() + val children = DocumentsContract.buildChildDocumentsUriUsingTree(tree, DocumentsContract.getTreeDocumentId(tree)) + val projection = arrayOf(DocumentsContract.Document.COLUMN_DOCUMENT_ID, DocumentsContract.Document.COLUMN_DISPLAY_NAME) + val documentId = context.contentResolver.query(children, projection, null, null, null)?.use { cursor -> + cursor.requireComplete() + generateSequence { if (cursor.moveToNext()) cursor else null } + .firstOrNull { it.getString(1) == NAMING_TABLE_FILE }?.getString(0) + } ?: return@withContext null + val table = DocumentsContract.buildDocumentUriUsingTree(tree, documentId) + context.contentResolver.openInputStream(table)?.use { it.readBytes() } + } + override suspend fun isMissing(uri: String, isTree: Boolean): Boolean = withContext(Dispatchers.IO) { val source = uri.toUri() val document = if (isTree) { diff --git a/app/src/main/java/com/anthonyla/paperize/data/source/EncryptedImageStore.kt b/app/src/main/java/com/anthonyla/paperize/data/source/EncryptedImageStore.kt index 24692cd..db86f3d 100644 --- a/app/src/main/java/com/anthonyla/paperize/data/source/EncryptedImageStore.kt +++ b/app/src/main/java/com/anthonyla/paperize/data/source/EncryptedImageStore.kt @@ -80,6 +80,8 @@ class EncryptedImageStore @Inject constructor( return decryptEncryptedImage(bytes, passphrase) } + fun decrypt(bytes: ByteArray): ByteArray = decryptEncryptedImage(bytes, synchronized(this) { readPassphrase() }) + private fun readPassphrase(): String { if (!hasPassphrase()) throw MissingPassphraseException() try { diff --git a/app/src/main/java/com/anthonyla/paperize/domain/model/Album.kt b/app/src/main/java/com/anthonyla/paperize/domain/model/Album.kt index b9f2507..cc70035 100644 --- a/app/src/main/java/com/anthonyla/paperize/domain/model/Album.kt +++ b/app/src/main/java/com/anthonyla/paperize/domain/model/Album.kt @@ -8,5 +8,7 @@ data class Album( val folders: List = emptyList(), val createdAt: Long = System.currentTimeMillis(), val modifiedAt: Long = System.currentTimeMillis(), - val isEncrypted: Boolean = false + val isEncrypted: Boolean = false, + /** Regex over naming-table lines; only matching images are picked as wallpaper. */ + val filter: String? = null ) diff --git a/app/src/main/java/com/anthonyla/paperize/domain/repository/AlbumRepository.kt b/app/src/main/java/com/anthonyla/paperize/domain/repository/AlbumRepository.kt index 6214a98..150a4bf 100644 --- a/app/src/main/java/com/anthonyla/paperize/domain/repository/AlbumRepository.kt +++ b/app/src/main/java/com/anthonyla/paperize/domain/repository/AlbumRepository.kt @@ -20,6 +20,9 @@ interface AlbumRepository { /** Returns false if another album has this name, ignoring case. */ suspend fun renameAlbum(albumId: String, name: String): Boolean + /** A null or blank [filter] removes it. Rebuilds the album queues. */ + suspend fun setAlbumFilter(albumId: String, filter: String?) + suspend fun deleteAlbum(albumId: String) /** Returns the number of new images. Progress counts rows written within the transaction. */ diff --git a/app/src/main/java/com/anthonyla/paperize/domain/source/DocumentSource.kt b/app/src/main/java/com/anthonyla/paperize/domain/source/DocumentSource.kt index 69668ac..156066f 100644 --- a/app/src/main/java/com/anthonyla/paperize/domain/source/DocumentSource.kt +++ b/app/src/main/java/com/anthonyla/paperize/domain/source/DocumentSource.kt @@ -13,5 +13,7 @@ interface DocumentSource { suspend fun retainReadPermission(uri: String) suspend fun readImage(uri: String): SourceImage suspend fun readFolder(uri: String, isEncrypted: Boolean, onProgress: (Int) -> Unit = {}): SourceFolder + /** The [NAMING_TABLE_FILE] in the root of a folder, or null if it has none. */ + suspend fun readNamingTable(folderUri: String): ByteArray? suspend fun isMissing(uri: String, isTree: Boolean = false): Boolean } diff --git a/app/src/main/java/com/anthonyla/paperize/domain/source/NamingTable.kt b/app/src/main/java/com/anthonyla/paperize/domain/source/NamingTable.kt new file mode 100644 index 0000000..91ceeac --- /dev/null +++ b/app/src/main/java/com/anthonyla/paperize/domain/source/NamingTable.kt @@ -0,0 +1,12 @@ +package com.anthonyla.paperize.domain.source + +const val NAMING_TABLE_FILE = "naming_table.enc" + +fun albumFilterRegex(pattern: String) = Regex(pattern, RegexOption.IGNORE_CASE) + +/** File names of the entries whose `name;encrypted_file;hash` line contains a [filter] match, like wallpaper_changer. */ +fun matchingNamingTableFiles(table: String, filter: Regex): Set = + table.lineSequence() + .filter { it.count { c -> c == ';' } >= 2 && filter.containsMatchIn(it) } + .map { it.split(';', limit = 3)[1].substringAfterLast('/') } + .toSet() diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewScreen.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewScreen.kt index 428bc0a..acbbc4f 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewScreen.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewScreen.kt @@ -72,6 +72,10 @@ fun AlbumViewScreen( var renameText by rememberSaveable { mutableStateOf("") } var renameError by rememberSaveable { mutableStateOf(null) } var isRenaming by remember { mutableStateOf(false) } + var showFilterDialog by rememberSaveable { mutableStateOf(false) } + var filterText by rememberSaveable { mutableStateOf("") } + var filterError by rememberSaveable { mutableStateOf(null) } + var isFiltering by remember { mutableStateOf(false) } val scope = rememberCoroutineScope() val snackbarHostState = remember { SnackbarHostState() } SnackbarMessageEffect(message, snackbarHostState, viewModel::dismissMessage) @@ -132,6 +136,13 @@ fun AlbumViewScreen( renameError = null showRenameDialog = true }, + onFilterAlbum = if (album?.isEncrypted == true) { + { + filterText = album?.filter.orEmpty() + filterError = null + showFilterDialog = true + } + } else null, onRefreshFolders = viewModel::refreshFolders, albumActionsEnabled = album != null && !isDeleting && !isRefreshing && importProgress is ImportProgress.Idle, hasFolders = folders.isNotEmpty(), @@ -266,6 +277,49 @@ fun AlbumViewScreen( ) } + if (showFilterDialog) { + AlertDialog( + onDismissRequest = { if (!isFiltering) showFilterDialog = false }, + title = { Text(stringResource(R.string.filter_album)) }, + text = { + OutlinedTextField( + value = filterText, + onValueChange = { filterText = it; filterError = null }, + label = { Text(stringResource(R.string.filter_pattern)) }, + supportingText = { + val error = filterError + if (error != null) Text(stringResource(error), color = MaterialTheme.colorScheme.error) + else Text(stringResource(R.string.filter_pattern_hint)) + }, + singleLine = true, + enabled = !isFiltering, + isError = filterError != null + ) + }, + confirmButton = { + TextButton( + enabled = !isFiltering, + onClick = { + isFiltering = true + scope.launch { + try { + filterError = viewModel.setFilter(filterText.trim()) + if (filterError == null) showFilterDialog = false + } finally { + isFiltering = false + } + } + } + ) { Text(stringResource(R.string.save)) } + }, + dismissButton = { + TextButton(onClick = { showFilterDialog = false }, enabled = !isFiltering) { + Text(stringResource(R.string.cancel)) + } + } + ) + } + if (showDeleteSelectedDialog) { ConfirmDialog( title = stringResource(R.string.remove_selected_title, selectedCount), diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewViewModel.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewViewModel.kt index aa3af91..ad6544e 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewViewModel.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewViewModel.kt @@ -9,6 +9,7 @@ import com.anthonyla.paperize.R import com.anthonyla.paperize.core.runCatchingCancellable import com.anthonyla.paperize.domain.model.Album import com.anthonyla.paperize.domain.repository.AlbumRepository +import com.anthonyla.paperize.domain.source.albumFilterRegex import com.anthonyla.paperize.domain.usecase.DeleteAlbumUseCase import com.anthonyla.paperize.domain.usecase.ImportWallpapersUseCase import com.anthonyla.paperize.domain.usecase.RefreshFolderUseCase @@ -128,6 +129,18 @@ class AlbumViewViewModel @Inject constructor( } ) + suspend fun setFilter(filter: String): Int? { + if (runCatching { albumFilterRegex(filter) }.isFailure) return R.string.filter_invalid + return runCatchingCancellable { albumRepository.setAlbumFilter(albumId, filter) } + .fold( + onSuccess = { null }, + onFailure = { e -> + Log.e(TAG, "Error setting album filter", e) + R.string.filter_album_failed + } + ) + } + fun refreshFolders() { if (_isRefreshing.value || _isDeleting.value || importJob?.isCompleted == false) return _message.value = null diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/components/AlbumViewTopBar.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/components/AlbumViewTopBar.kt index d129e98..0d02a9b 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/components/AlbumViewTopBar.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/components/AlbumViewTopBar.kt @@ -36,6 +36,7 @@ fun AlbumViewTopBar( onSortClick: () -> Unit, onDeleteAlbum: () -> Unit, onRenameAlbum: () -> Unit, + onFilterAlbum: (() -> Unit)?, onRefreshFolders: () -> Unit, albumActionsEnabled: Boolean, hasFolders: Boolean, @@ -96,6 +97,10 @@ fun AlbumViewTopBar( text = { Text(stringResource(R.string.rename_album)) }, onClick = { menuExpanded = false; onRenameAlbum() } ) + if (onFilterAlbum != null) DropdownMenuItem( + text = { Text(stringResource(R.string.filter_album)) }, + onClick = { menuExpanded = false; onFilterAlbum() } + ) DropdownMenuItem( text = { Text(stringResource(R.string.refresh_album_folders)) }, enabled = hasFolders, diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index f5ea493..afb5349 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -13,6 +13,11 @@ Album options Rename album Could not rename the album. Please try again. + Filter wallpapers + Filter pattern + Regular expression matched against the naming table. Empty uses every image. + Not a valid regular expression. + Could not save the filter. Please try again. Rescan all folders Album folders checked for new wallpapers. Some folders could not be rescanned. Check that they are accessible, then try again. diff --git a/app/src/test/java/com/anthonyla/paperize/domain/source/NamingTableTest.kt b/app/src/test/java/com/anthonyla/paperize/domain/source/NamingTableTest.kt new file mode 100644 index 0000000..cea8f35 --- /dev/null +++ b/app/src/test/java/com/anthonyla/paperize/domain/source/NamingTableTest.kt @@ -0,0 +1,21 @@ +package com.anthonyla.paperize.domain.source + +import org.junit.Assert.assertEquals +import org.junit.Test + +class NamingTableTest { + private val table = "beach.jpg;a1.jpg_enc;h1\nforest.jpg;sub/b2.jpg_enc;h2\n\nbroken line\ncity.jpg;c3.jpg_enc;h3\n" + + @Test fun matchesAnyPartOfTheLine() { + assertEquals(setOf("a1.jpg_enc", "b2.jpg_enc"), matchingNamingTableFiles(table, albumFilterRegex("beach|forest"))) + assertEquals(setOf("c3.jpg_enc"), matchingNamingTableFiles(table, Regex(";h3$"))) + } + + @Test fun ignoresCase() { + assertEquals(setOf("a1.jpg_enc"), matchingNamingTableFiles(table, albumFilterRegex("BEACH"))) + } + + @Test fun ignoresLinesWithoutThreeFields() { + assertEquals(emptySet(), matchingNamingTableFiles(table, Regex("broken"))) + } +}