feat(album): support encrypted wallpaper albums #1

Merged
lucas merged 8 commits from dev-LFA into main-LFA 2026-11-22 16:24:26 +01:00
56 changed files with 1666 additions and 95 deletions

No files matched your search

+69
View File
@@ -0,0 +1,69 @@
name: Paperize Android Debug CI
on:
push:
branches: ["dev-LFA"]
pull_request:
branches: ["dev-LFA"]
workflow_dispatch:
permissions:
contents: read
jobs:
test-and-lint:
name: Run unit tests and lint
runs-on: ubuntu-latest
steps:
- name: Check out source code
uses: actions/checkout@v4
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
java-version: "17"
distribution: temurin
- name: Set up Android SDK
uses: android-actions/setup-android@v3
with:
packages: platform-tools
- name: Install Android SDK 37
run: sdkmanager --install "platforms;android-37.0" "build-tools;37.0.0"
- name: Run unit tests and lint
run: ./gradlew testDebugUnitTest lintDebug
build:
name: Build debug APK
if: github.event_name == 'push'
needs: test-and-lint
runs-on: ubuntu-latest
steps:
- name: Check out source code
uses: actions/checkout@v4
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
java-version: "17"
distribution: temurin
- name: Set up Android SDK
uses: android-actions/setup-android@v3
with:
packages: platform-tools
- name: Install Android SDK 37
run: sdkmanager --install "platforms;android-37.0" "build-tools;37.0.0"
- name: Build debug APK
run: ./gradlew assembleDebug
- name: Upload debug APK
uses: https://github.com/christopherHX/gitea-upload-artifact@v4
with:
name: paperize-debug-apk
path: app/build/outputs/apk/debug/app-debug.apk
if-no-files-found: error
+80
View File
@@ -0,0 +1,80 @@
name: Paperize Android Release CI
on:
push:
branches: ["main-LFA"]
permissions:
contents: read
jobs:
test-and-lint:
name: Run unit tests and lint
runs-on: ubuntu-latest
steps:
- name: Check out source code
uses: actions/checkout@v4
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
java-version: "17"
distribution: temurin
- name: Set up Android SDK
uses: android-actions/setup-android@v3
with:
packages: platform-tools
- name: Install Android SDK 37
run: sdkmanager --install "platforms;android-37.0" "build-tools;37.0.0"
- name: Run unit tests and lint
run: ./gradlew testDebugUnitTest lintDebug
build:
name: Build release APK
needs: test-and-lint
runs-on: ubuntu-latest
steps:
- name: Check out source code
uses: actions/checkout@v4
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
java-version: "17"
distribution: temurin
- name: Set up Android SDK
uses: android-actions/setup-android@v3
with:
packages: platform-tools
- name: Install Android SDK 37
run: sdkmanager --install "platforms;android-37.0" "build-tools;37.0.0"
- name: Build signed release APK
env:
SIGNING_KEYSTORE_BASE64: ${{ secrets.SIGNING_KEYSTORE_BASE64 }}
SIGNING_KEY_ALIAS: ${{ secrets.SIGNING_KEY_ALIAS }}
SIGNING_STORE_PASSWORD: ${{ secrets.SIGNING_STORE_PASSWORD }}
SIGNING_KEY_PASSWORD: ${{ secrets.SIGNING_KEY_PASSWORD }}
shell: bash
run: |
set -euo pipefail
: "${SIGNING_KEYSTORE_BASE64:?Missing SIGNING_KEYSTORE_BASE64 secret}"
: "${SIGNING_KEY_ALIAS:?Missing SIGNING_KEY_ALIAS secret}"
: "${SIGNING_STORE_PASSWORD:?Missing SIGNING_STORE_PASSWORD secret}"
: "${SIGNING_KEY_PASSWORD:?Missing SIGNING_KEY_PASSWORD secret}"
export SIGNING_KEYSTORE_PATH="$(mktemp "${RUNNER_TEMP}/paperize-keystore.XXXXXX")"
trap 'rm -f "$SIGNING_KEYSTORE_PATH"' EXIT
printf '%s' "$SIGNING_KEYSTORE_BASE64" | base64 --decode > "$SIGNING_KEYSTORE_PATH"
./gradlew assembleRelease
- name: Upload release APK
uses: https://github.com/christopherHX/gitea-upload-artifact@v4
with:
name: paperize-release-apk
path: app/build/outputs/apk/release/app-release.apk
if-no-files-found: error
File renamed without changes.
File renamed without changes.
File renamed without changes.
+2
View File
@@ -22,6 +22,8 @@ Paperize is an Android app that changes your home and lock screen wallpaper on a
An album holds single images, whole folders, or both. Paperize rescans folders each time you open the app, and once a day while a schedule is running, so new files join the rotation and deleted ones leave it by themselves; **Refresh folder** rescans one straight away. 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.
Supported formats: JPG, PNG, WEBP, AVIF, HEIC/HEIF, BMP, GIF and TIFF.
<picture>
@@ -0,0 +1,451 @@
{
"formatVersion": 1,
"database": {
"version": 5,
"identityHash": "1ce8cde8f3aa8c69ae7806c22f502d86",
"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, 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"
}
],
"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"
]
}
]
}
],
"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, '1ce8cde8f3aa8c69ae7806c22f502d86')"
]
}
}
@@ -72,7 +72,7 @@ class DocumentAccessInstrumentedTest {
}
provider.answer = { cursor }
try {
treeUri.scanFolderImages(context)
treeUri.scanFolderImages(context, false)
fail("Expected incomplete scan failure")
} catch (_: java.io.IOException) { }
assertTrue(cursor.isClosed)
@@ -91,13 +91,31 @@ class DocumentAccessInstrumentedTest {
}
}
}
val found = treeUri.scanFolderImages(context)
val found = treeUri.scanFolderImages(context, false)
assertEquals(1, found.size)
assertEquals("photo.PNG", found.single().name)
assertEquals(42L, found.single().modifiedAt)
assertEquals(2, provider.queries)
}
@Test fun scansOnlyFilesForTheAlbumModeIncludingNestedDirectories() = runBlocking {
provider.answer = { uri ->
when (DocumentsContract.getDocumentId(uri)) {
"root" -> directoryCursor().apply {
addRow(arrayOf<Any>("child", "Child", DocumentsContract.Document.MIME_TYPE_DIR, 0L))
addRow(arrayOf<Any>("plain", "photo.JPG", "image/jpeg", 1L))
addRow(arrayOf<Any>("encrypted", "photo.JPG_ENC", "application/octet-stream", 2L))
addRow(arrayOf<Any>("other", "photo.png_enc", "application/octet-stream", 3L))
}
else -> directoryCursor().apply {
addRow(arrayOf<Any>("nested", "nested.jpg_enc", "application/octet-stream", 4L))
}
}
}
assertEquals(setOf("photo.JPG"), treeUri.scanFolderImages(context, false).map { it.name }.toSet())
assertEquals(setOf("photo.JPG_ENC", "nested.jpg_enc"), treeUri.scanFolderImages(context, true).map { it.name }.toSet())
}
@Test fun scanSkipsTrashedFilesButKeepsImagesInHiddenFolders() = runBlocking {
provider.answer = { uri ->
when (DocumentsContract.getDocumentId(uri)) {
@@ -115,7 +133,7 @@ class DocumentAccessInstrumentedTest {
else -> directoryCursor()
}
}
val found = treeUri.scanFolderImages(context)
val found = treeUri.scanFolderImages(context, false)
assertEquals(setOf("photo.jpg", "wall.png"), found.map { it.name }.toSet())
}
@@ -127,7 +145,7 @@ class DocumentAccessInstrumentedTest {
} else null
}
try {
treeUri.scanFolderImages(context)
treeUri.scanFolderImages(context, false)
fail("Expected child folder failure")
} catch (_: java.io.IOException) { }
}
@@ -141,7 +159,7 @@ class DocumentAccessInstrumentedTest {
check(cancelled.await(5, TimeUnit.SECONDS)) { "Provider query was not cancelled" }
signal?.throwIfCanceled()
}
val scan = launch(Dispatchers.IO) { treeUri.scanFolderImages(context) }
val scan = launch(Dispatchers.IO) { treeUri.scanFolderImages(context, false) }
assertTrue(started.await(5, TimeUnit.SECONDS))
scan.cancel()
scan.join()
@@ -16,7 +16,7 @@ class LibraryMigrationInstrumentedTest {
private val context = ApplicationProvider.getApplicationContext<Context>()
@Test fun everyLegacyVersionPreservesLibraryAndQueue() = runBlocking {
for (version in 1..3) {
for (version in 1..4) {
val name = "migration-test-$version"
context.deleteDatabase(name)
try {
@@ -26,6 +26,7 @@ class LibraryMigrationInstrumentedTest {
try {
assertEquals("My album", db.albumDao().getAlbumById("album")?.name)
assertEquals("content://image", db.albumDao().getAlbumById("album")?.coverUri)
assertFalse(db.albumDao().getAlbumById("album")!!.isEncrypted)
val image = db.wallpaperDao().getWallpaperById("image")!!
assertEquals("folder", image.folderId)
assertEquals("photo.jpg", image.fileName)
@@ -59,7 +60,8 @@ class LibraryMigrationInstrumentedTest {
// Verified against the version 1, 2 and 3 entities in Git history.
if (table == "wallpapers") {
create = if (version == 1) create.replace("`mediaType` TEXT NOT NULL, ", "")
else create.replace("PRIMARY KEY(`id`)", "`cropOffsetX` REAL, `cropOffsetY` REAL, `cropScale` REAL, PRIMARY KEY(`id`)")
else if (version < 4) create.replace("PRIMARY KEY(`id`)", "`cropOffsetX` REAL, `cropOffsetY` REAL, `cropScale` REAL, PRIMARY KEY(`id`)")
else create
}
db.execSQL(create)
val indices = entity.optJSONArray("indices")
@@ -34,6 +34,13 @@ class AlbumRepositoryInstrumentedTest {
@After fun close() = db.close()
@Test fun encryptedAlbumModeSurvivesPersistence() = runBlocking {
val album = albums.createAlbum("Encrypted", isEncrypted = true)
assertTrue(album.isEncrypted)
assertTrue(albums.getAlbumById(album.id).first()!!.isEncrypted)
assertFalse(albums.createAlbum("Ordinary").isEncrypted)
}
@Test fun cancellingAChunkedFolderImportRollsBackAllRows() = runBlocking {
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
val folder = testFolder("folder", "album").copy(
@@ -14,6 +14,19 @@ import org.junit.Assert.*
import org.junit.Test
class SettingsRepositoryInstrumentedTest {
@Test fun encryptedPreviewSettingPersistsAndCanBeDisabled() = runBlocking {
val preferences = SettingsRepositoryImpl(ApplicationProvider.getApplicationContext<Context>())
val original = preferences.getAppSettings().encryptedPreviews
try {
preferences.updateEncryptedPreviews(true)
assertTrue(preferences.getAppSettings().encryptedPreviews)
preferences.updateEncryptedPreviews(false)
assertFalse(preferences.getAppSettings().encryptedPreviews)
} finally {
preferences.updateEncryptedPreviews(original)
}
}
@Test fun concurrentScheduleEditsReadTheLatestValueWithoutLosingSelections() = runBlocking {
val preferences = SettingsRepositoryImpl(ApplicationProvider.getApplicationContext<Context>())
val previousSettings = preferences.getScheduleSettings()
@@ -0,0 +1,89 @@
package com.anthonyla.paperize.data.source
import android.content.ContentProvider
import android.content.ContentResolver
import android.content.ContentValues
import android.content.Context
import android.content.ContextWrapper
import android.database.Cursor
import android.net.Uri
import android.os.ParcelFileDescriptor
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.After
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import java.io.File
@RunWith(AndroidJUnit4::class)
class EncryptedImageStoreInstrumentedTest {
private val app = ApplicationProvider.getApplicationContext<Context>()
private val directory = File(app.cacheDir, "encrypted-image-store-test").apply { mkdirs() }
private val encryptedFile = File(directory, "image")
private val provider = ImageProvider(encryptedFile)
private val context = object : ContextWrapper(app) {
override fun getNoBackupFilesDir(): File = directory
override fun getContentResolver(): ContentResolver = ContentResolver.wrap(provider)
}
private val uri = Uri.parse("content://test/image")
private val encrypted = (
"53616c7465645f5f00010203040506075fccfb3397721c83694890dfe23e4516" +
"7b69d90d234d801114bb019d584a6f47"
).chunked(2).map { it.toInt(16).toByte() }.toByteArray()
@After fun cleanup() {
directory.deleteRecursively()
}
@Test fun persistsEncryptedPassphraseAndDecryptsProviderStream() {
encryptedFile.writeBytes(encrypted)
val store = EncryptedImageStore(context)
assertEquals(0, store.revision.value)
assertFalse(store.hasPassphrase())
assertThrows(MissingPassphraseException::class.java) { store.decrypt(uri) }
store.setPassphrase("päss漢字")
assertEquals(1, store.revision.value)
val stored = File(directory, "encrypted_image_passphrase").readBytes()
assertFalse(stored.toString(Charsets.UTF_8).contains("päss漢字"))
val reopened = EncryptedImageStore(context)
assertTrue(reopened.hasPassphrase())
assertArrayEquals(
"Paperize test image\u0000".toByteArray() + byteArrayOf(0xff.toByte()),
reopened.decrypt(uri)
)
reopened.setPassphrase("wrong")
assertEquals(1, reopened.revision.value)
assertThrows(IncorrectPassphraseException::class.java) { reopened.decrypt(uri) }
reopened.clearPassphrase()
assertEquals(2, reopened.revision.value)
assertFalse(store.hasPassphrase())
assertThrows(MissingPassphraseException::class.java) { reopened.decrypt(uri) }
}
@Test fun rejectsTamperedStoredPassphrase() {
val store = EncryptedImageStore(context)
store.setPassphrase("secret")
val file = File(directory, "encrypted_image_passphrase")
file.writeBytes(file.readBytes().apply { this[lastIndex] = (last().toInt() xor 1).toByte() })
assertThrows(PassphraseStorageException::class.java) { store.decrypt(uri) }
}
private class ImageProvider(private val file: File) : ContentProvider() {
override fun onCreate() = true
override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor =
ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
override fun query(uri: Uri, projection: Array<out String>?, selection: String?,
selectionArgs: Array<out String>?, sortOrder: String?): Cursor? = null
override fun getType(uri: Uri): String? = null
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0
override fun update(uri: Uri, values: ContentValues?, selection: String?,
selectionArgs: Array<out String>?): Int = 0
}
}
@@ -0,0 +1,145 @@
package com.anthonyla.paperize.data.source
import android.content.Context
import android.content.ContextWrapper
import android.graphics.Bitmap
import android.graphics.Color
import android.net.Uri
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.anthonyla.paperize.core.ScreenType
import com.anthonyla.paperize.core.util.getDeviceScreenSize
import com.anthonyla.paperize.domain.model.ScheduleSettings
import com.anthonyla.paperize.domain.model.Wallpaper
import com.anthonyla.paperize.service.livewallpaper.renderer.EncryptedImageLoader
import java.io.ByteArrayOutputStream
import java.io.File
import java.util.UUID
import javax.crypto.Cipher
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.PBEKeySpec
import javax.crypto.spec.SecretKeySpec
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class EncryptedRenderingInstrumentedTest {
private val instrumentation = InstrumentationRegistry.getInstrumentation()
private val directory = File(instrumentation.targetContext.cacheDir, "encrypted-render-${UUID.randomUUID()}")
private val context = object : ContextWrapper(instrumentation.targetContext) {
override fun getNoBackupFilesDir(): File = directory
}
private val encryptedFile = File(directory, "image.jpg_enc")
private val uri = Uri.fromFile(encryptedFile)
private val store = EncryptedImageStore(context)
private val renderer = AndroidWallpaperRenderer(context, store)
private val loader = EncryptedImageLoader(store, uri)
private val wallpaper = Wallpaper(
id = "image", albumId = "album", uri = uri.toString(),
fileName = "image.jpg_enc", dateModified = 0
)
private val passphrase = "päss漢字"
private lateinit var wrongPassphrase: String
@Before fun setup() {
check(directory.mkdirs())
val image = Bitmap.createBitmap(16, 16, Bitmap.Config.ARGB_8888)
val jpeg = try {
image.eraseColor(Color.rgb(220, 30, 40))
ByteArrayOutputStream().use { output ->
check(image.compress(Bitmap.CompressFormat.JPEG, 100, output))
output.toByteArray()
}
} finally {
image.recycle()
}
val encrypted = encryptTestJpeg(jpeg, passphrase)
encryptedFile.writeBytes(encrypted)
// CBC has no authentication; choose a wrong key that actually fails padding.
wrongPassphrase = (0..100).asSequence().map { "wrong-$it" }.first { candidate ->
try {
decryptEncryptedImage(encrypted, candidate).fill(0)
false
} catch (_: IncorrectPassphraseException) {
true
}
}
store.setPassphrase(passphrase)
}
@After fun cleanup() {
directory.deleteRecursively()
}
@Test fun rendersDecryptedJpegInStaticAndLivePaths() {
val rendered = runBlocking { renderer.render(wallpaper, ScreenType.HOME, ScheduleSettings()) }
assertNotNull(rendered)
checkNotNull(rendered)
try {
val screen = getDeviceScreenSize(context)
assertEquals(screen.width, rendered.width)
assertEquals(screen.height, rendered.height)
assertRed(rendered)
} finally {
rendered.recycle()
}
val loaded = loader.load(16, 16)
assertNotNull(loaded)
checkNotNull(loaded)
try {
assertEquals(16, loaded.width)
assertEquals(16, loaded.height)
assertRed(loaded)
} finally {
loaded.recycle()
}
}
@Test fun wrongOrMissingPassphraseFailsBothPaths() {
store.setPassphrase(wrongPassphrase)
assertThrows(IncorrectPassphraseException::class.java) {
runBlocking { renderer.render(wallpaper, ScreenType.HOME, ScheduleSettings()) }
}
assertNull(loader.load(16, 16))
store.clearPassphrase()
assertThrows(MissingPassphraseException::class.java) {
runBlocking { renderer.render(wallpaper, ScreenType.HOME, ScheduleSettings()) }
}
assertNull(loader.load(16, 16))
}
private fun assertRed(bitmap: Bitmap) {
val pixel = bitmap.getPixel(bitmap.width / 2, bitmap.height / 2)
assertTrue(Color.red(pixel) > 180)
assertTrue(Color.green(pixel) < 70)
assertTrue(Color.blue(pixel) < 80)
}
}
internal fun encryptTestJpeg(jpeg: ByteArray, passphrase: String): ByteArray {
val salt = byteArrayOf(0, 1, 2, 3, 4, 5, 6, 7)
val spec = PBEKeySpec(passphrase.toCharArray(), salt, 10_000, 384)
val material = try {
SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).encoded
} finally {
spec.clearPassword()
}
return try {
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(material, 0, 32, "AES"), IvParameterSpec(material, 32, 16))
"Salted__".toByteArray(Charsets.US_ASCII) + salt + cipher.doFinal(jpeg)
} finally {
material.fill(0)
}
}
@@ -92,8 +92,9 @@ class AlbumUiInstrumentedTest {
var attempts = 0
compose.setContent {
PaperizeTheme(false, false) {
LibraryScreen(emptyList(), {}, { name ->
LibraryScreen(emptyList(), {}, { name, encrypted ->
assertEquals("Mountains", name)
assertTrue(encrypted)
attempts++
if (attempts == 1) pending.await() else null
})
@@ -101,6 +102,7 @@ class AlbumUiInstrumentedTest {
}
compose.onNodeWithContentDescription(context.getString(R.string.add_album)).performClick()
compose.onNodeWithText(context.getString(R.string.album_name)).performTextInput("Mountains")
compose.onNodeWithText(context.getString(R.string.encrypted_album)).performClick()
compose.onNodeWithText(context.getString(R.string.save)).performClick().assertIsNotEnabled()
compose.runOnIdle { pending.complete(R.string.album_create_failed) }
compose.onNodeWithText(context.getString(R.string.album_create_failed)).assertIsDisplayed()
@@ -0,0 +1,94 @@
package com.anthonyla.paperize.presentation
import android.content.ContextWrapper
import android.graphics.Bitmap
import android.net.Uri
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.test.junit4.v2.createComposeRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import coil3.request.CachePolicy
import coil3.request.ImageRequest
import com.anthonyla.paperize.data.source.EncryptedImageStore
import com.anthonyla.paperize.data.source.encryptTestJpeg
import com.anthonyla.paperize.presentation.common.components.encryptedPreviewImageRequest
import java.io.ByteArrayOutputStream
import java.io.File
import java.util.UUID
import java.util.concurrent.atomic.AtomicReference
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class EncryptedPreviewInstrumentedTest {
@get:Rule val compose = createComposeRule()
private val instrumentation = InstrumentationRegistry.getInstrumentation()
private val directory = File(instrumentation.targetContext.cacheDir, "encrypted-preview-${UUID.randomUUID()}")
private val context = object : ContextWrapper(instrumentation.targetContext) {
override fun getNoBackupFilesDir(): File = directory
}
private val image = File(directory, "image.jpg_enc")
private val store = EncryptedImageStore(context)
@Before fun setup() {
check(directory.mkdirs())
val bitmap = Bitmap.createBitmap(8, 8, Bitmap.Config.ARGB_8888)
val jpeg = try {
ByteArrayOutputStream().use { output ->
check(bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output))
output.toByteArray()
}
} finally {
bitmap.recycle()
}
image.writeBytes(encryptTestJpeg(jpeg, "test"))
store.setPassphrase("test")
}
@After fun cleanup() {
directory.deleteRecursively()
}
@Test fun disablingPreviewsDropsTheDecryptedRequestAndNeverCachesIt() {
val enabled = mutableStateOf(true)
val request = AtomicReference<ImageRequest?>()
compose.setContent {
CompositionLocalProvider(LocalContext provides context) {
val value = encryptedPreviewImageRequest(
Uri.fromFile(image).toString(), 32, 32, false, enabled.value, store
)
SideEffect { request.set(value) }
}
}
compose.waitUntil(20_000) { request.get() != null }
val decrypted = checkNotNull(request.get())
assertTrue(decrypted.data is Bitmap)
assertEquals(CachePolicy.DISABLED, decrypted.memoryCachePolicy)
assertEquals(CachePolicy.DISABLED, decrypted.diskCachePolicy)
compose.runOnIdle { enabled.value = false }
compose.waitUntil(20_000) { request.get() == null }
compose.runOnIdle { enabled.value = true }
compose.waitUntil(20_000) { request.get() != null }
}
@Test fun missingDocumentMetadataStillLoadsTheOriginalUri() {
val uri = Uri.parse("content://missing.provider/image")
val request = AtomicReference<ImageRequest?>()
compose.setContent {
CompositionLocalProvider(LocalContext provides context) {
val value = encryptedPreviewImageRequest(uri.toString(), 32, 32, false, false, store)
SideEffect { request.set(value) }
}
}
compose.waitUntil(20_000) { request.get() != null }
assertEquals(uri, checkNotNull(request.get()).data)
}
}
@@ -2,7 +2,7 @@ package com.anthonyla.paperize.core.constants
object Constants {
const val DATABASE_NAME = "paperize_database"
const val DATABASE_VERSION = 4
const val DATABASE_VERSION = 5
const val PREFERENCES_NAME = "paperize_preferences"
@@ -116,11 +116,12 @@ fun retrieveBitmap(
width: Int,
height: Int,
scaling: ScalingType = ScalingType.FIT,
preserveSourceOverflow: Boolean = false
preserveSourceOverflow: Boolean = false,
imageSource: ImageDecoder.Source? = null
): Bitmap? {
// ImageDecoder applies EXIF orientation and reports dimensions after it.
val bitmap = try {
val source = ImageDecoder.createSource(context.contentResolver, wallpaperUri)
val source = imageSource ?: ImageDecoder.createSource(context.contentResolver, wallpaperUri)
ImageDecoder.decodeBitmap(source) { decoder, info, _ ->
val (targetW, targetH) = calculateDecodeSize(
info.size.width, info.size.height, width, height, scaling
@@ -4,7 +4,7 @@ import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
/** Versions 1–3 used the same library tables, with extra crop columns in versions 2–3. */
val LIBRARY_MIGRATIONS: Array<Migration> = (1..3).map { version ->
val LIBRARY_MIGRATIONS: Array<Migration> = (1..3).map<Int, Migration> { version ->
object : Migration(version, 4) {
override fun migrate(db: SupportSQLiteDatabase) {
// Rebuilding the parent table would cascade-delete these rows; preserve them first.
@@ -39,4 +39,8 @@ val LIBRARY_MIGRATIONS: Array<Migration> = (1..3).map { version ->
}
}
}
}.toTypedArray()
}.toTypedArray() + object : Migration(4, 5) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE `albums` ADD COLUMN `isEncrypted` INTEGER NOT NULL DEFAULT 0")
}
}
@@ -1,6 +1,7 @@
package com.anthonyla.paperize.data.database.entities
import androidx.room.Entity
import androidx.room.ColumnInfo
import androidx.room.PrimaryKey
@Entity(tableName = "albums")
@@ -10,5 +11,6 @@ data class AlbumEntity(
val name: String,
val coverUri: String?,
val createdAt: Long = System.currentTimeMillis(),
val modifiedAt: Long = System.currentTimeMillis()
val modifiedAt: Long = System.currentTimeMillis(),
@ColumnInfo(defaultValue = "0") val isEncrypted: Boolean = false
)
@@ -18,7 +18,8 @@ fun AlbumEntity.toDomainModel(
wallpapers = wallpapers,
folders = folders,
createdAt = createdAt,
modifiedAt = modifiedAt
modifiedAt = modifiedAt,
isEncrypted = isEncrypted
)
fun Album.toEntity(): AlbumEntity = AlbumEntity(
@@ -26,7 +27,8 @@ fun Album.toEntity(): AlbumEntity = AlbumEntity(
name = name,
coverUri = coverUri,
createdAt = createdAt,
modifiedAt = modifiedAt
modifiedAt = modifiedAt,
isEncrypted = isEncrypted
)
fun AlbumWithDetails.toDomainModel(): Album {
@@ -35,12 +35,15 @@ class AlbumRepositoryImpl @Inject constructor(
override fun getAlbumById(albumId: String): Flow<Album?> =
albumDao.getAlbumWithDetails(albumId).map { it?.toDomainModel() }
override suspend fun getAlbumEncryption(albumId: String): Boolean? =
albumDao.getAlbumById(albumId)?.isEncrypted
override fun getFolderById(folderId: String): Flow<Folder?> =
folderDao.getFolderWithWallpapers(folderId).map { it?.toDomainModel() }
override suspend fun createAlbum(name: String, coverUri: String?): Album {
override suspend fun createAlbum(name: String, coverUri: String?, isEncrypted: Boolean): Album {
val now = System.currentTimeMillis()
val album = Album(id = generateId(), name = name, coverUri = coverUri, createdAt = now, modifiedAt = now)
val album = Album(id = generateId(), name = name, coverUri = coverUri, createdAt = now, modifiedAt = now, isEncrypted = isEncrypted)
albumDao.insertAlbum(album.toEntity())
return album
}
@@ -31,6 +31,7 @@ private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
private val DARK_MODE = booleanPreferencesKey("dark_mode")
private val DYNAMIC_THEMING = booleanPreferencesKey("dynamic_theming")
private val ANIMATE = booleanPreferencesKey("animate")
private val ENCRYPTED_PREVIEWS = booleanPreferencesKey("encrypted_previews")
private val FIRST_LAUNCH = booleanPreferencesKey("first_launch")
private val WALLPAPER_MODE = stringPreferencesKey("wallpaper_mode")
private val ENABLE_CHANGER = booleanPreferencesKey("enable_changer")
@@ -84,7 +85,8 @@ class SettingsRepositoryImpl @Inject constructor(
darkMode = prefs[DARK_MODE],
dynamicTheming = prefs[DYNAMIC_THEMING] ?: defaults.dynamicTheming,
animate = prefs[ANIMATE] ?: defaults.animate,
firstLaunch = prefs[FIRST_LAUNCH] ?: defaults.firstLaunch
firstLaunch = prefs[FIRST_LAUNCH] ?: defaults.firstLaunch,
encryptedPreviews = prefs[ENCRYPTED_PREVIEWS] ?: defaults.encryptedPreviews
)
}
@@ -173,6 +175,10 @@ class SettingsRepositoryImpl @Inject constructor(
dataStore.edit { it[ANIMATE] = enabled }
}
override suspend fun updateEncryptedPreviews(enabled: Boolean) {
dataStore.edit { it[ENCRYPTED_PREVIEWS] = enabled }
}
override suspend fun completeFirstLaunch() {
dataStore.edit { it[FIRST_LAUNCH] = false }
}
@@ -10,11 +10,11 @@ import android.provider.DocumentsContract
import android.provider.OpenableColumns
import androidx.core.net.toUri
import androidx.documentfile.provider.DocumentFile
import com.anthonyla.paperize.core.constants.Constants
import com.anthonyla.paperize.core.runCatchingCancellable
import com.anthonyla.paperize.domain.source.DocumentSource
import com.anthonyla.paperize.domain.source.SourceFolder
import com.anthonyla.paperize.domain.source.SourceImage
import com.anthonyla.paperize.domain.source.isSupportedSourceName
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.currentCoroutineContext
@@ -37,11 +37,11 @@ class AndroidDocumentSource @Inject constructor(
SourceImage(uri, document?.name ?: uri.substringAfterLast('/'), document?.lastModified() ?: 0L)
}
override suspend fun readFolder(uri: String, onProgress: (Int) -> Unit): SourceFolder = withContext(Dispatchers.IO) {
override suspend fun readFolder(uri: String, isEncrypted: Boolean, onProgress: (Int) -> Unit): SourceFolder = withContext(Dispatchers.IO) {
val tree = uri.toUri()
SourceFolder(
DocumentFile.fromTreeUri(context, tree)?.name ?: uri.substringAfterLast('/'),
tree.scanFolderImages(context, onProgress)
tree.scanFolderImages(context, isEncrypted, onProgress)
)
}
@@ -80,7 +80,7 @@ private fun Cursor.requireComplete() {
* Rejects incomplete provider results and cancels in-flight queries with the caller.
* [onProgress] reports every [PROGRESS_REPORT_INTERVAL] discoveries and on completion.
*/
internal suspend fun Uri.scanFolderImages(context: Context, onProgress: (found: Int) -> Unit = {}): List<SourceImage> {
internal suspend fun Uri.scanFolderImages(context: Context, isEncrypted: Boolean, onProgress: (found: Int) -> Unit = {}): List<SourceImage> {
val rootDocumentId = DocumentsContract.getTreeDocumentId(this)
val projection = arrayOf(
@@ -130,8 +130,7 @@ internal suspend fun Uri.scanFolderImages(context: Context, onProgress: (found:
if (cursor.getString(mimeColumn) == DocumentsContract.Document.MIME_TYPE_DIR) {
pendingDirs.addLast(documentId)
} else {
val extension = name.substringAfterLast('.', "").lowercase()
if (extension in Constants.SUPPORTED_IMAGE_EXTENSIONS) {
if (isSupportedSourceName(name, isEncrypted)) {
results.add(
SourceImage(
uri = DocumentsContract.buildDocumentUriUsingTree(this, documentId).toString(),
@@ -2,6 +2,8 @@ package com.anthonyla.paperize.data.source
import android.content.Context
import android.graphics.Bitmap
import android.graphics.ImageDecoder
import android.util.Log
import androidx.core.net.toUri
import com.anthonyla.paperize.core.ScreenType
import com.anthonyla.paperize.core.util.adaptiveBrightnessAdjustment
@@ -14,11 +16,13 @@ import com.anthonyla.paperize.domain.model.Wallpaper
import com.anthonyla.paperize.domain.source.WallpaperRenderer
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import java.nio.ByteBuffer
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
class AndroidWallpaperRenderer @Inject constructor(
@param:ApplicationContext private val context: Context
@param:ApplicationContext private val context: Context,
private val encryptedImages: EncryptedImageStore
) : WallpaperRenderer {
override suspend fun render(wallpaper: Wallpaper, screen: ScreenType, settings: ScheduleSettings): Bitmap? {
currentCoroutineContext().ensureActive()
@@ -33,8 +37,21 @@ class AndroidWallpaperRenderer @Inject constructor(
ScreenType.LIVE -> settings.liveScalingType
}
val size = getDeviceScreenSize(context)
var bitmap = retrieveBitmap(context, wallpaper.uri.toUri(), size.width, size.height, scaling,
usesLauncherManagedScrolling(screen, scaling, settings.homeScrollingEnabled)) ?: return null
val decrypted = if (wallpaper.fileName.endsWith(".jpg_enc", ignoreCase = true)) {
try {
encryptedImages.decrypt(wallpaper.uri.toUri())
} catch (e: Exception) {
Log.e("AndroidWallpaperRenderer", "Could not decrypt wallpaper", e)
throw e
}
} else null
var bitmap = try {
retrieveBitmap(context, wallpaper.uri.toUri(), size.width, size.height, scaling,
usesLauncherManagedScrolling(screen, scaling, settings.homeScrollingEnabled),
decrypted?.let { ImageDecoder.createSource(ByteBuffer.wrap(it)) })
} finally {
decrypted?.fill(0)
} ?: return null
try {
val processed = processBitmap(
source = bitmap,
@@ -0,0 +1,155 @@
package com.anthonyla.paperize.data.source
import android.content.Context
import android.net.Uri
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.AtomicFile
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import java.io.File
import java.io.IOException
import java.security.KeyStore
import javax.crypto.BadPaddingException
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.PBEKeySpec
import javax.crypto.spec.SecretKeySpec
import javax.inject.Inject
import javax.inject.Singleton
class MissingPassphraseException : IllegalStateException("No encryption passphrase is configured")
class PassphraseStorageException(cause: Throwable) : IllegalStateException("Cannot access the stored passphrase", cause)
class InvalidEncryptedFileException : IOException("Invalid or truncated encrypted file")
class IncorrectPassphraseException : IOException("Incorrect passphrase or damaged encrypted file")
@Singleton
class EncryptedImageStore @Inject constructor(
@param:ApplicationContext private val context: Context
) {
private val passphraseFile = AtomicFile(File(context.noBackupFilesDir, "encrypted_image_passphrase"))
private val mutableRevision = MutableStateFlow(0)
val revision: StateFlow<Int> = mutableRevision.asStateFlow()
@Synchronized
fun setPassphrase(passphrase: String) {
try {
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, key(create = true))
val plaintext = passphrase.toByteArray(Charsets.UTF_8)
val encrypted = try {
cipher.doFinal(plaintext)
} finally {
plaintext.fill(0)
}
val output = passphraseFile.startWrite()
try {
output.write(cipher.iv)
output.write(encrypted)
passphraseFile.finishWrite(output)
mutableRevision.value += 1
} catch (e: Exception) {
passphraseFile.failWrite(output)
throw e
}
} catch (e: Exception) {
throw PassphraseStorageException(e)
}
}
@Synchronized
fun clearPassphrase() {
passphraseFile.delete()
check(!passphraseFile.baseFile.exists()) { "Cannot clear the stored passphrase" }
mutableRevision.value += 1
}
@Synchronized
fun hasPassphrase(): Boolean = passphraseFile.baseFile.exists()
fun decrypt(uri: Uri): ByteArray {
val passphrase = synchronized(this) { readPassphrase() }
val bytes = context.contentResolver.openInputStream(uri)?.use { it.readBytes() }
?: throw IOException("Cannot open encrypted file")
return decryptEncryptedImage(bytes, passphrase)
}
private fun readPassphrase(): String {
if (!hasPassphrase()) throw MissingPassphraseException()
try {
val stored = passphraseFile.readFully()
require(stored.size >= IV_SIZE + TAG_SIZE)
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.DECRYPT_MODE, key(create = false), GCMParameterSpec(128, stored, 0, IV_SIZE))
val plaintext = cipher.doFinal(stored, IV_SIZE, stored.size - IV_SIZE)
return try {
plaintext.toString(Charsets.UTF_8)
} finally {
plaintext.fill(0)
}
} catch (e: Exception) {
throw PassphraseStorageException(e)
}
}
private fun key(create: Boolean): SecretKey {
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
val existing = keyStore.getKey(KEY_ALIAS, null) as? SecretKey
if (existing != null) return existing
check(create) { "Keystore key is missing" }
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").run {
init(
KeyGenParameterSpec.Builder(
KEY_ALIAS,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.build()
)
generateKey()
}
}
private companion object {
const val KEY_ALIAS = "paperize_encrypted_image_passphrase"
const val IV_SIZE = 12
const val TAG_SIZE = 16
}
}
internal fun decryptEncryptedImage(encrypted: ByteArray, passphrase: String): ByteArray {
val headerSize = 16
if (encrypted.size < headerSize + 16 ||
(encrypted.size - headerSize) % 16 != 0 ||
!encrypted.copyOfRange(0, 8).contentEquals("Salted__".toByteArray(Charsets.US_ASCII))
) throw InvalidEncryptedFileException()
val spec = PBEKeySpec(passphrase.toCharArray(), encrypted.copyOfRange(8, headerSize), 10_000, 384)
val material = try {
SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).encoded
} finally {
spec.clearPassword()
}
try {
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(
Cipher.DECRYPT_MODE,
SecretKeySpec(material, 0, 32, "AES"),
IvParameterSpec(material, 32, 16)
)
return try {
cipher.doFinal(encrypted, headerSize, encrypted.size - headerSize)
} catch (_: BadPaddingException) {
throw IncorrectPassphraseException()
}
} finally {
material.fill(0)
}
}
@@ -7,5 +7,6 @@ data class Album(
val wallpapers: List<Wallpaper> = emptyList(),
val folders: List<Folder> = emptyList(),
val createdAt: Long = System.currentTimeMillis(),
val modifiedAt: Long = System.currentTimeMillis()
val modifiedAt: Long = System.currentTimeMillis(),
val isEncrypted: Boolean = false
)
@@ -4,5 +4,6 @@ data class AppSettings(
val darkMode: Boolean? = null, // null = system default, true = dark, false = light
val dynamicTheming: Boolean = false,
val animate: Boolean = true,
val firstLaunch: Boolean = true
val firstLaunch: Boolean = true,
val encryptedPreviews: Boolean = false
)
@@ -11,9 +11,11 @@ interface AlbumRepository {
fun getAlbumById(albumId: String): Flow<Album?>
suspend fun getAlbumEncryption(albumId: String): Boolean?
fun getFolderById(folderId: String): Flow<Folder?>
suspend fun createAlbum(name: String, coverUri: String? = null): Album
suspend fun createAlbum(name: String, coverUri: String? = null, isEncrypted: Boolean = false): Album
suspend fun deleteAlbum(albumId: String)
@@ -42,6 +42,7 @@ interface SettingsRepository {
suspend fun updateDarkMode(enabled: Boolean)
suspend fun updateDynamicTheming(enabled: Boolean)
suspend fun updateAnimate(enabled: Boolean)
suspend fun updateEncryptedPreviews(enabled: Boolean)
suspend fun completeFirstLaunch()
suspend fun updateEnableChanger(enabled: Boolean)
@@ -1,11 +1,17 @@
package com.anthonyla.paperize.domain.source
import com.anthonyla.paperize.core.constants.Constants
data class SourceImage(val uri: String, val name: String, val modifiedAt: Long)
data class SourceFolder(val name: String, val images: List<SourceImage>)
fun isSupportedSourceName(name: String, isEncrypted: Boolean): Boolean =
if (isEncrypted) name.endsWith(".jpg_enc", ignoreCase = true)
else name.substringAfterLast('.', "").lowercase() in Constants.SUPPORTED_IMAGE_EXTENSIONS
interface DocumentSource {
suspend fun retainReadPermission(uri: String)
suspend fun readImage(uri: String): SourceImage
suspend fun readFolder(uri: String, onProgress: (Int) -> Unit = {}): SourceFolder
suspend fun readFolder(uri: String, isEncrypted: Boolean, onProgress: (Int) -> Unit = {}): SourceFolder
suspend fun isMissing(uri: String, isTree: Boolean = false): Boolean
}
@@ -8,9 +8,9 @@ class CreateAlbumUseCase @Inject constructor(
private val albumRepository: AlbumRepository
) {
/** Returns false, creating nothing, when an album already has this name ignoring case. */
suspend operator fun invoke(name: String): Boolean {
suspend operator fun invoke(name: String, isEncrypted: Boolean = false): Boolean {
if (albumRepository.getAlbumSummaries().first().any { it.name.equals(name, ignoreCase = true) }) return false
albumRepository.createAlbum(name)
albumRepository.createAlbum(name, isEncrypted = isEncrypted)
return true
}
}
@@ -6,6 +6,7 @@ import com.anthonyla.paperize.domain.model.Wallpaper
import com.anthonyla.paperize.domain.repository.AlbumRepository
import com.anthonyla.paperize.domain.source.DocumentSource
import com.anthonyla.paperize.domain.source.SourceImage
import com.anthonyla.paperize.domain.source.isSupportedSourceName
import kotlinx.coroutines.flow.first
import javax.inject.Inject
@@ -14,9 +15,11 @@ class ImportWallpapersUseCase @Inject constructor(
private val albumRepository: AlbumRepository
) {
suspend fun addImages(albumId: String, uris: List<String>, onSaving: (Int, Int) -> Unit): Boolean {
val images = uris.distinct().map { uri ->
val isEncrypted = checkNotNull(albumRepository.getAlbumEncryption(albumId))
val images = uris.distinct().mapNotNull { uri ->
documents.retainReadPermission(uri)
documents.readImage(uri).toWallpaper(albumId)
val image = documents.readImage(uri)
if (!isEncrypted || isSupportedSourceName(image.name, true)) image.toWallpaper(albumId) else null
}
return albumRepository.addWallpapersToAlbum(albumId, images, onSaving) > 0
}
@@ -29,8 +32,9 @@ class ImportWallpapersUseCase @Inject constructor(
): Boolean {
documents.retainReadPermission(uri)
// Avoid rescanning an existing folder; insertion still checks duplicates atomically.
if (albumRepository.getAlbumById(albumId).first()?.folders.orEmpty().any { it.uri == uri }) return false
val source = documents.readFolder(uri, onScanning)
val album = checkNotNull(albumRepository.getAlbumById(albumId).first())
if (album.folders.any { it.uri == uri }) return false
val source = documents.readFolder(uri, album.isEncrypted, onScanning)
val folderId = generateId()
val folder = Folder(
id = folderId, albumId = albumId, uri = uri, name = source.name,
@@ -12,7 +12,8 @@ class RefreshFolderUseCase @Inject constructor(
/** Returns the number of new images. */
suspend operator fun invoke(folderId: String): Int {
val folder = albumRepository.getFolderById(folderId).first() ?: return 0
val source = documents.readFolder(folder.uri)
val isEncrypted = albumRepository.getAlbumEncryption(folder.albumId) ?: return 0
val source = documents.readFolder(folder.uri, isEncrypted)
return albumRepository.syncFolderWallpapers(
folder.albumId, folderId, source.images.map { it.toWallpaper(folder.albumId, folderId) }
)
@@ -13,11 +13,8 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import coil3.compose.AsyncImagePainter
import coil3.compose.rememberAsyncImagePainter
import coil3.request.ImageRequest
import coil3.size.Size
import com.anthonyla.paperize.domain.model.AlbumSummary
/** The album's cover image, or a placeholder icon until one loads. */
@@ -30,10 +27,7 @@ fun AlbumCover(
placeholderModifier: Modifier = Modifier
) {
val cover = rememberAsyncImagePainter(
ImageRequest.Builder(LocalContext.current)
.data(album.coverUri)
.size(Size(thumbnailSize, thumbnailSize))
.build(),
encryptedAwareImageRequest(album.coverUri, thumbnailSize, thumbnailSize),
contentScale = ContentScale.Crop
)
val coverState by cover.state.collectAsState()
@@ -1,23 +1,27 @@
package com.anthonyla.paperize.presentation.common.components
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.selection.toggleable
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.Alignment
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import com.anthonyla.paperize.R
import com.anthonyla.paperize.presentation.common.theme.AppSpacing
@Composable
fun AddAlbumDialog(
onDismiss: () -> Unit,
onConfirm: (String) -> Unit,
onConfirm: (String, Boolean) -> Unit,
errorMessage: String?,
isSaving: Boolean
) {
var albumName by rememberSaveable { mutableStateOf("") }
var isEncrypted by rememberSaveable { mutableStateOf(false) }
AlertDialog(
onDismissRequest = { if (!isSaving) onDismiss() },
@@ -38,11 +42,24 @@ fun AddAlbumDialog(
} else null,
modifier = Modifier.fillMaxWidth()
)
Row(
modifier = Modifier.fillMaxWidth().toggleable(
value = isEncrypted,
enabled = !isSaving,
role = Role.Checkbox,
onValueChange = { isEncrypted = it }
),
verticalAlignment = Alignment.CenterVertically
) {
Checkbox(checked = isEncrypted, onCheckedChange = null, enabled = !isSaving)
Text(stringResource(R.string.encrypted_album))
}
Text(stringResource(R.string.encrypted_album_hint), style = MaterialTheme.typography.bodySmall)
}
},
confirmButton = {
TextButton(
onClick = { onConfirm(albumName.trim()) },
onClick = { onConfirm(albumName.trim(), isEncrypted) },
enabled = !isSaving && albumName.isNotBlank()
) {
Text(stringResource(R.string.save))
@@ -0,0 +1,138 @@
package com.anthonyla.paperize.presentation.common.components
import android.graphics.ImageDecoder
import android.provider.OpenableColumns
import android.util.Log
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.core.net.toUri
import androidx.compose.ui.platform.LocalContext
import coil3.request.CachePolicy
import coil3.request.ImageRequest
import coil3.request.crossfade
import coil3.size.Size
import com.anthonyla.paperize.data.source.EncryptedImageStore
import com.anthonyla.paperize.domain.repository.SettingsRepository
import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.android.EntryPointAccessors
import dagger.hilt.components.SingletonComponent
import java.nio.ByteBuffer
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@EntryPoint
@InstallIn(SingletonComponent::class)
interface EncryptedPreviewEntryPoint {
fun encryptedImages(): EncryptedImageStore
fun settings(): SettingsRepository
}
private data class PreviewImage(val data: Any, val encrypted: Boolean)
@Composable
fun encryptedAwareImageRequest(
uri: String?,
width: Int? = null,
height: Int? = null,
animate: Boolean = false
): ImageRequest? {
val context = LocalContext.current
val dependencies = remember(context) {
EntryPointAccessors.fromApplication(context.applicationContext, EncryptedPreviewEntryPoint::class.java)
}
val settings = remember(dependencies) { dependencies.settings().getAppSettingsFlow() }
val appSettings by settings.collectAsState(initial = null)
val enabled = appSettings?.encryptedPreviews == true
val store = remember(dependencies) { dependencies.encryptedImages() }
return encryptedPreviewImageRequest(uri, width, height, animate, enabled, store)
}
@Composable
internal fun encryptedPreviewImageRequest(
uri: String?,
width: Int?,
height: Int?,
animate: Boolean,
enabled: Boolean,
store: EncryptedImageStore
): ImageRequest? {
val context = LocalContext.current
val revision by store.revision.collectAsState()
return key(uri, enabled, revision, width, height) {
val image by produceState<PreviewImage?>(initialValue = null) {
if (uri != null) {
value = withContext(Dispatchers.IO) {
try {
val parsed = uri.toUri()
val name = if (parsed.scheme == "file") parsed.lastPathSegment else {
try {
context.contentResolver.query(
parsed, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null
)?.use { cursor ->
if (cursor.moveToFirst()) cursor.getString(0) else null
}
} catch (e: Exception) {
Log.w("EncryptedPreview", "Could not read image name; loading the original URI", e)
null
}
}
if (name == null) {
Log.w("EncryptedPreview", "Image name unavailable; loading the original URI")
}
val isEncrypted = (name ?: parsed.lastPathSegment)?.endsWith(".jpg_enc", ignoreCase = true) == true
if (!isEncrypted) {
PreviewImage(parsed, false)
} else if (!enabled) {
null
} else {
val bytes = store.decrypt(parsed)
try {
val bitmap = ImageDecoder.decodeBitmap(ImageDecoder.createSource(ByteBuffer.wrap(bytes))) {
decoder, info, _ ->
val maxWidth = width ?: 2048
val maxHeight = height ?: 2048
val scale = minOf(1f, maxWidth.toFloat() / info.size.width, maxHeight.toFloat() / info.size.height)
decoder.setTargetSize(
(info.size.width * scale).toInt().coerceAtLeast(1),
(info.size.height * scale).toInt().coerceAtLeast(1)
)
decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
}
PreviewImage(bitmap, true)
} finally {
bytes.fill(0)
}
}
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.w("EncryptedPreview", "Could not load image preview", e)
null
}
}
}
}
remember(context, image, width, height, animate) {
image?.let {
ImageRequest.Builder(context)
.data(it.data)
.crossfade(animate && !it.encrypted)
.apply {
if (width != null && height != null) size(Size(width, height))
if (it.encrypted) {
memoryCachePolicy(CachePolicy.DISABLED)
diskCachePolicy(CachePolicy.DISABLED)
}
}
.build()
}
}
}
}
@@ -4,15 +4,11 @@ import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.semantics
import androidx.core.net.toUri
import coil3.compose.AsyncImage
import coil3.request.ImageRequest
import coil3.size.Size
import com.anthonyla.paperize.core.constants.Constants
@Composable
@@ -36,10 +32,9 @@ fun WallpaperItem(
}
) {
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(wallpaperUri.toUri())
.size(Size(Constants.GRID_THUMBNAIL_WIDTH, Constants.GRID_THUMBNAIL_HEIGHT))
.build(),
model = encryptedAwareImageRequest(
wallpaperUri, Constants.GRID_THUMBNAIL_WIDTH, Constants.GRID_THUMBNAIL_HEIGHT
),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize(),
@@ -121,7 +121,7 @@ fun AlbumViewScreen(
if (!isSelectionMode && totalItemsCount > 0) {
AddAlbumAnimatedFab(
isLoading = importProgress !is ImportProgress.Idle,
onImageClick = { imagePickerLauncher.launch(arrayOf("image/*")) },
onImageClick = { imagePickerLauncher.launch(arrayOf(if (album?.isEncrypted == true) "*/*" else "image/*")) },
onFolderClick = { folderPickerLauncher.launch(null) }
)
}
@@ -133,7 +133,7 @@ fun AlbumViewScreen(
hint = stringResource(R.string.album_empty_hint),
modifier = modifier.padding(paddingValues)
) {
FilledTonalButton(onClick = { imagePickerLauncher.launch(arrayOf("image/*")) }) {
FilledTonalButton(onClick = { imagePickerLauncher.launch(arrayOf(if (album?.isEncrypted == true) "*/*" else "image/*")) }) {
Text(stringResource(R.string.add_wallpapers))
}
TextButton(onClick = { folderPickerLauncher.launch(null) }) {
@@ -76,7 +76,7 @@ class HomeViewModel @Inject constructor(
}
/** Creates the album and returns null, or returns the string resource of the error to show. */
suspend fun createAlbum(name: String): Int? = runCatchingCancellable { createAlbumUseCase(name) }.fold(
suspend fun createAlbum(name: String, isEncrypted: Boolean = false): Int? = runCatchingCancellable { createAlbumUseCase(name, isEncrypted) }.fold(
onSuccess = { created -> if (created) null else R.string.album_name_exists_error },
onFailure = { R.string.album_create_failed }
)
@@ -38,7 +38,7 @@ import kotlinx.coroutines.launch
fun LibraryScreen(
albums: List<AlbumSummary>,
onViewAlbum: (String) -> Unit,
onCreateAlbum: suspend (String) -> Int?,
onCreateAlbum: suspend (String, Boolean) -> Int?,
modifier: Modifier = Modifier
) {
var showAddAlbumDialog by rememberSaveable { mutableStateOf(false) }
@@ -95,12 +95,12 @@ fun LibraryScreen(
showAddAlbumDialog = false
albumNameError = null
},
onConfirm = { name ->
onConfirm = { name, isEncrypted ->
isSaving = true
albumNameError = null
scope.launch {
try {
albumNameError = onCreateAlbum(name)
albumNameError = onCreateAlbum(name, isEncrypted)
if (albumNameError == null) showAddAlbumDialog = false
} finally {
isSaving = false
@@ -4,6 +4,7 @@ import androidx.annotation.StringRes
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.BatteryAlert
@@ -14,6 +15,8 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.Lifecycle
@@ -41,9 +44,12 @@ fun SettingsScreen(
val appSettings by viewModel.appSettings.collectAsStateWithLifecycle()
val isResetting by viewModel.isResetting.collectAsStateWithLifecycle()
val resetFailed by viewModel.resetFailed.collectAsStateWithLifecycle()
val passphraseFailed by viewModel.passphraseFailed.collectAsStateWithLifecycle()
val wallpaperMode by viewModel.wallpaperMode.collectAsStateWithLifecycle()
var showResetDialog by remember { mutableStateOf(false) }
var pendingMode by remember { mutableStateOf<WallpaperMode?>(null) }
var showPassphraseDialog by remember { mutableStateOf(false) }
var passphrase by remember { mutableStateOf("") }
val context = LocalContext.current
var isIgnoringBatteryOptimizations by remember {
@@ -122,6 +128,21 @@ fun SettingsScreen(
)
}
SettingsGroup(title = stringResource(R.string.encrypted_albums)) {
SettingsRow(onClick = { showPassphraseDialog = true }) {
SettingText(
title = stringResource(R.string.encrypted_passphrase),
description = stringResource(R.string.encrypted_passphrase_description)
)
}
SettingSwitchItem(
title = stringResource(R.string.encrypted_previews),
description = stringResource(R.string.encrypted_previews_description),
checked = appSettings?.encryptedPreviews ?: false,
onCheckedChange = viewModel::updateEncryptedPreviews
)
}
SettingsGroup(title = stringResource(R.string.reliability)) {
SettingsRow(verticalArrangement = Arrangement.spacedBy(AppSpacing.small)) {
Row(
@@ -224,6 +245,49 @@ fun SettingsScreen(
confirmColor = MaterialTheme.colorScheme.error
)
}
if (showPassphraseDialog) {
AlertDialog(
onDismissRequest = {
showPassphraseDialog = false
passphrase = ""
viewModel.dismissPassphraseError()
},
title = { Text(stringResource(R.string.encrypted_passphrase)) },
text = {
OutlinedTextField(
value = passphrase,
onValueChange = { passphrase = it },
label = { Text(stringResource(R.string.encrypted_passphrase)) },
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
singleLine = true,
isError = passphraseFailed,
supportingText = if (passphraseFailed) {
{ Text(stringResource(R.string.encrypted_passphrase_save_failed)) }
} else null
)
},
confirmButton = {
TextButton(
enabled = passphrase.isNotEmpty(),
onClick = {
viewModel.setPassphrase(passphrase) {
passphrase = ""
showPassphraseDialog = false
}
}
) { Text(stringResource(R.string.save)) }
},
dismissButton = {
TextButton(onClick = {
showPassphraseDialog = false
passphrase = ""
viewModel.dismissPassphraseError()
}) { Text(stringResource(R.string.cancel)) }
}
)
}
}
}
@@ -5,6 +5,7 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.anthonyla.paperize.core.WallpaperMode
import com.anthonyla.paperize.core.runCatchingCancellable
import com.anthonyla.paperize.data.source.EncryptedImageStore
import com.anthonyla.paperize.domain.model.AppSettings
import com.anthonyla.paperize.domain.repository.SettingsRepository
import com.anthonyla.paperize.presentation.common.launchBusy
@@ -22,7 +23,8 @@ import kotlinx.coroutines.launch
@HiltViewModel
class SettingsViewModel @Inject constructor(
private val settingsRepository: SettingsRepository,
private val coordinator: SettingsCoordinator
private val coordinator: SettingsCoordinator,
private val encryptedImages: EncryptedImageStore
) : ViewModel() {
// Eager so the first frame already knows whether to show onboarding.
@@ -36,6 +38,8 @@ class SettingsViewModel @Inject constructor(
val isResetting = _isResetting.asStateFlow()
private val _resetFailed = MutableStateFlow(false)
val resetFailed = _resetFailed.asStateFlow()
private val _passphraseFailed = MutableStateFlow(false)
val passphraseFailed = _passphraseFailed.asStateFlow()
fun updateDarkMode(enabled: Boolean) {
viewModelScope.launch { settingsRepository.updateDarkMode(enabled) }
@@ -49,6 +53,27 @@ class SettingsViewModel @Inject constructor(
viewModelScope.launch { settingsRepository.updateAnimate(enabled) }
}
fun updateEncryptedPreviews(enabled: Boolean) {
viewModelScope.launch { settingsRepository.updateEncryptedPreviews(enabled) }
}
fun setPassphrase(passphrase: String, onSuccess: () -> Unit) {
viewModelScope.launch {
runCatchingCancellable {
encryptedImages.setPassphrase(passphrase)
_passphraseFailed.value = false
onSuccess()
}.onFailure {
Log.e(TAG, "Could not save encryption passphrase", it)
_passphraseFailed.value = true
}
}
}
fun dismissPassphraseError() {
_passphraseFailed.value = false
}
fun completeFirstLaunch() {
viewModelScope.launch { settingsRepository.completeFirstLaunch() }
}
@@ -63,6 +88,7 @@ class SettingsViewModel @Inject constructor(
launchBusy(_isResetting) {
runCatchingCancellable {
coordinator.resetData(mode)
if (mode == null) encryptedImages.clearPassphrase()
onSuccess()
}.onFailure { e ->
Log.e(TAG, "Could not reset app data", e)
@@ -20,17 +20,14 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalWindowInfo
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import coil3.compose.AsyncImage
import coil3.request.ImageRequest
import coil3.request.crossfade
import coil3.size.Size
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.constants.Constants
import com.anthonyla.paperize.presentation.common.components.encryptedAwareImageRequest
import com.anthonyla.paperize.presentation.common.theme.AppSpacing
import kotlin.math.max
import kotlin.math.min
@@ -104,8 +101,6 @@ private fun WallpaperPreviewBox(
contentDescription: String,
animate: Boolean
) {
val context = LocalContext.current
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(AppSpacing.small)
@@ -120,11 +115,9 @@ private fun WallpaperPreviewBox(
.background(MaterialTheme.colorScheme.surfaceContainerHighest)
) {
AsyncImage(
model = ImageRequest.Builder(context)
.data(wallpaperUri)
.size(Size(Constants.PREVIEW_THUMBNAIL_WIDTH, Constants.PREVIEW_THUMBNAIL_HEIGHT))
.crossfade(animate)
.build(),
model = encryptedAwareImageRequest(
wallpaperUri, Constants.PREVIEW_THUMBNAIL_WIDTH, Constants.PREVIEW_THUMBNAIL_HEIGHT, animate
),
contentDescription = contentDescription,
contentScale = ContentScale.Crop,
modifier = Modifier.matchParentSize()
@@ -38,13 +38,13 @@ import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.core.net.toUri
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import coil3.compose.AsyncImage
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.ScreenType
import com.anthonyla.paperize.core.WallpaperMode
import com.anthonyla.paperize.presentation.common.components.encryptedAwareImageRequest
import com.anthonyla.paperize.presentation.common.theme.AppSpacing
import net.engawapg.lib.zoomable.rememberZoomState
import net.engawapg.lib.zoomable.zoomable
@@ -135,7 +135,7 @@ fun WallpaperViewScreen(
.zoomable(zoomState)
) {
AsyncImage(
model = viewModel.wallpaperUri.toUri(),
model = encryptedAwareImageRequest(viewModel.wallpaperUri),
contentDescription = viewModel.wallpaperName,
contentScale = ContentScale.Fit,
modifier = Modifier.fillMaxSize()
@@ -7,6 +7,7 @@ import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.res.Configuration
import android.graphics.BitmapFactory
import android.os.Build
import android.os.PowerManager
import android.util.Log
@@ -27,10 +28,12 @@ import com.anthonyla.paperize.domain.model.Wallpaper
import com.anthonyla.paperize.domain.model.usesVisibleLiveTimer
import com.anthonyla.paperize.domain.repository.SettingsRepository
import com.anthonyla.paperize.domain.usecase.ChangeWallpaperUseCase
import com.anthonyla.paperize.data.source.EncryptedImageStore
import com.anthonyla.paperize.service.LiveWallpaperReload
import com.anthonyla.paperize.service.livewallpaper.gl.GLWallpaperService
import com.anthonyla.paperize.service.livewallpaper.renderer.ContentUriImageLoader
import com.anthonyla.paperize.service.livewallpaper.renderer.EmptyImageLoader
import com.anthonyla.paperize.service.livewallpaper.renderer.EncryptedImageLoader
import com.anthonyla.paperize.service.livewallpaper.renderer.ImageLoader
import com.anthonyla.paperize.service.livewallpaper.renderer.PaperizeRenderController
import com.anthonyla.paperize.service.livewallpaper.renderer.PaperizeWallpaperRenderer
@@ -58,6 +61,7 @@ class PaperizeLiveWallpaperService : GLWallpaperService() {
@Inject lateinit var settingsRepository: SettingsRepository
@Inject lateinit var changeWallpaperUseCase: ChangeWallpaperUseCase
@Inject lateinit var liveWallpaperReload: LiveWallpaperReload
@Inject lateinit var encryptedImages: EncryptedImageStore
companion object {
private const val TAG = "PaperizeLiveWallpaper"
@@ -171,9 +175,9 @@ class PaperizeLiveWallpaperService : GLWallpaperService() {
val loader = withContext(Dispatchers.IO) {
changeWallpaperUseCase.dequeueReadable(albumId, ScreenType.LIVE, settings.shuffleEnabled) { candidate ->
val uri = candidate.uri.toUri()
if (uri.isReadable(contentResolver)) {
if (uri.isReadable(contentResolver) && isValidEncryptedImage(candidate)) {
currentWallpaper = candidate
ContentUriImageLoader(contentResolver, uri, settings.liveScalingType)
imageLoader(candidate, settings.liveScalingType)
} else {
null
}
@@ -229,11 +233,7 @@ class PaperizeLiveWallpaperService : GLWallpaperService() {
currentWallpaper?.let { wallpaper ->
Log.d(TAG, "Live scaling changed; reloading current wallpaper without advancing")
renderer.queueWallpaper(
ContentUriImageLoader(
contentResolver,
wallpaper.uri.toUri(),
scalingType
)
imageLoader(wallpaper, scalingType)
)
}
}
@@ -264,10 +264,35 @@ class PaperizeLiveWallpaperService : GLWallpaperService() {
// configuration changes while the wallpaper was hidden.
requestRender()
}
restartLiveIntervalTimer()
super.onVisibilityChanged(visible)
}
private fun imageLoader(wallpaper: Wallpaper, scalingType: ScalingType): ImageLoader =
if (wallpaper.fileName.endsWith(".jpg_enc", ignoreCase = true)) {
EncryptedImageLoader(encryptedImages, wallpaper.uri.toUri(), scalingType)
} else {
ContentUriImageLoader(contentResolver, wallpaper.uri.toUri(), scalingType)
}
private fun isValidEncryptedImage(wallpaper: Wallpaper): Boolean {
if (!wallpaper.fileName.endsWith(".jpg_enc", ignoreCase = true)) return true
return try {
val bytes = encryptedImages.decrypt(wallpaper.uri.toUri())
try {
val options = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
options.outWidth > 0 && options.outHeight > 0
} finally {
bytes.fill(0)
}
} catch (e: Exception) {
Log.e(TAG, "Could not decrypt live wallpaper", e)
false
}
}
override fun onOffsetsChanged(
xOffset: Float,
yOffset: Float,
@@ -7,6 +7,8 @@ import android.net.Uri
import android.util.Log
import com.anthonyla.paperize.core.ScalingType
import com.anthonyla.paperize.core.util.calculateDecodeSize
import com.anthonyla.paperize.data.source.EncryptedImageStore
import java.nio.ByteBuffer
sealed interface ImageLoader {
/** Decode on a worker thread. The caller owns the returned bitmap. */
@@ -40,3 +42,32 @@ class ContentUriImageLoader(
null
}
}
class EncryptedImageLoader(
private val encryptedImages: EncryptedImageStore,
private val uri: Uri,
private val scalingType: ScalingType = ScalingType.FILL
) : ImageLoader {
override fun load(targetWidth: Int, targetHeight: Int): Bitmap? {
return try {
val bytes = encryptedImages.decrypt(uri)
try {
ImageDecoder.decodeBitmap(ImageDecoder.createSource(ByteBuffer.wrap(bytes))) { decoder, info, _ ->
val (width, height) = calculateDecodeSize(
info.size.width, info.size.height, targetWidth, targetHeight, scalingType
)
decoder.setTargetSize(width, height)
decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
}
} finally {
bytes.fill(0)
}
} catch (e: Exception) {
Log.e("EncryptedImageLoader", "Failed to decode encrypted wallpaper", e)
null
} catch (e: OutOfMemoryError) {
Log.e("EncryptedImageLoader", "Out of memory decoding encrypted wallpaper", e)
null
}
}
}
+10 -1
View File
@@ -1,5 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Awaiting Crowdin translations. -->
<string name="encrypted_albums" tools:ignore="MissingTranslation">Encrypted albums</string>
<string name="encrypted_passphrase" tools:ignore="MissingTranslation">Encryption passphrase</string>
<string name="encrypted_passphrase_description" tools:ignore="MissingTranslation">Set the passphrase used by wallpaper_changer</string>
<string name="encrypted_passphrase_save_failed" tools:ignore="MissingTranslation">Could not save the passphrase</string>
<string name="encrypted_previews" tools:ignore="MissingTranslation">Show encrypted image previews</string>
<string name="encrypted_previews_description" tools:ignore="MissingTranslation">Decrypt previews in memory. Turning this off removes them from the app.</string>
<string name="encrypted_album" tools:ignore="MissingTranslation">Encrypted album</string>
<string name="encrypted_album_hint" tools:ignore="MissingTranslation">Only .jpg_enc files will be imported. This cannot be changed later.</string>
<string name="album_create_failed">Could not create the album. Please try again.</string>
<string name="app_name" translatable="false">Paperize</string>
<string name="continue_rotation_from_here">Continue rotation from here</string>
@@ -0,0 +1,48 @@
package com.anthonyla.paperize.data.source
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertThrows
import org.junit.Test
class EncryptedImageDecryptionTest {
private val encrypted = hex(
"53616c7465645f5f00010203040506075fccfb3397721c83694890dfe23e4516" +
"7b69d90d234d801114bb019d584a6f47"
)
@Test fun decryptsPythonCompatibleUtf8Fixture() {
assertArrayEquals(
"Paperize test image\u0000".toByteArray() + byteArrayOf(0xff.toByte()),
decryptEncryptedImage(encrypted, "päss漢字")
)
}
@Test fun rejectsWrongPassphraseAndDamagedPadding() {
assertThrows(IncorrectPassphraseException::class.java) {
decryptEncryptedImage(encrypted, "wrong")
}
val damaged = encrypted.clone().apply { this[21] = (this[21].toInt() xor 1).toByte() }
assertThrows(IncorrectPassphraseException::class.java) {
decryptEncryptedImage(damaged, "päss漢字")
}
}
@Test fun rejectsMalformedHeadersAndTruncatedCiphertext() {
val invalid = listOf(
byteArrayOf(),
encrypted.copyOfRange(0, 15),
encrypted.copyOfRange(0, 16),
encrypted.copyOfRange(0, 31),
encrypted.copyOfRange(0, encrypted.size - 1),
encrypted.clone().apply { this[0] = 0 }
)
invalid.forEach { bytes ->
assertThrows(InvalidEncryptedFileException::class.java) {
decryptEncryptedImage(bytes, "päss漢字")
}
}
}
private fun hex(value: String): ByteArray =
value.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
}
@@ -15,12 +15,12 @@ class CreateAlbumUseCaseTest {
@Test fun `a name that differs only by case is rejected without creating an album`() = runTest {
every { albums.getAlbumSummaries() } returns flowOf(listOf(testAlbumSummary("nature", "Nature")))
coEvery { albums.createAlbum("Trips", any()) } returns testAlbum("trips", "Trips")
coEvery { albums.createAlbum("Trips", any(), true) } returns testAlbum("trips", "Trips")
assertFalse(createAlbum("nature"))
coVerify(exactly = 0) { albums.createAlbum(any(), any()) }
coVerify(exactly = 0) { albums.createAlbum(any(), any(), any()) }
assertTrue(createAlbum("Trips"))
coVerify(exactly = 1) { albums.createAlbum("Trips", any()) }
assertTrue(createAlbum("Trips", true))
coVerify(exactly = 1) { albums.createAlbum("Trips", any(), true) }
}
}
@@ -20,6 +20,7 @@ class ImportWallpapersUseCaseTest {
private val useCase = ImportWallpapersUseCase(documents, repository)
@Test fun `image imports retain permission once and preserve metadata`() = runTest {
coEvery { repository.getAlbumEncryption("album") } returns false
coEvery { documents.retainReadPermission("image") } just Runs
coEvery { documents.readImage("image") } returns SourceImage("image", "photo.jpg", 42L)
coEvery { repository.addWallpapersToAlbum(any(), any(), any()) } returns 1
@@ -31,6 +32,7 @@ class ImportWallpapersUseCaseTest {
}
@Test fun `permission failure on one image saves nothing from the selection`() = runTest {
coEvery { repository.getAlbumEncryption("album") } returns false
coEvery { documents.retainReadPermission("ok") } just Runs
coEvery { documents.readImage("ok") } returns SourceImage("ok", "photo.jpg", 42L)
coEvery { documents.retainReadPermission("blocked") } throws SecurityException("No grant")
@@ -44,7 +46,7 @@ class ImportWallpapersUseCaseTest {
@Test fun `folder import keeps metadata and assigns membership`() = runTest {
coEvery { documents.retainReadPermission("tree") } just Runs
every { repository.getAlbumById("album") } returns flowOf(testAlbum("album"))
coEvery { documents.readFolder("tree", any()) } returns SourceFolder("Photos", listOf(SourceImage("image", "photo.png", 42L)))
coEvery { documents.readFolder("tree", false, any()) } returns SourceFolder("Photos", listOf(SourceImage("image", "photo.png", 42L)))
coEvery { repository.addFolderToAlbum(any(), any(), any()) } returns true
assertTrue(useCase.addFolder("album", "tree", {}, { _, _ -> }))
coVerify { repository.addFolderToAlbum("album", match { folder ->
@@ -62,6 +64,26 @@ class ImportWallpapersUseCaseTest {
))
assertFalse(useCase.addFolder("album", "tree", {}, { _, _ -> }))
coVerify { documents.retainReadPermission("tree") }
coVerify(exactly = 0) { documents.readFolder(any(), any()) }
coVerify(exactly = 0) { documents.readFolder(any(), any(), any()) }
}
@Test fun `encrypted image imports accept only jpg enc names ignoring case`() = runTest {
coEvery { repository.getAlbumEncryption("album") } returns true
coEvery { documents.retainReadPermission(any()) } just Runs
coEvery { documents.readImage("encrypted") } returns SourceImage("encrypted", "photo.JPG_ENC", 1)
coEvery { documents.readImage("plain") } returns SourceImage("plain", "photo.jpg", 2)
coEvery { documents.readImage("other") } returns SourceImage("other", "photo.png_enc", 3)
coEvery { repository.addWallpapersToAlbum(any(), any(), any()) } returns 1
assertTrue(useCase.addImages("album", listOf("encrypted", "plain", "other")) { _, _ -> })
coVerify { repository.addWallpapersToAlbum("album", match { it.map { image -> image.uri } == listOf("encrypted") }, any()) }
}
@Test fun `encrypted folder import passes its mode to source`() = runTest {
every { repository.getAlbumById("album") } returns flowOf(testAlbum("album").copy(isEncrypted = true))
coEvery { documents.retainReadPermission("tree") } just Runs
coEvery { documents.readFolder("tree", true, any()) } returns SourceFolder("Photos", emptyList())
coEvery { repository.addFolderToAlbum(any(), any(), any()) } returns true
assertTrue(useCase.addFolder("album", "tree", {}, { _, _ -> }))
coVerify { documents.readFolder("tree", true, any()) }
}
}
@@ -19,11 +19,13 @@ class RefreshFolderUseCaseTest {
@Test fun `refresh assigns membership and reports actual inserted count`() = runTest {
every { albums.getFolderById("folder") } returns flowOf(testFolder("folder", "album").copy(uri = "tree"))
coEvery { documents.readFolder("tree", any()) } returns SourceFolder("Photos", listOf(
coEvery { albums.getAlbumEncryption("album") } returns true
coEvery { documents.readFolder("tree", true, any()) } returns SourceFolder("Photos", listOf(
SourceImage("existing", "old.png", 1L), SourceImage("new", "new.png", 2L)
))
coEvery { albums.syncFolderWallpapers("album", "folder", any(), any()) } returns 1
assertEquals(1, refresh("folder"))
coVerify { documents.readFolder("tree", true, any()) }
coVerify { albums.syncFolderWallpapers("album", "folder", match {
it.size == 2 && it.all { image -> image.albumId == "album" && image.folderId == "folder" }
}, any()) }
@@ -123,13 +123,13 @@ class HomeViewModelTest {
}
@Test fun `album creation reports taken names and failed saves`() = runTest {
coEvery { createAlbum("nature") } returns false
coEvery { createAlbum("nature", false) } returns false
assertEquals(R.string.album_name_exists_error, viewModel.createAlbum("nature"))
coEvery { createAlbum("Trips") } throws IllegalStateException("Storage unavailable")
coEvery { createAlbum("Trips", false) } throws IllegalStateException("Storage unavailable")
assertEquals(R.string.album_create_failed, viewModel.createAlbum("Trips"))
coEvery { createAlbum("Trips") } returns true
coEvery { createAlbum("Trips", false) } returns true
assertNull(viewModel.createAlbum("Trips"))
}
}
@@ -2,6 +2,7 @@ package com.anthonyla.paperize.presentation.screens.settings
import androidx.lifecycle.ViewModelStore
import com.anthonyla.paperize.core.WallpaperMode
import com.anthonyla.paperize.data.source.EncryptedImageStore
import com.anthonyla.paperize.domain.model.AppSettings
import com.anthonyla.paperize.domain.repository.AlbumRepository
import com.anthonyla.paperize.domain.repository.SettingsRepository
@@ -24,6 +25,7 @@ class SettingsViewModelTest {
private val settings = mockk<SettingsRepository>(relaxed = true)
private val albums = mockk<AlbumRepository>()
private val scheduler = mockk<WallpaperScheduler>(relaxed = true)
private val encryptedImages = mockk<EncryptedImageStore>(relaxed = true)
private val store = ViewModelStore()
private lateinit var viewModel: SettingsViewModel
@@ -32,7 +34,7 @@ class SettingsViewModelTest {
@Before fun setUp() {
every { settings.getAppSettingsFlow() } returns flowOf(AppSettings())
every { settings.getWallpaperModeFlow() } returns flowOf(WallpaperMode.STATIC)
viewModel = SettingsViewModel(settings, SettingsCoordinator(mockk(), settings, mockk(), albums, scheduler))
viewModel = SettingsViewModel(settings, SettingsCoordinator(mockk(), settings, mockk(), albums, scheduler), encryptedImages)
store.put("settings", viewModel)
}
@@ -77,5 +79,15 @@ class SettingsViewModelTest {
advanceUntilIdle()
assertFalse(viewModel.resetFailed.value)
coVerify(exactly = 1) { settings.clearAllSettings() }
verify(exactly = 1) { encryptedImages.clearPassphrase() }
}
@Test fun `failed passphrase storage reports error and does not close dialog`() = runTest {
every { encryptedImages.setPassphrase(any()) } throws IllegalStateException("Keystore unavailable")
var saved = false
viewModel.setPassphrase("example") { saved = true }
advanceUntilIdle()
assertTrue(viewModel.passphraseFailed.value)
assertFalse(saved)
}
}
+18
View File
@@ -0,0 +1,18 @@
cd /home/lucas/git/Paperize
# Build the app
./gradlew assembleDebug
# Run unit tests and lint
./gradlew testDebugUnitTest lintDebug
# Run device/emulator tests (requires a running emulator or connected device)
./gradlew connectedDebugAndroidTest
# Install on a connected device
./gradlew installDebug
# Copy test assets to the device
adb shell mkdir -p /sdcard/Pictures/Paperize-testfiles
adb push ../Server-scripts/testassets/wallpaper_changer/corrupt /sdcard/Pictures/Paperize-testfiles/
adb push ../Server-scripts/testassets/wallpaper_changer/Desktop1920x1080 /sdcard/Pictures/Paperize-testfiles/