From 22091dd808a41a0c87e7fa79fe8a19cb6f8b262e Mon Sep 17 00:00:00 2001 From: Hadrian Burkhardt Date: Tue, 20 Oct 2026 09:28:29 +0200 Subject: [PATCH] feat: turn the paid app into a freemium app with ads and Pro - add a single AdMob anchored adaptive banner to the free tier - add UMP consent and a privacy-options entry point before ads load - add the one-time Play Billing product `pro_no_ads`; Pro removes the banner and nothing else, every scan/selection/deletion feature stays free - cache the entitlement locally, handle pending purchases, acknowledge and retry acknowledgement, and restore from Play on resume - grandfather paid installs through `legacyPro.cutoffEpochMs`, checking both the new package and the old paid package declared in - move the Play identity to `de.softwareapp_hb.fotodup.finder.free` while keeping the Kotlin namespace `de.softwareapp_hb.fotodup.finder` - add a debug-only Pro toggle and focused monetisation tests - add AGENTS.md, docs/codemap.md, docs/codemap.mmd and docs/MONETIZATION.md - update README, PRIVACY, CHANGELOG, ROADMAP, store copy and the Play checklist - bump to 1.1.0 / versionCode 4 --- AGENTS.md | 357 +++++++++++++ CHANGELOG.md | 49 ++ PRIVACY.md | 113 +++- README.md | 140 ++++- app/build.gradle.kts | 67 ++- app/src/debug/AndroidManifest.xml | 8 +- .../fotodup/finder/debug/DebugProToggle.kt | 55 ++ app/src/main/AndroidManifest.xml | 35 ++ .../fotodup/finder/FotoDupApplication.kt | 25 +- .../fotodup/finder/MainActivity.kt | 19 + .../fotodup/finder/monetization/AdPolicy.kt | 16 + .../finder/monetization/AdsController.kt | 124 +++++ .../fotodup/finder/monetization/AdsState.kt | 12 + .../fotodup/finder/monetization/LegacyPro.kt | 27 + .../fotodup/finder/monetization/ProProduct.kt | 19 + .../fotodup/finder/monetization/ProState.kt | 15 + .../fotodup/finder/monetization/ProStore.kt | 458 ++++++++++++++++ .../fotodup/finder/ui/ads/BannerAdSlot.kt | 92 ++++ .../finder/ui/components/ContextExt.kt | 20 + .../fotodup/finder/ui/pro/ProSheet.kt | 174 ++++++ .../finder/ui/scanner/ScannerScreen.kt | 98 +++- .../finder/ui/scanner/ScannerUiState.kt | 5 + .../finder/ui/scanner/ScannerViewModel.kt | 30 ++ app/src/main/res/values/strings.xml | 34 +- .../finder/monetization/AdPolicyTest.kt | 29 + .../finder/monetization/LegacyProTest.kt | 40 ++ docs/AD_COPY.md | 71 +-- docs/EDGE_CASE_TESTING.md | 10 +- docs/MONETIZATION.md | 274 ++++++++++ docs/PLAY_RELEASE_CHECKLIST.md | 307 ++++++----- docs/ROADMAP.md | 28 +- docs/STORE_LISTING.md | 125 +++-- docs/codemap.md | 496 ++++++++++++++++++ docs/codemap.mmd | 164 ++++++ gradle/libs.versions.toml | 12 + local.properties.example | 15 + 36 files changed, 3268 insertions(+), 295 deletions(-) create mode 100644 AGENTS.md create mode 100644 app/src/debug/java/de/softwareapp_hb/fotodup/finder/debug/DebugProToggle.kt create mode 100644 app/src/main/java/de/softwareapp_hb/fotodup/finder/monetization/AdPolicy.kt create mode 100644 app/src/main/java/de/softwareapp_hb/fotodup/finder/monetization/AdsController.kt create mode 100644 app/src/main/java/de/softwareapp_hb/fotodup/finder/monetization/AdsState.kt create mode 100644 app/src/main/java/de/softwareapp_hb/fotodup/finder/monetization/LegacyPro.kt create mode 100644 app/src/main/java/de/softwareapp_hb/fotodup/finder/monetization/ProProduct.kt create mode 100644 app/src/main/java/de/softwareapp_hb/fotodup/finder/monetization/ProState.kt create mode 100644 app/src/main/java/de/softwareapp_hb/fotodup/finder/monetization/ProStore.kt create mode 100644 app/src/main/java/de/softwareapp_hb/fotodup/finder/ui/ads/BannerAdSlot.kt create mode 100644 app/src/main/java/de/softwareapp_hb/fotodup/finder/ui/components/ContextExt.kt create mode 100644 app/src/main/java/de/softwareapp_hb/fotodup/finder/ui/pro/ProSheet.kt create mode 100644 app/src/test/java/de/softwareapp_hb/fotodup/finder/monetization/AdPolicyTest.kt create mode 100644 app/src/test/java/de/softwareapp_hb/fotodup/finder/monetization/LegacyProTest.kt create mode 100644 docs/MONETIZATION.md create mode 100644 docs/codemap.md create mode 100644 docs/codemap.mmd create mode 100644 local.properties.example diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..f77067c --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,357 @@ +# AGENTS.md + +Operating instructions for AI coding agents working on **Foto Dup Finder**. + +Read this file before changing code, tests, monetisation, permissions or Android +configuration. It defines the product boundaries, architecture rules and the +definition of done for this repository. + +## 1. Project snapshot + +| Item | Value | +|---|---| +| Product | Foto Dup Finder — offline duplicate/near-duplicate photo finder | +| Model | **Freemium**: free tier with one AdMob banner, one-time Pro purchase removes ads | +| Current version | `1.1.0` / `versionCode 4` (`app/build.gradle.kts`) | +| Platform | Android, Kotlin + Jetpack Compose, single `:app` module | +| Application id | `de.softwareapp_hb.fotodup.finder.free` (debug `.free.debug`); namespace/code package remains `de.softwareapp_hb.fotodup.finder` | +| SDKs | `minSdk 26`, `compileSdk`/`targetSdk` 36 | +| Toolchain | Gradle 9.3.1, AGP 9.1.0, Kotlin 2.4.10, JDK 17+ | +| UI | Compose BOM 2026.06.01 (Compose 1.11.4, Material 3) | +| Ads | Google Mobile Ads (legacy) 25.5.0 + UMP 4.0.0 | +| Billing | Play Billing 9.1.0, one-time product `pro_no_ads` | +| Persistence | SQLite `photo_index.db` (hash cache) + `pro_entitlement` SharedPreferences | +| Tests | JVM unit tests + Robolectric; no instrumentation test suite | + +Architecture document: [`docs/codemap.md`](docs/codemap.md) +Standalone Mermaid graph: [`docs/codemap.mmd`](docs/codemap.mmd) +Monetisation setup: [`docs/MONETIZATION.md`](docs/MONETIZATION.md) +Roadmap: [`docs/ROADMAP.md`](docs/ROADMAP.md) +Release checklist: [`docs/PLAY_RELEASE_CHECKLIST.md`](docs/PLAY_RELEASE_CHECKLIST.md) +Privacy policy: [`PRIVACY.md`](PRIVACY.md) + +**Current gate:** the freemium release (`1.1.0`) is implemented in code, but the +Play Console work (change the app to free, create `pro_no_ads`, AdMob app/unit, +UMP message, Data Safety, Ads/Advertising ID declarations) is manual. Do not +describe the app as "ad-free", "no internet" or "paid once" — those claims belong +to the historical pre-freemium build. + +## 2. Commands + +```bash +# Build / test / lint +./gradlew :app:assembleDebug +./gradlew :app:testDebugUnitTest +./gradlew :app:lintDebug +./gradlew :app:assembleRelease +./gradlew :app:bundleRelease + +# Focused tests +./gradlew :app:testDebugUnitTest --tests '*AdPolicyTest*' +./gradlew :app:testDebugUnitTest --tests '*LegacyProTest*' +./gradlew :app:testDebugUnitTest --tests '*ScanEngineEndToEndTest*' + +# Opt-in similarity benchmark +./gradlew :app:testDebugUnitTest --tests '*SimilarityBenchmarkTest*' -DfotoBench=true + +# Install +adb install -r app/build/outputs/apk/debug/app-debug.apk +``` + +**AdMob configuration.** Debug builds default to Google's public test ids. Real ids +and the legacy-Pro cutoff come from `local.properties` (git-ignored) or Gradle +properties: + +```properties +admob.appId=ca-app-pub-XXXXXXXXXXXXXXXX~YYYYYYYYYY +admob.bannerUnitId=ca-app-pub-XXXXXXXXXXXXXXXX/NNNNNNNNNN +legacyPro.cutoffEpochMs=1793491200000 +``` + +```bash +./gradlew :app:bundleRelease \ + -Padmob.appId=ca-app-pub-... \ + -Padmob.bannerUnitId=ca-app-pub-.../... \ + -PlegacyPro.cutoffEpochMs=1793491200000 +``` + +**Debug hooks** (debug source set only, absent from release): + +```bash +adb shell am broadcast -a de.softwareapp_hb.fotodup.finder.debug.GRANT_PRO \ + -n de.softwareapp_hb.fotodup.finder.free.debug/de.softwareapp_hb.fotodup.finder.debug.DebugProToggle +adb shell am broadcast -a de.softwareapp_hb.fotodup.finder.debug.REVOKE_PRO \ + -n de.softwareapp_hb.fotodup.finder.free.debug/de.softwareapp_hb.fotodup.finder.debug.DebugProToggle +adb shell am broadcast -a de.softwareapp_hb.fotodup.finder.debug.REPORT_PRO_STATE \ + -n de.softwareapp_hb.fotodup.finder.free.debug/de.softwareapp_hb.fotodup.finder.debug.DebugProToggle +``` + +`DebugScanTrigger` is the existing scan driver; see `app/src/debug/AndroidManifest.xml`. + +Never use `./gradlew --offline` for a fresh dependency check, and never commit +`local.properties`, `keystore.properties`, `*.jks`, APKs or AABs. + +## 3. Non-negotiable product constraints + +1. **The utility stays free.** Every scan, sensitivity preset, selection and + deletion feature must work in the free tier. Pro removes the banner and nothing + else. Do not add scan limits, locked groups or a paywall for deleting. +2. **Photo pixels never leave the device.** Only the ad SDK, UMP and Play Billing + may use the network. No analytics, crash reporting, accounts, cloud sync or + server-side purchase verification. +3. **Ads are the only free-tier monetisation.** One anchored adaptive banner at the + bottom. No interstitial, app-open, rewarded or native ad without an explicit + product decision and a UX review. +4. **Deletion is two-step and system-consented.** Staging is not deletion. Android + 11+ always uses `MediaStore.createDeleteRequest` / `createTrashRequest`; never + request `MANAGE_EXTERNAL_STORAGE`. +5. **Existing paid customers keep Pro.** The legacy install cutoff is the migration + path. Do not remove it without a replacement that preserves paid users. +6. **Test ids are for development only.** Never ship Google's test AdMob ids in a + release build. The build warns when they are still in use. +7. **Consent comes before ads.** No `MobileAds.initialize()` and no ad request until + UMP says `canRequestAds()`. Pro users skip ad initialisation entirely. +8. **Historical claims are historical.** README/PRIVACY/store copy must not claim + "no ads", "no INTERNET permission" or "paid once" for the freemium build. + +## 4. Architecture rules + +- `core/` is **pure Kotlin** — no `android.*`, no Compose, no resources. It must run + on a plain JVM so the hashing/grouping tests stay fast. +- `data/` is the only layer that talks to MediaStore, the file system, SQLite, + permissions and the system delete APIs. +- `domain/` orchestrates scanning and owns `ScanController`; it must not import + Compose or hold an Activity. +- `service/` mirrors `ScanController` into a foreground notification; it contains no + scan logic. +- `monetization/` owns consent, Mobile Ads and Play Billing. It must not touch the + photo pipeline. +- `ui/` owns Compose, selection/staging and the ad slot. It may read domain/data/ + monetisation state; it must not hash or delete photos directly. +- All user-visible text lives in `res/values/strings.xml`; enum→resource mappings + live in `text/TextRes.kt` so the screen and notification cannot drift. +- `FotoDupApplication` creates exactly three process-scoped objects: + `ScanController`, `ProStore`, `AdsController`. +- `MainActivity` starts consent/ad init for free users and refreshes purchases on + resume. Do not move scan ownership into an Activity or ViewModel. + +## 5. Key files + +| Area | Files | +|---|---| +| Entry | `FotoDupApplication.kt`, `MainActivity.kt`, `AndroidManifest.xml` | +| Scan UI | `ui/scanner/ScannerScreen.kt`, `ScannerViewModel.kt`, `ScannerUiState.kt`, `ScannerSections.kt`, `GroupSection.kt` | +| Scan engine | `domain/ScanEngine.kt`, `ScanController.kt`, `ScanModels.kt`, `Parallel.kt` | +| Data | `data/MediaStorePhotoSource.kt`, `PhotoHasher.kt`, `PhotoIndexStore.kt`, `MediaDeleter.kt`, `AppPermissions.kt`, `BoundedCall.kt` | +| Core | `core/Hashing.kt`, `PerceptualHash.kt`, `RgbDHash.kt`, `DuplicateGrouper.kt`, `DuplicatePolicy.kt`, `AdaptiveThreshold.kt` | +| Monetisation | `monetization/ProStore.kt`, `ProProduct.kt`, `LegacyPro.kt`, `AdsController.kt`, `AdPolicy.kt` | +| Monetisation UI | `ui/ads/BannerAdSlot.kt`, `ui/pro/ProSheet.kt` | +| Resources | `res/values/strings.xml`, `text/TextRes.kt`, `AndroidManifest.xml`, `app/build.gradle.kts` | +| Tests | `app/src/test/.../core`, `data/BoundedCallTest.kt`, `domain/ScanEngineEndToEndTest.kt`, `monetization/*Test.kt` | + + +## 6. Scan-engine invariants + +1. **Tiering is the performance contract.** Only photos with a duplicate file size + are opened for the quick signature; only signature buckets with 2+ members get a + full SHA-256; every readable photo gets a perceptual hash unless the policy is + `EXACT_ONLY`. +2. **One decode per perceptual photo.** `PhotoHasher.perceptualFingerprint()` must + produce both the pHash and the RGB dHash from the same decode/thumbnail. +3. **The index is a cache.** A row is reusable only when size and modified stamp + still match. Bump `PhotoIndexStore.DB_VERSION` whenever the meaning of a stored + hash changes; `onUpgrade` drops and rebuilds. +4. **Every provider call has a deadline.** Do not call `ContentResolver`, file + descriptors or `loadThumbnail` without `BoundedCall`/`withTimeoutOrNull`. A + stuck provider must produce an unreadable photo, not a frozen scan. +5. **The scan is process-scoped.** `ScanController` owns the job and result; the + ViewModel mirrors `ScanState`. `ScanService` keeps a `dataSync` foreground + service alive while it runs. +6. **Thresholds are fitted, then clamped.** `DuplicatePolicy` supplies ceilings; + `AdaptiveThreshold` fits the pHash cut to the candidate population; exact + grouping does not decode anything. +7. **Unreadable photos are reported, not silently dropped.** They still participate + in exact matching but not in the perceptual pass. +8. **Grouping is deterministic.** Union-find plus the suggested-keep rule must match + the UI's `BEST` badge and “select all but best”. + +## 7. Monetisation workflow + +1. Free users get exactly one `BannerAdSlot`, placed below the bottom action bar. + It is only composed when `AdPolicy.shouldShowBanner(!isPro, canRequestAds, + initialized)` is true. +2. `AdsController` requests a UMP consent update at every free-user launch, shows a + form if required, and only then calls `MobileAds.initialize()`. +3. Pro users never initialise ads. `MainActivity` checks the cached entitlement + before calling `ensureInitialized()`. +4. `ProStore` is the only entitlement source. It queries `pro_no_ads`, grants only + `PurchaseState.PURCHASED`, acknowledges the purchase, retries an outstanding + acknowledgement, and keeps the local cache for offline launches. +5. `PENDING` never grants Pro. `USER_CANCELED` is not an error. `ITEM_ALREADY_OWNED` + refreshes purchases. A successful query with no purchase revokes Pro **unless** + the install is grandfathered. +6. `LegacyPro` compares the earliest `firstInstallTime` of the freemium package and + the old paid package (`LegacyPro.OLD_PAID_PACKAGE`, declared in ``) with + `BuildConfig.LEGACY_PRO_CUTOFF_EPOCH_MS`. Set that cutoff to the first freemium + release before shipping. The old app must still be installed on the first freemium + launch; otherwise the grant is best-effort only. +7. Product id: `pro_no_ads` (`ProProduct.ID`). Price comes from Play's localized + `formattedPrice`; never hardcode a currency amount in UI text. +8. Do not add a server-side entitlement check, analytics or a second ad network + without an explicit product/privacy decision. + +## 8. UI and UX conventions + +- Material 3 + `FotoDupTheme`; dynamic colour on Android 12+, branded green + fallback otherwise. +- All text through `stringResource` / `TextRes`. Plurals use ``. +- The bottom slot is `Column(navigationBarsPadding) { BottomActionBar; BannerAdSlot }`. + Do not reintroduce `navigationBarsPadding()` inside `BottomActionBar`. +- Keep the ad separated from Apply by padding; never overlay an ad on a button. +- Staging is optimistic: rows disappear immediately, nothing is deleted until + Apply. The bottom bar must always say whether Apply will trash or delete. +- The Pro sheet must state that every feature stays free and that the purchase is + one-time. Show a localized price when Play provides one. +- Keep the Options menu usable on a phone: Scan/Cancel + Options are the only top + bar actions; Pro and privacy options live in the menu. +- TalkBack: thumbnails are selectable and have content descriptions; ad views are + announced by the SDK. Do not remove the ad's own accessibility behaviour. +- Verify layouts on a phone and a tablet; the app supports edge-to-edge and both + form factors. + + +## 9. Testing expectations + +- Add a focused JVM test for every new pure rule. `AdPolicyTest` and + `LegacyProTest` are the pattern for monetisation logic; `core/*Test` for hashing/ + grouping; `BoundedCallTest` for provider robustness. +- `ScanEngineEndToEndTest` runs the real pipeline through Robolectric and + `FakeMediaStoreProvider`. It can prove exact duplicates and unreadable-file + handling, but **not** perceptual matching (Robolectric does not decode real + pixels). Use the benchmark harness or a device for perceptual changes. +- There is no instrumentation test. UI, ads and Billing must be checked on a device: + - ads need a Play-services device and a real or test AdMob unit; + - Billing needs an internal-testing track and a license-tester account; + - the AOSP AVDs in this environment have no Play services, so they cannot fill + ads or complete purchases. +- Use `DebugProToggle` to exercise the Pro UI without Billing. Use the UMP debug + geography/test-device flow in `docs/MONETIZATION.md` to exercise consent. +- After any dependency or manifest change, audit the **merged** release manifest: + `./gradlew :app:processReleaseMainManifest` and inspect + `app/build/intermediates/merged_manifests/release/.../AndroidManifest.xml`. +- Minimum before calling a change done: + `./gradlew :app:testDebugUnitTest :app:lintDebug :app:assembleDebug`. + For release changes also `:app:assembleRelease` (R8 + manifest merge). + +## 10. Privacy and security + +- The app's differentiator is on-device photo processing. Never add code that + uploads a photo, a thumbnail, a hash, a filename or a folder path. +- The only network traffic is AdMob/UMP and Play Billing. Adding analytics, crash + reporting, a backend or another SDK changes the Data Safety declaration and + `PRIVACY.md`; treat it as a product decision, not a refactor. +- The ads SDK merges `INTERNET`, `ACCESS_NETWORK_STATE`, `AD_ID`, the + `ACCESS_ADSERVICES_*` permissions and `WAKE_LOCK`. Billing merges + `com.android.vending.BILLING`. Audit the + merged manifest; do not claim the old "no INTERNET" permission set. +- UMP consent must be collected where required and the privacy-options entry point + must stay reachable. A refused consent means no ad request, not a broken app. +- The Pro entitlement is client-side and can be tampered with on a rooted device. + Do not log purchase tokens, do not put secrets in source, and do not pretend this + is server-verified. +- Keep `local.properties`, `keystore.properties`, `*.jks`, AdMob ids and the legacy + cutoff out of commits. Test ids are public and may stay in the build defaults. +- `photo_index.db` is a cache and is excluded from backup. The Pro prefs are + included in Android backup; Play re-verifies on the next connection. + +## 11. Common pitfalls + +1. **`compileSdk` is pinned to 36.** Compose BOM 2026.06.01 and Coil 3.5.0 were + chosen because the next versions require compileSdk 37, which AGP 9.1.0 does + not support. Bump them together once AGP supports 37. +2. **AGP 9 has built-in Kotlin.** Do not apply `org.jetbrains.kotlin.android`; it is + an error. Only the Compose compiler plugin is applied. +3. **Billing 9 callbacks changed.** `queryProductDetailsAsync` delivers a + `QueryProductDetailsResult`; use `result.productDetailsList`, not the old list. + `enablePendingPurchases(PendingPurchasesParams...)` is mandatory for one-time + products. +4. **Acknowledge after granting.** Play refunds an unacknowledged purchase after + three days. Keep `KEY_PENDING_ACK` and retry. +5. **The adaptive ad API moved.** Use + `AdSize.getLargeAnchoredAdaptiveBannerAdSize(context, widthDp)`. + `getCurrentOrientationAnchoredAdaptiveBannerAdSize` is deprecated. +6. **AdMob needs the manifest meta-data.** `com.google.android.gms.ads.APPLICATION_ID` + must resolve; without it `MobileAds.initialize` fails. Test ids are the defaults. +7. **Gradle parallel builds can collide on resources.** If `mergeDebugResources` + reports a missing `values-xx.xml` while another Gradle command is running, rerun + the command sequentially; both tasks were writing the same incremental folder. +8. **Robolectric needs the JVM flags** in `app/build.gradle.kts` (`--add-opens` / + `--add-exports`). Removing them breaks the data-layer tests on JDK 17+. +9. **AOSP emulators do not have Play services.** An empty ad slot or a "purchases + unavailable" message there is expected; it is not a code failure. +10. **`versionCode` must increase** for every Play upload. `1.0.2` used 3; the + freemium build is 4. Update `CHANGELOG.md` and the release checklist too. +11. **Do not call `navigationBarsPadding()` twice.** The bottom slot owns the inset; + `BottomActionBar` must not add it again. +12. **The old paid-app docs are historical.** Do not copy "pay once", "no ads" or + "no INTERNET" claims into new copy. + + +## 12. Definition of done + +- [ ] Feature works through a complete user flow, not a dead placeholder. +- [ ] Free tier still does everything; Pro removes only the banner. +- [ ] Photo data remains on-device; no new network dependency beyond ads/UMP/Billing. +- [ ] `core/` remains pure Kotlin; no Android import. +- [ ] All user-visible text is in `strings.xml`; plurals are real ``. +- [ ] New pure logic has a focused JVM test. +- [ ] `./gradlew :app:testDebugUnitTest` is green. +- [ ] `./gradlew :app:lintDebug` is clean (or the existing warnings are unchanged). +- [ ] `./gradlew :app:assembleDebug` succeeds. +- [ ] For release-affecting work: `./gradlew :app:assembleRelease` succeeds and the + merged manifest permissions are re-audited. +- [ ] `docs/codemap.md` and `docs/codemap.mmd` are updated for architecture changes. +- [ ] `README.md`, `PRIVACY.md`, `CHANGELOG.md`, `docs/MONETIZATION.md`, + `docs/STORE_LISTING.md` and `docs/PLAY_RELEASE_CHECKLIST.md` are updated when + user-visible behaviour, permissions or monetisation changed. +- [ ] No secrets, keystores, APKs/AABs, `local.properties` or build outputs staged. +- [ ] The commit message describes the change. + +## 13. Agent workflow + +1. Read this file, `README.md`, the relevant part of `docs/codemap.md`, and — for + monetisation changes — `docs/MONETIZATION.md`. +2. Run the baseline checks (`./gradlew :app:testDebugUnitTest`) if time permits. +3. Locate the owning layer from the codemap; make the smallest coherent change. +4. Add/adjust tests before or alongside the implementation. +5. Run focused tests, then the full suite, lint and the debug build. +6. For ads/Billing changes, verify the free/Pro UI with `DebugProToggle`; state + clearly which device/Play-console steps could not be run locally. +7. Update the codemap, AGENTS.md and the relevant user/release docs. +8. Commit with a scoped message. + +Do **not**: + +- add a feature gate to scanning or deletion; +- add analytics, accounts, a backend or a new ad network without an explicit + product/privacy decision; +- weaken or delete correctness tests to make a change pass; +- ship test ad ids in a release build; +- claim the app has no network permission or is ad-free; +- commit generated build outputs or secrets. + +## 14. Environment notes + +- Verified with JDK 25, Gradle 9.3.1, AGP 9.1.0 and Android SDK 36. +- The machine may expose no `/dev/kvm`; AOSP AVDs run in software emulation. That is + fine for layout checks, but they have no Play services, so ads and Billing cannot + be exercised there. +- The real device used for earlier screenshots is MIUI, which denies `adb shell + input`; the debug broadcast hooks exist for that reason. +- `local.properties` is machine-specific and git-ignored. Use + `local.properties.example` as the template. +- Release builds are signed only when `keystore.properties` exists; otherwise they + still run R8 and produce an unsigned APK for local checks. +- The store assets and screenshots in `store-assets/` predate the freemium banner + and need a re-shoot (banner visible, Pro sheet) before the next store listing. + diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ad9a5a..ee91f59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,55 @@ upload needs a **higher `versionCode`** than every previous upload. ## [Unreleased] +## [1.1.0] — 2026-10-20 · versionCode 4 + +### Added + +- **Freemium model.** The app is free to download and use. The free tier shows one + anchored adaptive AdMob banner at the bottom of the scanner; a one-time in-app + purchase (`pro_no_ads`) removes it. Every duplicate-finding, selection and deletion + feature stays free — Pro only removes advertising. +- **Play Billing 9.1.0** with purchase, pending-purchase, acknowledgement and restore + handling. The entitlement is cached locally so an already-Pro install opens ad-free + offline and is reconciled with Play on resume. +- **UMP consent** (`user-messaging-platform` 4.0.0) before ad initialization, plus a + **Privacy options** entry point when UMP requires it. +- **Legacy paid-install grandfathering** through a build-time + `legacyPro.cutoffEpochMs`, so customers who bought the paid app keep the ad-free + tier. +- **Debug tools:** `DebugProToggle` (adb-driven free/Pro switch) and the existing + scan trigger. +- **Documentation:** [`AGENTS.md`](AGENTS.md), [`docs/codemap.md`](docs/codemap.md), + [`docs/codemap.mmd`](docs/codemap.mmd) and + [`docs/MONETIZATION.md`](docs/MONETIZATION.md). + +### Changed + +- **`versionName` 1.1.0 / `versionCode` 4.** Play has consumed codes 1–3. +- **New Play application id:** `de.softwareapp_hb.fotodup.finder.free` (debug + `.free.debug`). The Kotlin package and `namespace` stay + `de.softwareapp_hb.fotodup.finder`; only the installed/listing identity changes. This + makes the freemium build a **separate Play listing** from the old paid app, so the old + listing's price does not have to be changed irreversibly. Grandfathering checks both + packages' first-install times, but the old paid app must still be installed on the + first freemium launch; otherwise use promo codes/support. +- **Permissions.** The merged manifest now includes `INTERNET`, + `ACCESS_NETWORK_STATE`, `AD_ID`, the `ACCESS_ADSERVICES_*` Privacy Sandbox + permissions, `WAKE_LOCK` and `com.android.vending.BILLING`, merged by the ads and + Billing SDKs. The previous “no INTERNET permission” claim no longer applies. +- **Privacy policy and store copy** now describe advertising, consent, the + advertising ID and the optional purchase. Photo processing remains on-device; + photos are never uploaded. +- **Store/Play documentation** now treats the paid-app pricing section as historical + and documents the freemium Console steps, Data Safety answers and required + screenshot re-shoot. + +### Fixed + +- The old paid-app claims (“ad-free”, “no internet permission”, “pay once”) were + removed from the current README/PRIVACY/store wording so they cannot contradict the + shipped SDKs. + ## [1.0.2] — 2026-10-18 · versionCode 3 ### Changed diff --git a/PRIVACY.md b/PRIVACY.md index 374f986..6fb2bb9 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -1,13 +1,16 @@ # Privacy Policy — Foto Dup Finder -_Last updated: 2026-10-14_ +_Last updated: 2026-10-20_ ## Summary -Foto Dup Finder finds and removes duplicate photos **entirely on your device**. -The app does **not** collect, transmit, sell or share any of your data. It has no -network access at all. It is sold once through Google Play; the purchase is handled -entirely by Google Play, never by the app (see [Purchases](#purchases)). +Foto Dup Finder finds and removes duplicate photos **entirely on your device**. Your +photos, thumbnails and photo metadata are never uploaded, sold or shared. + +The app is **freemium**. The free tier is supported by advertising served by Google +AdMob; a one-time **Pro** purchase removes the ads. The only network traffic is the +advertising/consent SDK and Google Play Billing. The app has no account, no analytics +and no developer-operated server. ## What the app accesses @@ -16,16 +19,51 @@ entirely by Google Play, never by the app (see [Purchases](#purchases)). | Your photos (images) | To compare them and detect duplicates | Never leaves your device | | Photo metadata (file name, size, folder, dimensions, date) | To group and display results | Never leaves your device | | A local cache of file hashes | To make repeat scans fast | Stored only in this app's private storage | +| Purchase status (`pro_no_ads`) | To keep Pro active and restore it | Handled by Google Play; the app never receives payment details | +| Advertising data (see below) | To show the free tier's banner | Collected/shared by Google Mobile Ads | + +## Advertising and consent + +The free tier uses the **Google Mobile Ads SDK**. Google states that the SDK +automatically collects and shares the following data for advertising, analytics and +fraud-prevention purposes: + +- **IP address** — may be used to estimate general location; +- **User product interactions** — app launch, taps and video views; +- **Diagnostic information** — app launch time, hang rate and energy usage; +- **Device and account identifiers** — Android advertising ID, app set ID, and + identifiers related to signed-in accounts on the device where applicable. + +All of that data is encrypted in transit using TLS. The app does not receive your +name, email, phone number or payment details. + +Where required (for example the EEA, UK, Switzerland and some US states), the +**Google User Messaging Platform (UMP)** asks for your consent before any ad is +requested. You can change your choice at any time through **Options → Privacy +options** when that entry point is required, or by resetting/deleting your advertising +ID in Android Settings. A refused or unresolved consent means no ad is shown; the +duplicate finder still works. + +Google's privacy policy: . ## What the app does NOT do -- It does **not** have the `INTERNET` permission, so it cannot send data anywhere. -- It does **not** collect analytics, crash reports, advertising identifiers or - location data. -- It does **not** contain advertising SDKs or third-party trackers. -- It does **not** create accounts and does **not** ask for your name, email or - phone number. +- It does **not** upload, transmit or share your photos, thumbnails, file names or + folder paths. +- The app itself does **not** collect analytics or crash reports. Google Mobile Ads + collects the advertising data described above for advertising, analytics and + fraud prevention. +- It does **not** request or collect location, contacts, camera, microphone or + health data. The ads SDK may estimate general location from the IP address, as + described above. +- It does **not** contain third-party trackers beyond the Google Mobile Ads/UMP and + Play Billing SDKs described here. +- It does **not** sell your data. +- It does **not** create accounts or ask for your name, email or phone number. - It does **not** read photos other than the images you grant access to. +- It does **not** use `MANAGE_EXTERNAL_STORAGE` or delete anything without the + Android system confirmation dialog. + ## Permissions and what they mean @@ -34,6 +72,15 @@ entirely by Google Play, never by the app (see [Purchases](#purchases)). | Read photos (`READ_MEDIA_IMAGES` / `READ_EXTERNAL_STORAGE`) | Required to scan your photo library. You can deny this and the app simply will not scan. On Android 14+ you may grant access to *selected photos only*; the app then scans only those. | | `READ_MEDIA_VISUAL_USER_SELECTED` | Supports Android 14's partial photo access. | | `WRITE_EXTERNAL_STORAGE` (Android 10 only) | Used solely to delete photos you explicitly select on that older Android version. | +| `POST_NOTIFICATIONS` | Shows the optional scan-progress notification. The scan works without it. | +| `FOREGROUND_SERVICE` + `FOREGROUND_SERVICE_DATA_SYNC` | Keeps a long scan alive while the app is backgrounded. | +| `INTERNET` + `ACCESS_NETWORK_STATE` | Used only by the free-tier ad/consent SDK and the optional Pro purchase. | +| `AD_ID` + `ACCESS_ADSERVICES_*` | Merged by the Google Mobile Ads SDK; used for advertising and measurement. | +| `WAKE_LOCK` | Merged by the Google Mobile Ads SDK for ad rendering. | +| `com.android.vending.BILLING` | Merged by Play Billing; used only for the one-time `pro_no_ads` purchase. | + +The ad and Billing SDKs have no access to your photos. The app never requests +location, contacts, camera, microphone or `MANAGE_EXTERNAL_STORAGE`. ## Deleting photos @@ -48,24 +95,46 @@ you selected. ## Data retention and deletion The app stores a small local database of file hashes in its private app storage so -that repeat scans are fast. This database contains no image content and never leaves -your device. Uninstalling the app, or clearing its storage in Android Settings, -removes it completely. +that repeat scans are fast. It contains no image content and never leaves your +device. Uninstalling the app, or clearing its storage in Android Settings, removes it +completely. + +The app also stores a small `pro_entitlement` preference file (whether Pro is active, +the legacy-install decision and a pending purchase-acknowledgement token). It +contains no photo data. Clearing the app's storage or uninstalling removes it; a +purchase can then be restored through Google Play. + +Advertising data collected by Google Mobile Ads is held by Google under its privacy +policy, not by the developer. You can reset or delete your advertising ID in Android +Settings and change consent through the app's **Privacy options** entry point where +UMP requires it. ## Purchases -The app is **sold once through Google Play**. There is no subscription and there is nothing to buy -inside the app. +The app is **free to download and use**. The optional **Pro** upgrade is a one-time +in-app purchase (`pro_no_ads`) that removes the banner. There is no subscription. -Google Play processes the payment and holds the payment details. The app contains no payment code -and never receives them, because it has no network access of any kind (see above). Refunds, order -problems and any question about a charge are handled by Google Play, and the developer can be -reached at the address below. +Google Play processes the payment and holds the payment details. The app never +receives or stores your payment method, and it has no server that could verify a +purchase remotely. Pro status is cached locally and reconciled with Google Play when +the app is online; this is why a purchase can be restored on a device signed into the +same Google account. + +Customers who bought the app before it became freemium are grandfathered into Pro +based on the install timestamp, as described in +[docs/MONETIZATION.md](docs/MONETIZATION.md). Because the freemium build is a separate +package, the old paid app must still be installed the first time the new app runs; +otherwise the grant cannot be detected. + +Refunds, order problems and questions about a charge are handled by Google Play, and +the developer can be reached at the address below. ## Children -The app is a general-purpose utility and is not directed at children. It collects no -personal data from anyone. +The app is a general-purpose utility and is not directed at children. It has no +account and does not knowingly collect personal information from children. The +free-tier advertising is not configured as child-directed; if that changes, the ad +configuration and this policy must change with it. ## Changes diff --git a/README.md b/README.md index 921f06d..ed2e0d6 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,26 @@ # Foto Dup Finder -A fast, **ad-free**, **fully offline** Android app that finds and removes duplicate -and near-duplicate photos. Built as a direct answer to the slow, ad-laden cleanup -tools that ship with many phones. +A fast, private Android app that finds and removes duplicate and near-duplicate +photos. The free tier is supported by a single banner ad; a one-time **Pro** +purchase removes it. -Nothing ever leaves the device: the app declares no network permission, contains no -analytics and needs no account. +Your photos never leave the device: all scanning, hashing and grouping happen +on-device. The only network traffic is the ad/consent SDK and Google Play Billing +(for the optional Pro purchase). There is no account, no app-level analytics and no +upload; the ads SDK's own data collection is described in [PRIVACY.md](PRIVACY.md). ## Features +- **Free with one banner, Pro without ads** + - The free tier has every feature and one anchored banner at the bottom. + - A one-time in-app purchase (`pro_no_ads`) removes the banner. + - Nothing is locked behind Pro; the duplicate cleaner stays fully usable for free. - **Two kinds of duplicates** - *Exact* — byte-identical copies, found with a cheap size/head/tail signature followed by a full SHA-256. - *Near* — resized, recompressed or lightly edited versions, found with a 64-bit - perceptual difference hash (`dHash`) plus a Hamming-distance threshold. + pHash plus one RGB difference hash per colour channel, compared with + Hamming-distance thresholds. - **Tiered, parallel pipeline**: only plausible candidates get a full hash, and the work is spread across all CPU cores. - **Persistent index** so a re-scan only touches new or changed files. @@ -32,11 +39,15 @@ analytics and needs no account. | Area | Choice | |---|---| +| Application ID | `de.softwareapp_hb.fotodup.finder.free` (namespace/code package stays `de.softwareapp_hb.fotodup.finder`) | | Language | Kotlin 2.4.10 (using AGP 9 *built-in Kotlin*) | | UI | Jetpack Compose, BOM 2026.06.01, Material 3 | | Build | Gradle 9.3.1, Android Gradle Plugin 9.1.0 | | Image loading | Coil 3.5.0 | | Storage | MediaStore read + a small SQLite hash cache | +| Ads | Google Mobile Ads 25.5.0 + UMP 4.0.0 | +| Purchases | Play Billing 9.1.0, one-time `pro_no_ads` | +| Network | only the ad/consent SDK and Play Billing; photos never leave the device | | SDK levels | `compileSdk`/`targetSdk` 36, `minSdk` 26 | `targetSdk` is 36 because Google Play requires new apps and updates to target @@ -50,20 +61,27 @@ Android 16 (API 36) from 31 August 2026. ``` app/src/main/java/de/softwareapp_hb/fotodup/finder/ -├── core/ Pure-Kotlin duplicate engine (no Android imports!) +├── core/ Pure-Kotlin duplicate engine (no Android imports!) │ ├── Hashing.kt SHA-256 + cheap size/head/tail signature -│ ├── PerceptualHash.kt 64-bit dHash + Hamming distance +│ ├── PerceptualHash.kt 64-bit pHash +│ ├── RgbDHash.kt one difference hash per colour channel │ ├── DuplicateGrouper.kt exact + perceptual grouping (union-find) │ ├── DuplicatePolicy.kt Exact / Balanced / Aggressive thresholds │ └── … -├── data/ MediaStore access, hashing, permissions, SQLite index, deletion -├── domain/ ScanEngine (tiered pipeline) + progress/result models -└── ui/ Compose theme, scanner screen, ViewModel, components -app/src/test/java/… JVM unit tests for the core engine +├── data/ MediaStore access, hashing, permissions, SQLite index, deletion +├── domain/ ScanController + ScanEngine (tiered pipeline) + result models +├── service/ dataSync foreground service + scan notification +├── monetization/ ProStore (Billing), AdsController (UMP + Ads), AdPolicy, LegacyPro +├── text/ shared enum → string-resource mappings +└── ui/ Compose theme, scanner, ad slot, Pro sheet, components +app/src/test/java/… JVM unit tests for core/data/domain/monetization ``` `core/` deliberately has **no Android dependencies**, so the trickiest logic -(hashing, perceptual hashing, grouping) is covered by fast JVM tests. +(hashing, perceptual hashing, grouping) is covered by fast JVM tests. The full +layered map, runtime flows and change-impact matrix are in +[`docs/codemap.md`](docs/codemap.md); the standalone graph is +[`docs/codemap.mmd`](docs/codemap.mmd). ## Building @@ -73,16 +91,34 @@ Prerequisites: - Android SDK with `platforms;android-36` and `build-tools;36.0.0` ```bash -# Tell Gradle where the SDK lives (this file is git-ignored) -echo "sdk.dir=$HOME/Android/Sdk" > local.properties +# Copy the machine-specific template (this file is git-ignored) +cp local.properties.example local.properties +# then set sdk.dir=... and optionally the real AdMob ids ./gradlew :app:assembleDebug # debug APK -./gradlew :app:testDebugUnitTest # JVM unit tests for the engine +./gradlew :app:testDebugUnitTest # JVM unit tests ./gradlew :app:lintDebug # Android Lint ./gradlew :app:assembleRelease # R8-minified release APK ./gradlew :app:bundleRelease # Play-ready .aab ``` +### AdMob / Pro configuration + +Debug builds default to Google's public **test** ad ids, which are safe to click +and produce no revenue. A release build needs real ids and — if the app was sold as +a paid app — the legacy-Pro cutoff: + +```properties +# local.properties (git-ignored) +admob.appId=ca-app-pub-XXXXXXXXXXXXXXXX~YYYYYYYYYY +admob.bannerUnitId=ca-app-pub-XXXXXXXXXXXXXXXX/NNNNNNNNNN +legacyPro.cutoffEpochMs=1793491200000 # first freemium release, epoch ms +``` + +The Gradle build warns while test ids or a zero cutoff are still in use. The full +AdMob, UMP, Play Console and Data Safety setup is in +[`docs/MONETIZATION.md`](docs/MONETIZATION.md). + ### Installing on a device ```bash @@ -137,9 +173,13 @@ Banding gives *exact* candidate recall for pHash distances up to 7 (see the comm | `WRITE_EXTERNAL_STORAGE` (**API ≤ 29 only**) | legacy delete path on Android 10 | | `POST_NOTIFICATIONS` (API 33+) | shows the scan-progress notification (optional — the scan runs without it) | | `FOREGROUND_SERVICE` + `FOREGROUND_SERVICE_DATA_SYNC` | keeps a long scan alive while the app is backgrounded | +| `INTERNET` + `ACCESS_NETWORK_STATE` | free-tier ads/consent and the optional Pro purchase | +| `AD_ID` + `ACCESS_ADSERVICES_*` | merged by the Google Mobile Ads SDK; used for advertising | +| `WAKE_LOCK` | merged by the Google Mobile Ads SDK for ad rendering | +| `com.android.vending.BILLING` | merged by Play Billing; used only for `pro_no_ads` | Deletion on Android 11+ always goes through the system consent dialog. The app -never requests `MANAGE_EXTERNAL_STORAGE`. +never requests `MANAGE_EXTERNAL_STORAGE`, and the ad/Billing SDKs never read photos. ### Scanning in the background @@ -154,11 +194,32 @@ foreground service with a progress notification that has a **Cancel** action. So When `POST_NOTIFICATIONS` is denied the scan still works; the notification is simply not shown. +## Free tier, Pro and consent + +- **Free** — all features plus one anchored adaptive banner at the bottom of the + scanner. +- **Pro** — one-time Play Billing product `pro_no_ads`; removes the banner. Price is + read from Play and shown localized; there is no subscription and no account. +- **Consent** — UMP is asked for consent before `MobileAds.initialize()`; a refused + or unresolved consent simply means no ad. Where UMP requires it, **Privacy + options** is available in the Options menu. +- **Existing paid customers** — grandfathered by the earliest `firstInstallTime` of + the new package and the old paid package (`de.softwareapp_hb.fotodup.finder`), + compared with `legacyPro.cutoffEpochMs`. The old app must still be installed on the + first freemium launch; otherwise use a promo code or support flow. + +The entitlement is cached locally so an already-Pro install opens ad-free offline; +Play is re-queried on resume and is authoritative when it answers. The trade-off is +that this is a client-side entitlement — there is no backend or account. + +Full setup, Play Console steps, Data Safety answers and testing matrix: +[`docs/MONETIZATION.md`](docs/MONETIZATION.md). + ## Testing -`app/src/test` holds JVM unit tests for `core/`: SHA-256 test vectors, dHash bit -patterns, Hamming distance, exact/perceptual grouping, aspect-ratio filtering and -the reclaimable-bytes maths. +`app/src/test` holds JVM unit tests for `core/` (hashing, pHash/RGB dHash, +grouping, thresholds), `data/BoundedCall`, the Robolectric end-to-end scan, and the +pure monetisation rules (`AdPolicyTest`, `LegacyProTest`). ```bash ./gradlew :app:testDebugUnitTest @@ -170,17 +231,33 @@ hand or with `adb shell input tap`. That is how the store screenshots are taken; shot on AOSP AVDs running in **software emulation**, because this machine exposes no `/dev/kvm` (see [docs/STORE_LISTING.md](docs/STORE_LISTING.md)). +Ads and Billing cannot be completed on an AOSP emulator: it has no Play services. Use a real device +with Play services for ads, and an internal-testing track plus a license tester for a purchase. +For the free/Pro UI split without a purchase, use the debug-only broadcast: + +```bash +adb shell am broadcast -a de.softwareapp_hb.fotodup.finder.debug.GRANT_PRO \ + -n de.softwareapp_hb.fotodup.finder.free.debug/de.softwareapp_hb.fotodup.finder.debug.DebugProToggle +adb shell am broadcast -a de.softwareapp_hb.fotodup.finder.debug.REVOKE_PRO \ + -n de.softwareapp_hb.fotodup.finder.free.debug/de.softwareapp_hb.fotodup.finder.debug.DebugProToggle +``` + ## Releasing to Google Play See [docs/PLAY_RELEASE_CHECKLIST.md](docs/PLAY_RELEASE_CHECKLIST.md) (signing, store listing, Data Safety, release notes, rollout), [docs/STORE_LISTING.md](docs/STORE_LISTING.md) (ready-to-paste listing copy plus the icon / feature graphic generators), [docs/AD_COPY.md](docs/AD_COPY.md) (the Google Ads headlines and descriptions, with a -character-count check) and [PRIVACY.md](PRIVACY.md). +character-count check), [`docs/MONETIZATION.md`](docs/MONETIZATION.md) and +[PRIVACY.md](PRIVACY.md). -The app is published as a **one-time paid app** — no ads, no subscription, no in-app purchases, and -therefore no Billing code or `com.android.vending.BILLING` permission in the APK: the price lives on -the listing, not in the build ([why](docs/STORE_LISTING.md#app-pricing)). +The app is **freemium** and uses the new applicationId +`de.softwareapp_hb.fotodup.finder.free`, so publish it as a **new free Play listing**; +the old paid listing at `.finder` is untouched. Create and activate the one-time +in-app product `pro_no_ads` on the new listing, and update the **Ads**, +**Advertising ID** and **Data Safety** declarations. Existing paid installs are +grandfathered via the legacy cutoff when the old app is still installed on the first +freemium launch. The old “pay once / no ads / no INTERNET” copy is historical. The upload-ready graphics and screenshots live in [`store-assets/`](store-assets/). `tools/make-store-assets.sh` regenerates the Play icon and feature graphic *and* the Google Ads @@ -230,12 +307,23 @@ Byte units ("KB", "MB") and the duration formatter are intentionally left unloca - The Aggressive policy may miss some pairs because of the banded candidate search. - The very first scan of a huge library (50k+ photos) takes a while; later scans reuse the hash index and are much faster. +- The Pro entitlement is **client-side** and can be tampered with on a rooted + device. There is no account or backend to verify it server-side. +- Ads and Billing need Google Play services; an AOSP emulator shows no banner and + cannot complete a purchase. The scanner still works there. +- Grandfathering a paid install is best-effort: the old paid app must still be installed + on the first freemium launch, and uninstall/reinstall, cleared data or a backup restore + that resets `firstInstallTime` can lose it. +- The committed store screenshots and feature graphic predate the banner and Pro + sheet; they need a re-shoot before the freemium listing goes live. ## Roadmap -The project is tracked against a milestone plan (M0–M10). What is done, what remains, +The project is tracked against a milestone plan (M0–M11). What is done, what remains, the current release blockers and the candidate features all live in -[docs/ROADMAP.md](docs/ROADMAP.md). +[docs/ROADMAP.md](docs/ROADMAP.md). The architecture map is +[docs/codemap.md](docs/codemap.md) / [docs/codemap.mmd](docs/codemap.mmd), and +agent rules are in [AGENTS.md](AGENTS.md). ## Licence diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 222e38e..49d4741 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -36,16 +36,68 @@ if (hasReleaseSigning) { } } +// --- Monetisation configuration -------------------------------------------------------------- +// +// Real AdMob IDs and the legacy-Pro cutoff are machine/release specific, so they never live in +// version control. Put them in `local.properties` (git-ignored) or pass them on the command line: +// +// admob.appId=ca-app-pub-XXXXXXXXXXXXXXXX~YYYYYYYYYY +// admob.bannerUnitId=ca-app-pub-XXXXXXXXXXXXXXXX/NNNNNNNNNN +// legacyPro.cutoffEpochMs=1760918400000 +// +// The defaults are Google's public test IDs, which are safe to click and produce no revenue. +// A release build that still uses a test ID is almost certainly a misconfiguration, hence the +// warning below. See docs/MONETIZATION.md for the complete setup. +val localProperties = Properties().apply { + val file = rootProject.file("local.properties") + if (file.exists()) file.inputStream().use { load(it) } +} + +fun configValue(key: String, default: String): String = + (project.findProperty(key) as String?)?.takeIf { it.isNotBlank() } + ?: localProperties.getProperty(key)?.takeIf { it.isNotBlank() } + ?: default + +val testAdMobAppId = "ca-app-pub-3940256099942544~3347511713" +val testAdMobBannerUnitId = "ca-app-pub-3940256099942544/9214589741" +val adMobAppId = configValue("admob.appId", testAdMobAppId) +val adMobBannerUnitId = configValue("admob.bannerUnitId", testAdMobBannerUnitId) +val legacyProCutoffEpochMs = configValue("legacyPro.cutoffEpochMs", "0").toLongOrNull() ?: 0L + +if (adMobAppId == testAdMobAppId || adMobBannerUnitId == testAdMobBannerUnitId) { + logger.warn( + "AdMob is using Google's TEST ids. Set admob.appId and admob.bannerUnitId in " + + "local.properties (or -Padmob.appId=... -Padmob.bannerUnitId=...) before a release build.", + ) +} +if (legacyProCutoffEpochMs <= 0L) { + logger.warn( + "legacyPro.cutoffEpochMs is unset: installs that predate the freemium release will NOT " + + "be grandfathered into Pro. Set it before shipping if the app was sold as a paid app.", + ) +} + android { namespace = "de.softwareapp_hb.fotodup.finder" compileSdk = 36 defaultConfig { - applicationId = "de.softwareapp_hb.fotodup.finder" + // The installed package. This is intentionally different from `namespace`: + // the code package stays `de.softwareapp_hb.fotodup.finder`, while the Play + // listing is a new app at `.free`. Relative manifest class names resolve + // against the namespace, so `.MainActivity` still means the existing class. + applicationId = "de.softwareapp_hb.fotodup.finder.free" minSdk = 26 targetSdk = 36 - versionCode = 3 - versionName = "1.0.2" + versionCode = 4 + versionName = "1.1.0" + + // AdMob reads its application id from the manifest, so it has to be a placeholder: + // the value differs between a developer machine, CI and a release build. + manifestPlaceholders["admobAppId"] = adMobAppId + + buildConfigField("String", "ADMOB_BANNER_UNIT_ID", "\"$adMobBannerUnitId\"") + buildConfigField("long", "LEGACY_PRO_CUTOFF_EPOCH_MS", "${legacyProCutoffEpochMs}L") vectorDrawables { useSupportLibrary = true @@ -93,6 +145,8 @@ android { buildFeatures { compose = true + // AdMob unit id + legacy-Pro cutoff are injected here. + buildConfig = true } testOptions { @@ -186,6 +240,13 @@ dependencies { implementation(libs.kotlinx.coroutines.android) implementation(libs.coil.compose) + // Free tier: AdMob banner + UMP consent. Pro tier: one-time Play Billing product. + // The ads SDK merges INTERNET, ACCESS_NETWORK_STATE, AD_ID and the Privacy Sandbox + // permissions into the release manifest; billing-ktx merges com.android.vending.BILLING. + implementation(libs.play.services.ads) + implementation(libs.user.messaging.platform) + implementation(libs.billing.ktx) + debugImplementation(libs.androidx.compose.ui.tooling) testImplementation(libs.junit) diff --git a/app/src/debug/AndroidManifest.xml b/app/src/debug/AndroidManifest.xml index feebe44..aee21e2 100644 --- a/app/src/debug/AndroidManifest.xml +++ b/app/src/debug/AndroidManifest.xml @@ -7,7 +7,7 @@ receiver lets a scan be driven over adb instead: adb shell am broadcast -a de.softwareapp_hb.fotodup.finder.debug.START_SCAN \ - -n de.softwareapp_hb.fotodup.finder.debug/de.softwareapp_hb.fotodup.finder.debug.DebugScanTrigger + -n de.softwareapp_hb.fotodup.finder.free.debug/de.softwareapp_hb.fotodup.finder.debug.DebugScanTrigger Verified absent from the release manifest by the permission/receiver audit in docs/PLAY_RELEASE_CHECKLIST.md § 5. @@ -25,7 +25,7 @@ MANAGE_EXTERNAL_STORAGE allow`), and MediaProvider honours it, which is enough to exercise the real scan over the device's photo library: - adb shell appops set de.softwareapp_hb.fotodup.finder.debug MANAGE_EXTERNAL_STORAGE allow + adb shell appops set de.softwareapp_hb.fotodup.finder.free.debug MANAGE_EXTERNAL_STORAGE allow The release manifest must never contain this permission — re-check it with the audit command in docs/PLAY_RELEASE_CHECKLIST.md § 5. @@ -39,6 +39,10 @@ android:name=".debug.DebugScanTrigger" android:exported="true" tools:ignore="ExportedReceiver" /> + diff --git a/app/src/debug/java/de/softwareapp_hb/fotodup/finder/debug/DebugProToggle.kt b/app/src/debug/java/de/softwareapp_hb/fotodup/finder/debug/DebugProToggle.kt new file mode 100644 index 0000000..5ed8b4a --- /dev/null +++ b/app/src/debug/java/de/softwareapp_hb/fotodup/finder/debug/DebugProToggle.kt @@ -0,0 +1,55 @@ +package de.softwareapp_hb.fotodup.finder.debug + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.util.Log +import de.softwareapp_hb.fotodup.finder.FotoDupApplication + +/** + * Debug-only hook for the free/Pro UI split. + * + * A debug build cannot complete a Play purchase without being uploaded to a testing + * track and signed into a license-tester account, so this lets the Pro sheet and the + * banner gate be exercised over adb: + * + * adb shell am broadcast -a de.softwareapp_hb.fotodup.finder.debug.GRANT_PRO \ + * -n de.softwareapp_hb.fotodup.finder.free.debug/de.softwareapp_hb.fotodup.finder.debug.DebugProToggle + * + * This class lives in the debug source set and is absent from a release build. + */ +class DebugProToggle : BroadcastReceiver() { + + override fun onReceive(context: Context, intent: Intent) { + val app = context.applicationContext as? FotoDupApplication ?: return + when (intent.action) { + ACTION_GRANT_PRO -> { + app.proStore.debugSetPro(true) + report(app) + } + + ACTION_REVOKE_PRO -> { + app.proStore.debugSetPro(false) + report(app) + } + + ACTION_REPORT_STATE -> report(app) + } + } + + private fun report(app: FotoDupApplication) { + Log.i( + TAG, + "PRO isPro=${app.proStore.state.value.isPro} " + + "billing=${app.proStore.state.value.billingAvailable} " + + "ads=${app.adsController.state.value}", + ) + } + + companion object { + const val ACTION_GRANT_PRO = "de.softwareapp_hb.fotodup.finder.debug.GRANT_PRO" + const val ACTION_REVOKE_PRO = "de.softwareapp_hb.fotodup.finder.debug.REVOKE_PRO" + const val ACTION_REPORT_STATE = "de.softwareapp_hb.fotodup.finder.debug.REPORT_PRO_STATE" + const val TAG = "FotoDupDebug" + } +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 0b0fa52..30bffa6 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -31,6 +31,26 @@ + + + + + + + + + + + + + + = _state.asStateFlow() + + @Volatile + private var started = false + + /** + * Requests a consent update, shows the form if UMP requires one, then initialises + * Mobile Ads. Safe to call from every activity creation: only the first call does work. + * + * A Pro user never reaches this class (see MainActivity), so buying Pro also stops + * the ad SDK from being initialised on the next launch. + */ + fun ensureInitialized(activity: Activity) { + if (started) return + started = true + + val params = ConsentRequestParameters.Builder().build() + consentInformation.requestConsentInfoUpdate( + activity, + params, + { + UserMessagingPlatform.loadAndShowConsentFormIfRequired(activity) { formError -> + val canRequestAds = consentInformation.canRequestAds() + _state.update { + it.copy( + canRequestAds = canRequestAds, + privacyOptionsRequired = privacyOptionsRequired(), + error = formError?.message, + ) + } + if (canRequestAds) initializeMobileAds() + } + }, + { requestError -> + // Consent lookup needs the network. If it fails, keep the app usable and + // only request ads when UMP already has a usable answer. + val canRequestAds = consentInformation.canRequestAds() + Log.i(TAG, "Consent update failed: ${requestError.message}") + _state.update { + it.copy( + canRequestAds = canRequestAds, + privacyOptionsRequired = privacyOptionsRequired(), + error = requestError.message, + ) + } + if (canRequestAds) initializeMobileAds() + }, + ) + } + + /** + * Shows the UMP privacy-options form. The menu item is only offered when UMP says + * the form is required; calling it without that requirement would be a no-op error. + */ + fun showPrivacyOptions(activity: Activity, onFinished: (String?) -> Unit) { + if (!privacyOptionsRequired()) { + onFinished(null) + return + } + UserMessagingPlatform.showPrivacyOptionsForm(activity) { formError -> + val canRequestAds = consentInformation.canRequestAds() + _state.update { + it.copy( + canRequestAds = canRequestAds, + privacyOptionsRequired = privacyOptionsRequired(), + error = formError?.message, + ) + } + if (canRequestAds) initializeMobileAds() + onFinished(formError?.message) + } + } + + private fun privacyOptionsRequired(): Boolean = + consentInformation.privacyOptionsRequirementStatus == + ConsentInformation.PrivacyOptionsRequirementStatus.REQUIRED + + private fun initializeMobileAds() { + if (_state.value.initialized) return + try { + MobileAds.initialize(appContext) { + _state.update { it.copy(initialized = true) } + } + } catch (e: Exception) { + // A missing/invalid AdMob application id or an unavailable Play services + // install must not take the scanner down with it. + Log.w(TAG, "Mobile Ads initialization failed", e) + _state.update { it.copy(error = e.message) } + } + } + + private companion object { + const val TAG = "FotoDupAds" + } +} diff --git a/app/src/main/java/de/softwareapp_hb/fotodup/finder/monetization/AdsState.kt b/app/src/main/java/de/softwareapp_hb/fotodup/finder/monetization/AdsState.kt new file mode 100644 index 0000000..74fbb25 --- /dev/null +++ b/app/src/main/java/de/softwareapp_hb/fotodup/finder/monetization/AdsState.kt @@ -0,0 +1,12 @@ +package de.softwareapp_hb.fotodup.finder.monetization + +/** State of the UMP consent + Mobile Ads initialization pipeline. */ +data class AdsState( + /** MobileAds.initialize() has completed. */ + val initialized: Boolean = false, + /** UMP says an ad request is permitted (consent granted, or not required). */ + val canRequestAds: Boolean = false, + /** The UMP privacy-options form must be reachable from the UI. */ + val privacyOptionsRequired: Boolean = false, + val error: String? = null, +) diff --git a/app/src/main/java/de/softwareapp_hb/fotodup/finder/monetization/LegacyPro.kt b/app/src/main/java/de/softwareapp_hb/fotodup/finder/monetization/LegacyPro.kt new file mode 100644 index 0000000..d167cf5 --- /dev/null +++ b/app/src/main/java/de/softwareapp_hb/fotodup/finder/monetization/LegacyPro.kt @@ -0,0 +1,27 @@ +package de.softwareapp_hb.fotodup.finder.monetization + +/** + * Grandfathering for customers who bought the app before it became freemium. + * + * There is no server and no account, so Play cannot tell us whether this install was + * bought as a paid app. The install timestamp is the best signal available: the + * earliest install of the new freemium package and the old paid package is compared + * with the first freemium release. An older install keeps the ad-free tier. Set + * `legacyPro.cutoffEpochMs` to that release instant before shipping; a cutoff of 0 + * disables the migration. + * + * Limitation: the old paid app must still be installed on the first freemium launch. + * Uninstall/reinstall, clearing data, or a restore that resets `firstInstallTime` + * loses the grandfather. That is documented in PRIVACY.md and MONETIZATION.md. + */ +object LegacyPro { + /** + * The old paid app's package. The freemium build is a separate package + * (`…finder.free`), so the only way to see an existing paid install is to query + * this package explicitly (declared in `` in the manifest). + */ + const val OLD_PAID_PACKAGE = "de.softwareapp_hb.fotodup.finder" + + fun isLegacyInstall(firstInstallTimeMs: Long, cutoffEpochMs: Long): Boolean = + cutoffEpochMs > 0L && firstInstallTimeMs > 0L && firstInstallTimeMs < cutoffEpochMs +} diff --git a/app/src/main/java/de/softwareapp_hb/fotodup/finder/monetization/ProProduct.kt b/app/src/main/java/de/softwareapp_hb/fotodup/finder/monetization/ProProduct.kt new file mode 100644 index 0000000..631a858 --- /dev/null +++ b/app/src/main/java/de/softwareapp_hb/fotodup/finder/monetization/ProProduct.kt @@ -0,0 +1,19 @@ +package de.softwareapp_hb.fotodup.finder.monetization + +/** + * The one product that removes the free tier's banner. + * + * This id must match the active **in-app product** created in the Play Console + * (`Monetise > Products > In-app products`). It is a non-consumable one-time product: + * once bought, [ProStore] keeps it by querying Play on every launch and caches the + * answer locally so the app still opens ad-free while offline. + */ +object ProProduct { + const val ID = "pro_no_ads" + + const val PREFS_NAME = "pro_entitlement" + const val KEY_IS_PRO = "is_pro" + const val KEY_LEGACY_PRO = "legacy_pro" + const val KEY_ORIGIN_RESOLVED = "install_origin_resolved" + const val KEY_PENDING_ACK = "pending_ack_token" +} diff --git a/app/src/main/java/de/softwareapp_hb/fotodup/finder/monetization/ProState.kt b/app/src/main/java/de/softwareapp_hb/fotodup/finder/monetization/ProState.kt new file mode 100644 index 0000000..5ad59da --- /dev/null +++ b/app/src/main/java/de/softwareapp_hb/fotodup/finder/monetization/ProState.kt @@ -0,0 +1,15 @@ +package de.softwareapp_hb.fotodup.finder.monetization + +/** Everything the Pro sheet and the ad gate need to render. */ +data class ProState( + /** True for a Play purchase or a grandfathered paid-app install. */ + val isPro: Boolean = false, + /** Localized one-time price from Play, e.g. "€2.99". Null until Play answers. */ + val priceText: String? = null, + /** True once a Play Billing connection has been established. */ + val billingAvailable: Boolean = false, + /** A purchase flow is in flight (or waiting for product details). */ + val purchaseInProgress: Boolean = false, + /** One-shot user-facing message, consumed by the screen's snackbar. */ + val message: String? = null, +) diff --git a/app/src/main/java/de/softwareapp_hb/fotodup/finder/monetization/ProStore.kt b/app/src/main/java/de/softwareapp_hb/fotodup/finder/monetization/ProStore.kt new file mode 100644 index 0000000..e583b81 --- /dev/null +++ b/app/src/main/java/de/softwareapp_hb/fotodup/finder/monetization/ProStore.kt @@ -0,0 +1,458 @@ +package de.softwareapp_hb.fotodup.finder.monetization + +import android.app.Activity +import android.content.Context +import android.content.pm.PackageManager +import android.os.Build +import android.util.Log +import androidx.core.content.edit +import com.android.billingclient.api.AcknowledgePurchaseParams +import com.android.billingclient.api.BillingClient +import com.android.billingclient.api.BillingClientStateListener +import com.android.billingclient.api.BillingFlowParams +import com.android.billingclient.api.BillingResult +import com.android.billingclient.api.PendingPurchasesParams +import com.android.billingclient.api.ProductDetails +import com.android.billingclient.api.Purchase +import com.android.billingclient.api.QueryProductDetailsParams +import com.android.billingclient.api.QueryPurchasesParams +import de.softwareapp_hb.fotodup.finder.BuildConfig +import de.softwareapp_hb.fotodup.finder.R +import java.lang.ref.WeakReference +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update + +/** + * Process-scoped owner of the Pro entitlement. + * + * It has three inputs: + * - the local cache, so an already-Pro install opens ad-free even while offline; + * - Play Billing, which is authoritative when it answers; + * - the legacy install cutoff, which grandfathers customers who paid for the app + * before it became freemium. + * + * There is no backend on purpose: the app has no account and its core promise is that + * photos never leave the device. The consequence is that the entitlement is a local + * claim and can be tampered with by a rooted device; that trade-off is documented in + * PRIVACY.md and docs/MONETIZATION.md. + */ +class ProStore(context: Context) { + + private val appContext = context.applicationContext + private val prefs = appContext.getSharedPreferences(ProProduct.PREFS_NAME, Context.MODE_PRIVATE) + + private val _state = MutableStateFlow( + ProState( + isPro = prefs.getBoolean(ProProduct.KEY_IS_PRO, false) || + prefs.getBoolean(ProProduct.KEY_LEGACY_PRO, false), + ), + ) + val state: StateFlow = _state.asStateFlow() + + private var billingClient: BillingClient? = null + private var productDetails: ProductDetails? = null + private var connecting = false + private var lastQueryAtMs = 0L + private var pendingPurchaseActivity: WeakReference? = null + + init { + resolveLegacyEntitlement() + connect() + } + + /** + * Starts the one-time purchase flow. + * + * Play product details are queried lazily; if the user taps before the first query + * has returned, the activity is remembered and the flow is launched as soon as the + * details arrive. + */ + fun purchase(activity: Activity) { + if (_state.value.isPro) { + _state.update { it.copy(message = appContext.getString(R.string.message_pro_already)) } + return + } + if (_state.value.purchaseInProgress) return + + val details = productDetails + if (details != null) { + launchPurchase(activity, details) + return + } + + val client = billingClient + if (client == null || !client.isReady) { + _state.update { + it.copy(message = appContext.getString(R.string.message_purchase_unavailable)) + } + connect() + return + } + + pendingPurchaseActivity = WeakReference(activity) + _state.update { it.copy(purchaseInProgress = true, message = null) } + queryProductDetails() + } + + /** Re-queries Play for an existing purchase. [restore] adds a user-facing outcome message. */ + fun refreshPurchases(force: Boolean = false, restore: Boolean = false) { + val now = System.currentTimeMillis() + if (!force && now - lastQueryAtMs < REFRESH_THROTTLE_MS) return + lastQueryAtMs = now + + val client = billingClient + if (client == null || !client.isReady) { + if (restore) { + _state.update { + it.copy(message = appContext.getString(R.string.message_purchase_unavailable)) + } + } + connect() + return + } + + val params = QueryPurchasesParams.newBuilder() + .setProductType(BillingClient.ProductType.INAPP) + .build() + client.queryPurchasesAsync(params) { result, purchases -> + if (result.responseCode != BillingClient.BillingResponseCode.OK) { + Log.i(TAG, "Purchase query failed: ${result.responseCode} ${result.debugMessage}") + if (restore) { + _state.update { + it.copy(message = appContext.getString(R.string.message_purchase_unavailable)) + } + } + return@queryPurchasesAsync + } + + val proPurchase = purchases.firstOrNull { ProProduct.ID in it.products } + if (proPurchase == null) { + // Only a successful Play query may revoke Pro. A legacy grant is + // independent of Play and is never removed here. + if (!prefs.getBoolean(ProProduct.KEY_LEGACY_PRO, false)) { + persistPro(false) + } + _state.update { it.copy(purchaseInProgress = false) } + if (restore) { + _state.update { + it.copy( + message = appContext.getString( + if (it.isPro) { + R.string.message_pro_already + } else { + R.string.message_purchase_not_found + }, + ), + ) + } + } + } else { + applyPurchase(proPurchase) + if (restore && proPurchase.purchaseState == Purchase.PurchaseState.PURCHASED) { + _state.update { + it.copy(message = appContext.getString(R.string.message_purchase_restored)) + } + } + } + retryPendingAcknowledgement() + } + } + + fun dismissMessage() = _state.update { it.copy(message = null) } + + // --- Billing connection ------------------------------------------------------------------- + + private fun connect() { + if (connecting || billingClient?.isReady == true) return + connecting = true + + billingClient?.endConnection() + billingClient = BillingClient.newBuilder(appContext) + .setListener { result, purchases -> onPurchasesUpdated(result, purchases) } + .enablePendingPurchases( + PendingPurchasesParams.newBuilder() + .enableOneTimeProducts() + .build(), + ) + .build() + + billingClient?.startConnection( + object : BillingClientStateListener { + override fun onBillingSetupFinished(result: BillingResult) { + connecting = false + val available = result.responseCode == BillingClient.BillingResponseCode.OK + _state.update { it.copy(billingAvailable = available) } + if (available) { + queryProductDetails() + refreshPurchases(force = true) + } else { + Log.i( + TAG, + "Billing unavailable: ${result.responseCode} ${result.debugMessage}", + ) + failPendingPurchase() + } + } + + override fun onBillingServiceDisconnected() { + connecting = false + _state.update { it.copy(billingAvailable = false) } + } + }, + ) + } + + private fun queryProductDetails() { + val client = billingClient + if (client == null || !client.isReady) { + failPendingPurchase() + return + } + + val params = QueryProductDetailsParams.newBuilder() + .setProductList( + listOf( + QueryProductDetailsParams.Product.newBuilder() + .setProductId(ProProduct.ID) + .setProductType(BillingClient.ProductType.INAPP) + .build(), + ), + ) + .build() + + client.queryProductDetailsAsync(params) { result, details -> + if (result.responseCode != BillingClient.BillingResponseCode.OK) { + Log.i( + TAG, + "Product details unavailable: ${result.responseCode} ${result.debugMessage}", + ) + failPendingPurchase() + return@queryProductDetailsAsync + } + + val detail = details.productDetailsList.firstOrNull { it.productId == ProProduct.ID } + productDetails = detail + val price = detail?.oneTimePurchaseOfferDetails?.formattedPrice + ?: detail?.oneTimePurchaseOfferDetailsList?.firstOrNull()?.formattedPrice + _state.update { it.copy(priceText = price, billingAvailable = true) } + + val activity = pendingPurchaseActivity?.get() + pendingPurchaseActivity = null + if (detail == null) { + failPendingPurchase() + } else if (activity != null) { + launchPurchase(activity, detail) + } + } + } + + // --- Purchases ---------------------------------------------------------------------------- + + private fun launchPurchase(activity: Activity, details: ProductDetails) { + if (activity.isFinishing || activity.isDestroyed) { + _state.update { it.copy(purchaseInProgress = false) } + return + } + + val params = BillingFlowParams.newBuilder() + .setProductDetailsParamsList( + listOf( + BillingFlowParams.ProductDetailsParams.newBuilder() + .setProductDetails(details) + .build(), + ), + ) + .build() + + val result = billingClient?.launchBillingFlow(activity, params) + if (result == null || result.responseCode != BillingClient.BillingResponseCode.OK) { + _state.update { + it.copy( + purchaseInProgress = false, + message = appContext.getString(R.string.message_purchase_unavailable), + ) + } + } + // On OK the Play sheet owns the flow; onPurchasesUpdated() finishes the state. + } + + private fun onPurchasesUpdated(result: BillingResult, purchases: MutableList?) { + when (result.responseCode) { + BillingClient.BillingResponseCode.OK -> { + purchases?.forEach(::applyPurchase) + _state.update { it.copy(purchaseInProgress = false) } + } + + BillingClient.BillingResponseCode.USER_CANCELED -> { + _state.update { it.copy(purchaseInProgress = false) } + } + + BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED -> { + _state.update { it.copy(purchaseInProgress = false) } + refreshPurchases(force = true, restore = true) + } + + else -> { + Log.i( + TAG, + "Purchase failed: ${result.responseCode} ${result.debugMessage}", + ) + _state.update { + it.copy( + purchaseInProgress = false, + message = appContext.getString(R.string.message_purchase_failed), + ) + } + } + } + } + + // --- Entitlement -------------------------------------------------------------------------- + + private fun applyPurchase(purchase: Purchase) { + if (ProProduct.ID !in purchase.products) return + + when (purchase.purchaseState) { + Purchase.PurchaseState.PURCHASED -> { + val wasPro = _state.value.isPro + persistPro(true) + if (!wasPro) { + _state.update { + it.copy(message = appContext.getString(R.string.message_ads_removed)) + } + } + if (purchase.isAcknowledged) { + prefs.edit { remove(ProProduct.KEY_PENDING_ACK) } + } else { + prefs.edit { putString(ProProduct.KEY_PENDING_ACK, purchase.purchaseToken) } + acknowledge(purchase.purchaseToken) + } + } + + Purchase.PurchaseState.PENDING -> { + _state.update { + it.copy( + purchaseInProgress = false, + message = appContext.getString(R.string.message_purchase_pending), + ) + } + } + + else -> Unit + } + } + + private fun acknowledge(token: String) { + val client = billingClient + if (client == null || !client.isReady) return + val params = AcknowledgePurchaseParams.newBuilder() + .setPurchaseToken(token) + .build() + client.acknowledgePurchase(params) { result -> + if (result.responseCode == BillingClient.BillingResponseCode.OK) { + prefs.edit { remove(ProProduct.KEY_PENDING_ACK) } + } else { + // The purchase is still granted locally; Play retries the acknowledgement + // on the next launch through KEY_PENDING_ACK. Without this retry Play + // refunds an unacknowledged purchase after three days. + Log.i( + TAG, + "Acknowledge failed: ${result.responseCode} ${result.debugMessage}", + ) + } + } + } + + private fun retryPendingAcknowledgement() { + val token = prefs.getString(ProProduct.KEY_PENDING_ACK, null) ?: return + acknowledge(token) + } + + private fun persistPro(value: Boolean) { + prefs.edit { putBoolean(ProProduct.KEY_IS_PRO, value) } + _state.update { it.copy(isPro = value) } + } + + private fun failPendingPurchase() { + val hadPending = pendingPurchaseActivity != null || _state.value.purchaseInProgress + pendingPurchaseActivity = null + if (hadPending) { + _state.update { + it.copy( + purchaseInProgress = false, + message = appContext.getString(R.string.message_purchase_unavailable), + ) + } + } else { + _state.update { it.copy(purchaseInProgress = false) } + } + } + + // --- Legacy paid-app migration ------------------------------------------------------------ + + private fun resolveLegacyEntitlement() { + if (prefs.getBoolean(ProProduct.KEY_ORIGIN_RESOLVED, false)) return + + val legacy = LegacyPro.isLegacyInstall( + firstInstallTimeMs = earliestInstallTimeMs(), + cutoffEpochMs = BuildConfig.LEGACY_PRO_CUTOFF_EPOCH_MS, + ) + prefs.edit { + putBoolean(ProProduct.KEY_ORIGIN_RESOLVED, true) + putBoolean(ProProduct.KEY_LEGACY_PRO, legacy) + } + + if (legacy) { + prefs.edit { putBoolean(ProProduct.KEY_IS_PRO, true) } + _state.update { it.copy(isPro = true) } + } + } + + /** + * The freemium app is a separate package, so its own first-install time can never + * predate the cutoff. It also checks the old paid package when that app is still + * installed; that is the only cross-package signal available without a backend. + */ + private fun earliestInstallTimeMs(): Long { + val own = firstInstallTimeMs(appContext.packageName) + val oldPaid = firstInstallTimeMs(LegacyPro.OLD_PAID_PACKAGE) + return listOf(own, oldPaid).filter { it > 0L }.minOrNull() ?: 0L + } + + @Suppress("DEPRECATION") + private fun firstInstallTimeMs(packageName: String): Long = try { + val info = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + appContext.packageManager.getPackageInfo( + packageName, + PackageManager.PackageInfoFlags.of(0L), + ) + } else { + appContext.packageManager.getPackageInfo(packageName, 0) + } + info.firstInstallTime + } catch (e: PackageManager.NameNotFoundException) { + 0L + } + + // --- Debug tooling ------------------------------------------------------------------------ + + /** + * Debug-only entitlement override, driven by [de.softwareapp_hb.fotodup.finder.debug.DebugProToggle]. + * Not called from the app; R8 removes it from a release build. It exists so the Pro UI and + * the banner gate can be exercised without a Play-enabled device and a real purchase. + */ + fun debugSetPro(value: Boolean) { + prefs.edit { + putBoolean(ProProduct.KEY_IS_PRO, value) + putBoolean(ProProduct.KEY_LEGACY_PRO, value) + } + _state.update { it.copy(isPro = value, message = null) } + } + + private companion object { + const val TAG = "FotoDupPro" + const val REFRESH_THROTTLE_MS = 15_000L + } +} diff --git a/app/src/main/java/de/softwareapp_hb/fotodup/finder/ui/ads/BannerAdSlot.kt b/app/src/main/java/de/softwareapp_hb/fotodup/finder/ui/ads/BannerAdSlot.kt new file mode 100644 index 0000000..bac13b0 --- /dev/null +++ b/app/src/main/java/de/softwareapp_hb/fotodup/finder/ui/ads/BannerAdSlot.kt @@ -0,0 +1,92 @@ +package de.softwareapp_hb.fotodup.finder.ui.ads + +import android.util.Log +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.unit.dp +import androidx.compose.ui.viewinterop.AndroidView +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import androidx.lifecycle.compose.LocalLifecycleOwner +import com.google.android.gms.ads.AdListener +import com.google.android.gms.ads.AdRequest +import com.google.android.gms.ads.AdSize +import com.google.android.gms.ads.AdView +import com.google.android.gms.ads.LoadAdError +import de.softwareapp_hb.fotodup.finder.BuildConfig +import de.softwareapp_hb.fotodup.finder.monetization.AdPolicy + +/** + * The free tier's only ad placement: one anchored adaptive banner at the bottom. + * + * Pro users, users who refused consent, and devices where the SDK could not be + * initialised simply get no view. There is no placeholder and no error surface — + * an unfilled ad must never take space away from the scanner. + */ +@Composable +fun BannerAdSlot( + isPro: Boolean, + canRequestAds: Boolean, + initialized: Boolean, + modifier: Modifier = Modifier, +) { + if (!AdPolicy.shouldShowBanner(isPro, canRequestAds, initialized)) return + + val context = LocalContext.current + val lifecycleOwner = LocalLifecycleOwner.current + + BoxWithConstraints( + modifier = modifier + .fillMaxWidth() + // A little breathing room stops a tap meant for Apply from landing on the ad. + .padding(horizontal = 8.dp, vertical = 4.dp), + ) { + val widthDp = maxWidth.value.toInt() + if (widthDp <= 0) return@BoxWithConstraints + + val adView = remember(widthDp, context) { + AdView(context).apply { + adUnitId = BuildConfig.ADMOB_BANNER_UNIT_ID + val adaptive = AdSize.getLargeAnchoredAdaptiveBannerAdSize(context, widthDp) + setAdSize(if (adaptive != AdSize.INVALID) adaptive else AdSize.BANNER) + adListener = object : AdListener() { + override fun onAdFailedToLoad(error: LoadAdError) { + if (BuildConfig.DEBUG) { + Log.i("FotoDupAds", "Banner failed to load: ${error.message}") + } + } + } + } + } + + // Load after the view has been created by the composition; AdMob refreshes + // banners itself, so this must not run again on recomposition. + LaunchedEffect(adView) { + adView.loadAd(AdRequest.Builder().build()) + } + + DisposableEffect(adView, lifecycleOwner) { + val observer = LifecycleEventObserver { _, event -> + when (event) { + Lifecycle.Event.ON_RESUME -> adView.resume() + Lifecycle.Event.ON_PAUSE -> adView.pause() + else -> Unit + } + } + lifecycleOwner.lifecycle.addObserver(observer) + onDispose { + lifecycleOwner.lifecycle.removeObserver(observer) + adView.destroy() + } + } + + AndroidView(factory = { adView }, modifier = Modifier.fillMaxWidth()) + } +} diff --git a/app/src/main/java/de/softwareapp_hb/fotodup/finder/ui/components/ContextExt.kt b/app/src/main/java/de/softwareapp_hb/fotodup/finder/ui/components/ContextExt.kt new file mode 100644 index 0000000..4b361b5 --- /dev/null +++ b/app/src/main/java/de/softwareapp_hb/fotodup/finder/ui/components/ContextExt.kt @@ -0,0 +1,20 @@ +package de.softwareapp_hb.fotodup.finder.ui.components + +import android.app.Activity +import android.content.Context +import android.content.ContextWrapper + +/** + * Finds the Activity behind a Compose [Context]. + * + * Play Billing's `launchBillingFlow()` needs an Activity, not the application + * context, and UMP's consent forms do too. + */ +fun Context.findActivity(): Activity? { + var context: Context = this + while (context is ContextWrapper) { + if (context is Activity) return context + context = context.baseContext + } + return null +} diff --git a/app/src/main/java/de/softwareapp_hb/fotodup/finder/ui/pro/ProSheet.kt b/app/src/main/java/de/softwareapp_hb/fotodup/finder/ui/pro/ProSheet.kt new file mode 100644 index 0000000..5496f51 --- /dev/null +++ b/app/src/main/java/de/softwareapp_hb/fotodup/finder/ui/pro/ProSheet.kt @@ -0,0 +1,174 @@ +package de.softwareapp_hb.fotodup.finder.ui.pro + +import android.app.Activity +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.rememberModalBottomSheetState +import androidx.compose.runtime.Composable +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.font.FontWeight +import androidx.compose.ui.unit.dp +import de.softwareapp_hb.fotodup.finder.R +import de.softwareapp_hb.fotodup.finder.monetization.ProState +import de.softwareapp_hb.fotodup.finder.ui.components.findActivity + +/** + * The "go Pro" sheet. + * + * Pro is deliberately narrow: it removes the banner and nothing else. Every scan, + * selection and deletion feature stays available for free, so this sheet can never + * become a paywall for the app's actual job. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun ProSheet( + pro: ProState, + onDismiss: () -> Unit, + onBuy: (Activity) -> Unit, + onRestore: () -> Unit, +) { + val activity = LocalContext.current.findActivity() + val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) + + ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 24.dp) + .padding(bottom = 32.dp), + ) { + Text(text = "\u2728", style = MaterialTheme.typography.displaySmall) + Spacer(Modifier.height(8.dp)) + Text( + text = stringResource(R.string.pro_title), + style = MaterialTheme.typography.headlineSmall, + fontWeight = FontWeight.Bold, + ) + Spacer(Modifier.height(4.dp)) + Text( + text = stringResource(R.string.pro_subtitle), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(Modifier.height(20.dp)) + + BenefitRow(stringResource(R.string.pro_benefit_ads)) + BenefitRow(stringResource(R.string.pro_benefit_all_features)) + BenefitRow(stringResource(R.string.pro_benefit_support)) + + pro.message?.let { message -> + Spacer(Modifier.height(12.dp)) + Text( + text = message, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + + Spacer(Modifier.height(24.dp)) + + if (pro.isPro) { + Text( + text = stringResource(R.string.pro_active), + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.primary, + fontWeight = FontWeight.SemiBold, + ) + Spacer(Modifier.height(16.dp)) + Button(onClick = onDismiss, modifier = Modifier.fillMaxWidth()) { + Text(stringResource(R.string.pro_close)) + } + return@Column + } + + Text( + text = if (pro.priceText != null) { + stringResource(R.string.pro_price, pro.priceText) + } else { + stringResource(R.string.pro_price_unknown) + }, + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.SemiBold, + ) + Spacer(Modifier.height(12.dp)) + + Button( + onClick = { activity?.let(onBuy) }, + enabled = activity != null && !pro.purchaseInProgress, + modifier = Modifier.fillMaxWidth(), + ) { + if (pro.purchaseInProgress) { + CircularProgressIndicator( + modifier = Modifier.size(18.dp), + strokeWidth = 2.dp, + ) + Spacer(Modifier.size(10.dp)) + Text(stringResource(R.string.pro_purchasing)) + } else { + Text( + text = if (pro.priceText != null) { + stringResource(R.string.pro_buy_price, pro.priceText) + } else { + stringResource(R.string.pro_buy) + }, + ) + } + } + + TextButton( + onClick = onRestore, + enabled = !pro.purchaseInProgress, + modifier = Modifier.fillMaxWidth(), + ) { + Text(stringResource(R.string.pro_restore)) + } + + if (!pro.billingAvailable && pro.message == null) { + Text( + text = stringResource(R.string.pro_unavailable), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + ) + } + + TextButton(onClick = onDismiss, modifier = Modifier.fillMaxWidth()) { + Text(stringResource(R.string.pro_not_now)) + } + } + } +} + +@Composable +private fun BenefitRow(text: String) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(vertical = 4.dp), + horizontalArrangement = Arrangement.Start, + verticalAlignment = Alignment.Top, + ) { + Text( + text = "\u2713", + color = MaterialTheme.colorScheme.primary, + fontWeight = FontWeight.Bold, + ) + Spacer(Modifier.size(10.dp)) + Text(text = text, style = MaterialTheme.typography.bodyMedium) + } +} diff --git a/app/src/main/java/de/softwareapp_hb/fotodup/finder/ui/scanner/ScannerScreen.kt b/app/src/main/java/de/softwareapp_hb/fotodup/finder/ui/scanner/ScannerScreen.kt index 5d49306..6bc2a15 100644 --- a/app/src/main/java/de/softwareapp_hb/fotodup/finder/ui/scanner/ScannerScreen.kt +++ b/app/src/main/java/de/softwareapp_hb/fotodup/finder/ui/scanner/ScannerScreen.kt @@ -35,6 +35,7 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue 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.font.FontWeight import androidx.compose.ui.unit.dp @@ -46,6 +47,9 @@ import de.softwareapp_hb.fotodup.finder.data.MediaAccess import de.softwareapp_hb.fotodup.finder.data.AppPermissions import de.softwareapp_hb.fotodup.finder.data.humanReadableBytes import de.softwareapp_hb.fotodup.finder.text.labelRes +import de.softwareapp_hb.fotodup.finder.ui.ads.BannerAdSlot +import de.softwareapp_hb.fotodup.finder.ui.components.findActivity +import de.softwareapp_hb.fotodup.finder.ui.pro.ProSheet @Composable fun ScannerScreen(viewModel: ScannerViewModel = viewModel()) { @@ -74,10 +78,51 @@ fun ScannerScreen(viewModel: ScannerViewModel = viewModel()) { } } + var showProSheet by remember { mutableStateOf(false) } + val activity = LocalContext.current.findActivity() + + // While the Pro sheet is open it shows the message inline; only surface it as a + // snackbar once the sheet is gone, so a purchase error cannot hide behind the sheet. + LaunchedEffect(state.pro.message, showProSheet) { + if (!showProSheet) { + state.pro.message?.let { message -> + snackbarHostState.showSnackbar(message) + viewModel.dismissProMessage() + } + } + } + + // A successful purchase flips isPro; close the sheet rather than leaving the + // now-stale "buy" state on screen. + LaunchedEffect(state.pro.isPro) { + if (state.pro.isPro) showProSheet = false + } + Scaffold( - topBar = { ScannerTopBar(state, viewModel) }, + topBar = { + ScannerTopBar( + state = state, + viewModel = viewModel, + onUpgrade = { showProSheet = true }, + onPrivacyOptions = { activity?.let(viewModel::showPrivacyOptions) }, + ) + }, snackbarHost = { SnackbarHost(snackbarHostState) }, - bottomBar = { BottomActionBar(state, viewModel) }, + bottomBar = { + Column( + modifier = Modifier + // Scaffold does not inset a custom bottom bar. Apply the navigation + // inset once here so the action bar and the banner cannot double it. + .navigationBarsPadding(), + ) { + BottomActionBar(state, viewModel) + BannerAdSlot( + isPro = state.pro.isPro, + canRequestAds = state.ads.canRequestAds, + initialized = state.ads.initialized, + ) + } + }, ) { innerPadding -> Column( modifier = Modifier @@ -98,11 +143,25 @@ fun ScannerScreen(viewModel: ScannerViewModel = viewModel()) { } } } + + if (showProSheet) { + ProSheet( + pro = state.pro, + onDismiss = { showProSheet = false }, + onBuy = viewModel::purchasePro, + onRestore = viewModel::restorePro, + ) + } } @OptIn(ExperimentalMaterial3Api::class) @Composable -private fun ScannerTopBar(state: ScannerUiState, viewModel: ScannerViewModel) { +private fun ScannerTopBar( + state: ScannerUiState, + viewModel: ScannerViewModel, + onUpgrade: () -> Unit, + onPrivacyOptions: () -> Unit, +) { var menuOpen by remember { mutableStateOf(false) } TopAppBar( @@ -155,6 +214,34 @@ private fun ScannerTopBar(state: ScannerUiState, viewModel: ScannerViewModel) { menuOpen = false }, ) + HorizontalDivider() + DropdownMenuItem( + text = { + Text( + stringResource( + if (state.pro.isPro) { + R.string.menu_pro_active + } else { + R.string.menu_remove_ads + }, + ), + ) + }, + onClick = { + menuOpen = false + if (!state.pro.isPro) onUpgrade() + }, + enabled = !state.pro.isPro, + ) + if (state.ads.privacyOptionsRequired) { + DropdownMenuItem( + text = { Text(stringResource(R.string.menu_privacy_options)) }, + onClick = { + menuOpen = false + onPrivacyOptions() + }, + ) + } } }, ) @@ -178,9 +265,8 @@ private fun BottomActionBar(state: ScannerUiState, viewModel: ScannerViewModel) Column( modifier = Modifier .fillMaxWidth() - // Reserve room for the system navigation bar: Scaffold does not inset a - // custom bottom bar itself. - .navigationBarsPadding() + // The navigation-bar inset is applied once by the bottom slot in + // ScannerScreen, which also owns the banner below this bar. .padding(horizontal = 16.dp, vertical = 10.dp), ) { if (hasMarked) { diff --git a/app/src/main/java/de/softwareapp_hb/fotodup/finder/ui/scanner/ScannerUiState.kt b/app/src/main/java/de/softwareapp_hb/fotodup/finder/ui/scanner/ScannerUiState.kt index de4c0b1..7795a96 100644 --- a/app/src/main/java/de/softwareapp_hb/fotodup/finder/ui/scanner/ScannerUiState.kt +++ b/app/src/main/java/de/softwareapp_hb/fotodup/finder/ui/scanner/ScannerUiState.kt @@ -5,11 +5,16 @@ import de.softwareapp_hb.fotodup.finder.core.DuplicatePolicy import de.softwareapp_hb.fotodup.finder.data.MediaAccess import de.softwareapp_hb.fotodup.finder.domain.ScanPhase import de.softwareapp_hb.fotodup.finder.domain.ScanResult +import de.softwareapp_hb.fotodup.finder.monetization.AdsState +import de.softwareapp_hb.fotodup.finder.monetization.ProState /** Everything the scanner screen renders. */ data class ScannerUiState( val access: MediaAccess = MediaAccess.NONE, val policy: DuplicatePolicy = DuplicatePolicy.DEFAULT, + /** Free-tier ad gate and Pro purchase state. */ + val pro: ProState = ProState(), + val ads: AdsState = AdsState(), val scanning: Boolean = false, val phase: ScanPhase? = null, val progressDone: Int = 0, diff --git a/app/src/main/java/de/softwareapp_hb/fotodup/finder/ui/scanner/ScannerViewModel.kt b/app/src/main/java/de/softwareapp_hb/fotodup/finder/ui/scanner/ScannerViewModel.kt index ff685fb..5d15b80 100644 --- a/app/src/main/java/de/softwareapp_hb/fotodup/finder/ui/scanner/ScannerViewModel.kt +++ b/app/src/main/java/de/softwareapp_hb/fotodup/finder/ui/scanner/ScannerViewModel.kt @@ -1,5 +1,6 @@ package de.softwareapp_hb.fotodup.finder.ui.scanner +import android.app.Activity import android.app.Application import android.content.IntentSender import androidx.annotation.PluralsRes @@ -13,6 +14,8 @@ import de.softwareapp_hb.fotodup.finder.core.DuplicatePolicy import de.softwareapp_hb.fotodup.finder.data.AppPermissions import de.softwareapp_hb.fotodup.finder.data.MediaDeleter import de.softwareapp_hb.fotodup.finder.domain.ScanState +import de.softwareapp_hb.fotodup.finder.monetization.AdsController +import de.softwareapp_hb.fotodup.finder.monetization.ProStore import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.MutableStateFlow @@ -34,6 +37,8 @@ import kotlinx.coroutines.withContext class ScannerViewModel(application: Application) : AndroidViewModel(application) { private val scanController = (application as FotoDupApplication).scanController + private val proStore: ProStore = (application as FotoDupApplication).proStore + private val adsController: AdsController = (application as FotoDupApplication).adsController private val deleter = MediaDeleter(application) private val _state = MutableStateFlow(ScannerUiState()) @@ -64,6 +69,12 @@ class ScannerViewModel(application: Application) : AndroidViewModel(application) viewModelScope.launch { scanController.state.collect(::onScanState) } + viewModelScope.launch { + proStore.state.collect { pro -> _state.update { it.copy(pro = pro) } } + } + viewModelScope.launch { + adsController.state.collect { ads -> _state.update { it.copy(ads = ads) } } + } } fun refreshAccess() { @@ -78,6 +89,25 @@ class ScannerViewModel(application: Application) : AndroidViewModel(application) fun cancelScan() = scanController.cancel() + // --- Monetisation ------------------------------------------------------------------------ + + /** Opens the Play purchase flow for the one-time "remove ads" product. */ + fun purchasePro(activity: Activity) = proStore.purchase(activity) + + /** Re-queries Play for an existing purchase and reports the outcome in the Pro sheet. */ + fun restorePro() = proStore.refreshPurchases(force = true, restore = true) + + fun dismissProMessage() = proStore.dismissMessage() + + /** Opens the UMP privacy-options form (only offered when UMP requires it). */ + fun showPrivacyOptions(activity: Activity) { + adsController.showPrivacyOptions(activity) { error -> + if (error != null) { + _state.update { it.copy(message = text(R.string.message_privacy_unavailable)) } + } + } + } + private fun onScanState(scan: ScanState) { val freshResult = scan.result?.takeIf { scan.generation != appliedGeneration } if (freshResult != null) appliedGeneration = scan.generation diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 30794d3..f623a72 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -29,13 +29,13 @@ Photo access needed - The app needs permission to read your photos so it can find duplicates. Nothing ever leaves your device. + The app needs permission to read your photos so it can find duplicates. Your photos never leave your device. Limited photo access You granted access to selected photos only. Grant full access to scan your whole library. Find and remove duplicate photos - Fast, ad-free and completely offline. Your photos are never uploaded. + Fast, private and completely on-device. Your photos are never uploaded. The free version is supported by ads; Pro removes them. Reading your photo library… @@ -116,6 +116,36 @@ Nothing was deleted Deletion was not confirmed + + Remove ads + Pro — ads removed + Privacy options + + Remove ads with Pro + One-time purchase. No subscription, no account. + No banner ads + Every duplicate-finding feature stays free + Supports the app\'s development + One-time purchase · %1$s + One-time purchase + Buy Pro + Buy for %1$s + Opening Google Play… + Restore purchase + Not now + Close + Pro is active. Ads are removed. + Purchases are unavailable right now. Check Google Play and your connection, then try again. + + Your purchase is pending. Pro activates once Google Play confirms the payment. + The purchase could not be completed. Please try again. + Purchases are unavailable right now. Check Google Play and your connection. + No purchase was found for this Google account. + Purchase restored. Ads are removed. + Pro is already active on this Google account. + Ads removed. Thank you for supporting the app! + Privacy options are unavailable right now. Please try again later. + Scan progress Shows progress while duplicate photos are being searched for diff --git a/app/src/test/java/de/softwareapp_hb/fotodup/finder/monetization/AdPolicyTest.kt b/app/src/test/java/de/softwareapp_hb/fotodup/finder/monetization/AdPolicyTest.kt new file mode 100644 index 0000000..5bfd9c5 --- /dev/null +++ b/app/src/test/java/de/softwareapp_hb/fotodup/finder/monetization/AdPolicyTest.kt @@ -0,0 +1,29 @@ +package de.softwareapp_hb.fotodup.finder.monetization + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** The free-tier ad gate: Pro, consent and an initialised SDK are all required. */ +class AdPolicyTest { + + @Test + fun `a free, consented, initialised install shows the banner`() { + assertTrue(AdPolicy.shouldShowBanner(isPro = false, canRequestAds = true, initialized = true)) + } + + @Test + fun `pro never shows the banner`() { + assertFalse(AdPolicy.shouldShowBanner(isPro = true, canRequestAds = true, initialized = true)) + } + + @Test + fun `a refused or unresolved consent never shows the banner`() { + assertFalse(AdPolicy.shouldShowBanner(isPro = false, canRequestAds = false, initialized = true)) + } + + @Test + fun `an uninitialised ad sdk never shows the banner`() { + assertFalse(AdPolicy.shouldShowBanner(isPro = false, canRequestAds = true, initialized = false)) + } +} diff --git a/app/src/test/java/de/softwareapp_hb/fotodup/finder/monetization/LegacyProTest.kt b/app/src/test/java/de/softwareapp_hb/fotodup/finder/monetization/LegacyProTest.kt new file mode 100644 index 0000000..2e39066 --- /dev/null +++ b/app/src/test/java/de/softwareapp_hb/fotodup/finder/monetization/LegacyProTest.kt @@ -0,0 +1,40 @@ +package de.softwareapp_hb.fotodup.finder.monetization + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * Grandfathering is an install-time decision. These cases pin the boundaries so a + * reinstall cannot silently turn a paid customer into an ad-supported one, and a + * post-release install cannot silently receive Pro for free. + */ +class LegacyProTest { + + private val cutoff = 1_800_000_000_000L + + @Test + fun `an install before the freemium release is grandfathered`() { + assertTrue(LegacyPro.isLegacyInstall(firstInstallTimeMs = cutoff - 1, cutoffEpochMs = cutoff)) + } + + @Test + fun `an install after the freemium release is not grandfathered`() { + assertFalse(LegacyPro.isLegacyInstall(firstInstallTimeMs = cutoff + 1, cutoffEpochMs = cutoff)) + } + + @Test + fun `an install exactly at the cutoff is not grandfathered`() { + assertFalse(LegacyPro.isLegacyInstall(firstInstallTimeMs = cutoff, cutoffEpochMs = cutoff)) + } + + @Test + fun `a zero cutoff disables the migration`() { + assertFalse(LegacyPro.isLegacyInstall(firstInstallTimeMs = cutoff - 1, cutoffEpochMs = 0L)) + } + + @Test + fun `an unknown install time is not grandfathered`() { + assertFalse(LegacyPro.isLegacyInstall(firstInstallTimeMs = 0L, cutoffEpochMs = cutoff)) + } +} diff --git a/docs/AD_COPY.md b/docs/AD_COPY.md index 36efb95..44a900e 100644 --- a/docs/AD_COPY.md +++ b/docs/AD_COPY.md @@ -6,6 +6,11 @@ only the format is different: an App campaign asset group takes **5 headlines of characters** and **5 descriptions of at most 90 characters**, and Google rotates and recombines them, so every asset has to stand on its own. +> **Current model: freemium.** The app is free to download with one small banner; a one-time Pro +> purchase removes it. The copy and rules in this section reflect that. Strategy notes further down +> that still describe the old paid listing are historical — see +> [MONETIZATION](MONETIZATION.md) and [STORE_LISTING › App pricing](STORE_LISTING.md#app-pricing). + Character counts below are **measured**, not estimated, and are the loading figure (spaces and punctuation included). An em dash and a hyphen are both one character, so swapping `—` for `-` never changes a count. @@ -18,26 +23,25 @@ never changes a count. | 2 | Delete Duplicate Photos | 23 | | 3 | Duplicate Photo Cleaner | 23 | | 4 | Reclaim Storage Fast | 20 | -| 5 | No Ads, No Uploads | 18 | +| 5 | Free With One Small Ad | 22 | Headlines 1–3 carry the search intent (*duplicate photos* — the phrase a user actually types and the one Play's tag list cannot express, see [STORE_LISTING](STORE_LISTING.md#category-and-tags)), -4 carries the benefit, 5 carries the differentiator that no competitor in this category can copy -without rewriting its APK. +4 carries the benefit, 5 states the free/Pro model without pretending the free tier is ad-free. ## Descriptions (max 90 characters) | # | Description | Chars | |---|---|---| | 1 | Find duplicate and near-duplicate photos, keep the best of each, delete the rest safely. | 88 | -| 2 | Ad-free and fully offline. Scans thousands of photos in seconds. Nothing is ever uploaded. | 90 | +| 2 | Free with one small banner; ad-free with Pro. Scans thousands of photos in seconds. | 83 | | 3 | Exact copies and visually similar shots, grouped for you. Android confirms every deletion. | 90 | | 4 | Reclaim gigabytes. Keep the best copy, trash the rest — reversible on demand. | 77 | -| 5 | Pay once, own it — no ads, no subscription, no account. Your photos never leave the phone. | 90 | +| 5 | Free to scan; one-time Pro removes the banner. Your photos never leave the phone. | 81 | The five cover five different angles on purpose, because Google mixes descriptions with any -headline: what it does (1), speed and privacy (2), accuracy and safety (3), the payoff (4), the -commercial promise (5). +headline: what it does (1), the free/Pro model and speed (2), accuracy and safety (3), the payoff +(4), and privacy plus the upgrade (5). ## Spares for A/B testing @@ -45,11 +49,11 @@ Rotate these in one at a time and let the campaign decide; they are all in-spec. | Headline | Chars | Angle | |---|---|---| -| Pay Once, Own It | 16 | Price honesty, filters out freebie-hunters | -| Works Fully Offline | 19 | Flight-mode reassurance | +| Free Photo Cleanup | 18 | The free tier, stated plainly | +| Ad-Free With Pro | 16 | The upgrade, without hiding the free banner | +| Works Fully Offline | 19 | Flight-mode reassurance for photo scanning | | Photos Stay On Your Phone | 25 | The privacy promise stated as a fact | | Find Similar Photos | 19 | Second keyword surface | -| Clean Up Your Gallery | 21 | Plain-language intent | | Description | Chars | Angle | |---|---|---| @@ -57,31 +61,30 @@ Rotate these in one at a time and let the campaign decide; they are all in-spec. | Resized, recompressed or byte-identical — one scan finds them all and shows the space. | 86 | Why "near-duplicate" matters | | Faster every re-scan. Remembers file hashes on your phone, never in the cloud. | 78 | The persistent index | | Keep the best copy of every shot. One tap marks the rest; you always confirm the delete. | 88 | The two-step removal | -| No ads, no account, no internet permission. Clean up your gallery with nothing given up. | 88 | Privacy as the lead | +| No account, no uploads. Free with one banner; a one-time Pro purchase removes it. | 81 | Privacy plus the honest model | ## Rules this copy follows -- **The word "free" is not used, and must not be added.** The app is sold at a single price - ([STORE_LISTING › App pricing](STORE_LISTING.md#app-pricing)), so any free claim is simply - false — and both Play's misleading-claims policy and Google Ads' misrepresentation policy treat - that as a violation, not a growth hack. "Reclaim storage" is a benefit; "free" would be a lie. -- **No price, discount or urgency wording.** Same reason the *Short description* alternatives in - [STORE_LISTING](STORE_LISTING.md#short-description-max-80-characters) avoid it: there is no - free tier to promote, and "limited time" reads as a promotion. *Pay once, own it* is a plain - statement of the business model. -- **Every claim is checkable against this repository.** *No ads* — no ad or analytics dependency - in `gradle/libs.versions.toml`. *No internet permission* — nothing in the merged manifest. - *Never uploaded* — same manifest, and [PRIVACY.md](../PRIVACY.md). *Faster every re-scan* — the - persistent hash index in `data/PhotoIndexStore.kt`. *Android confirms every deletion* — - `MediaStore.createDeleteRequest` / `createTrashRequest`, no `MANAGE_EXTERNAL_STORAGE`. +- **“Free” is accurate for the free tier** — the app is free to download and use. Do **not** say + “ad-free” without the Pro qualifier: the free tier shows one banner. “Ad-free with Pro” and + “free with one small banner” are the honest pairings. +- **No discount or urgency wording.** The free/Pro split is a plain statement of the model, not a + promotion. Avoid “limited time”, “50% off” and similar. +- **Every claim is checkable against this repository.** *Free tier with one banner* — + `ui/ads/BannerAdSlot.kt` + `AdPolicy`. *Pro removes it* — `monetization/ProStore.kt` + + `pro_no_ads`. *Your photos never leave the phone* — `PRIVACY.md` and the on-device scan + pipeline. *Faster every re-scan* — the persistent hash index in `data/PhotoIndexStore.kt`. + *Android confirms every deletion* — `MediaStore.createDeleteRequest` / `createTrashRequest`, + no `MANAGE_EXTERNAL_STORAGE`. - **No editing or video claims.** The app cannot edit or capture photos and does not scan videos ([README › Known limitations](../README.md#known-limitations)); *Photo editor* framing is deliberately absent for the same reason the tag is not used. - **No absolutes.** *Finds every duplicate* and *100% safe* are not claims the engine can keep — the Aggressive policy can miss pairs, EXIF-rotated images do not match, and unreadable files are skipped. The copy says what the app does, not what it never fails at. -- **"Ad-free" is a feature claim, not a price claim** — it is what a user of the competing - ad-laden cleaners is looking for, and it survives the paid-app rule above. +- **Don't claim “no internet permission”.** The ad/consent and Billing SDKs use the network; the + accurate claim is that **photos** are never uploaded. See + [PRIVACY.md](../PRIVACY.md) and [MONETIZATION](MONETIZATION.md). ## Which asset types to supply (and what to skip) @@ -153,7 +156,13 @@ results), uploaded to YouTube as **unlisted** and pasted in as a video asset. It not an ad — a purpose-shot 15 s clip of scan → "43.7 MB reclaimable" would beat it, and a landscape or square variant would additionally fill the other orientations. -### The gate to pass first: does a sale pay for the ad? +### Historical: the gate that applied to the paid app + +> **Superseded paid-app economics.** The sections from here to the end of the budgeting notes were +> written when a Play install *was* a paid purchase. They do not describe the freemium funnel and +> must not be used as current budget or target guidance. The freemium funnel has two different +> conversions — a free install and, later, a Pro upgrade — so its cost-per-install target and +> payback have to be measured separately. The copy and rules above are current. This app nets ≈ **€2.54** a sale ([STORE_LISTING › The arithmetic](STORE_LISTING.md#app-pricing)) and a paid app has no free install to optimise towards — Google counts a conversion only after the buyer @@ -206,7 +215,7 @@ here — delivery is, and the target is what caps it. | Location | **one market only, to start** | One market means one sticker price and one set of unit economics; mixing VAT rates mixes the arithmetic | | Audience segments | **leave empty** (see below) | A segment *narrows* delivery, and delivery is already the binding constraint | | Networks, devices, schedule | leave to Google | App campaigns set these themselves | -| Conversion tracking | **nothing to install** | Google Play reports the purchase. The app has no SDK, no `INTERNET` permission and no analytics ([PRIVACY.md](../PRIVACY.md)); adding one to "fix attribution" would make the listing's central claim false | +| Conversion tracking | **nothing to install** | Google Play reports the purchase. The app has no analytics SDK; photos never leave the device. The freemium build's only network users are ads/UMP/Billing ([PRIVACY.md](../PRIVACY.md)) | #### Audience segments, if you set one at all @@ -267,9 +276,9 @@ breaking even — which is what a bounded experiment should look like. Review at Do not touch the budget or the target mid-flight: both reset learning, and at this volume the model has little enough data as it is. -Two house rules apply to creatives exactly as to the copy: **no "free"** anywhere — this is a paid app -([why](STORE_LISTING.md#app-pricing)) — and no absolute claims the engine cannot keep (see *Rules this -copy follows* above). +Two house rules apply to creatives exactly as to the copy: **do not claim “ad-free” without the +Pro qualifier** — the free tier shows one banner — and no absolute claims the engine cannot keep +(see *Rules this copy follows* above). ## Re-checking the counts diff --git a/docs/EDGE_CASE_TESTING.md b/docs/EDGE_CASE_TESTING.md index d770d6e..f3f5fbd 100644 --- a/docs/EDGE_CASE_TESTING.md +++ b/docs/EDGE_CASE_TESTING.md @@ -166,7 +166,7 @@ release build — re-check with the audit command in `PLAY_RELEASE_CHECKLIST.md` ```bash adb shell am broadcast -a de.softwareapp_hb.fotodup.finder.debug.START_SCAN \ - -n de.softwareapp_hb.fotodup.finder.debug/de.softwareapp_hb.fotodup.finder.debug.DebugScanTrigger + -n de.softwareapp_hb.fotodup.finder.free.debug/de.softwareapp_hb.fotodup.finder.debug.DebugScanTrigger ``` Add `--es policy exact|balanced|aggressive` to override the default (`balanced`). The receiver @@ -177,7 +177,7 @@ the final timings are readable without the screen: adb logcat -s FotoDupDebug # poll the current state at any time: adb shell am broadcast -a de.softwareapp_hb.fotodup.finder.debug.REPORT_STATE \ - -n de.softwareapp_hb.fotodup.finder.debug/de.softwareapp_hb.fotodup.finder.debug.DebugScanTrigger + -n de.softwareapp_hb.fotodup.finder.free.debug/de.softwareapp_hb.fotodup.finder.debug.DebugScanTrigger ``` ### Granting photo access @@ -186,9 +186,9 @@ adb shell am broadcast -a de.softwareapp_hb.fotodup.finder.debug.REPORT_STATE \ why the **debug** manifest declares it: ```bash -adb shell appops set de.softwareapp_hb.fotodup.finder.debug MANAGE_EXTERNAL_STORAGE allow +adb shell appops set de.softwareapp_hb.fotodup.finder.free.debug MANAGE_EXTERNAL_STORAGE allow # ...run the scan, then put it back: -adb shell appops set de.softwareapp_hb.fotodup.finder.debug MANAGE_EXTERNAL_STORAGE default +adb shell appops set de.softwareapp_hb.fotodup.finder.free.debug MANAGE_EXTERNAL_STORAGE default ``` The app's own banner still reads *“Photo access needed”*, because `checkSelfPermission` is @@ -199,7 +199,7 @@ unaffected by an appops grant. That is expected: it only affects the on-screen p `jdb` attaches over JDWP to the debug build: ```bash -adb forward tcp:8700 jdwp:$(adb shell pidof de.softwareapp_hb.fotodup.finder.debug | tr -d '\r') +adb forward tcp:8700 jdwp:$(adb shell pidof de.softwareapp_hb.fotodup.finder.free.debug | tr -d '\r') printf 'suspend\nwhere all\nquit\n' | jdb -attach localhost:8700 ``` diff --git a/docs/MONETIZATION.md b/docs/MONETIZATION.md new file mode 100644 index 0000000..1372eaf --- /dev/null +++ b/docs/MONETIZATION.md @@ -0,0 +1,274 @@ +# Monetisation — ads, Pro and the Play Console + +Foto Dup Finder is **freemium**: + +- **Free tier** — every duplicate-finding feature, plus one anchored adaptive AdMob + banner at the bottom of the scanner screen. +- **Pro tier** — the same features with no banner. A one-time, non-consumable Play + Billing product `pro_no_ads`. + +There is no subscription, no trial, no feature gate and no account. Photo +processing remains entirely on-device; the only network traffic is AdMob/UMP and +Google Play Billing. + +## 1. Dependencies and why + +| Dependency | Version | Why | +|---|---|---| +| `com.google.android.gms:play-services-ads` | 25.5.0 | Stable Google Mobile Ads (legacy) SDK; `minSdk 24`, `compileSdk 34+` | +| `com.google.android.ump:user-messaging-platform` | 4.0.0 | Consent form / privacy options for EEA, UK, Switzerland and US states | +| `com.android.billingclient:billing-ktx` | 9.1.0 | Play Billing; one-time products, pending purchases, acknowledgement | + +**Legacy vs Next-Gen ads SDK.** Google now recommends the GMA Next-Gen SDK +(`com.google.android.libraries.ads.mobile.sdk:ads-mobile-sdk:1.5.0`). This app uses +the stable legacy SDK because its API is widely documented, it has the smaller +permission set (`READ_BASIC_PHONE_STATE` is not needed) and it is sufficient for one +banner. Treat a Next-Gen migration as a separate, tested change — the initialization +and ad-request APIs differ. + +## 2. AdMob setup + +1. Create an **AdMob account** and add an **Android app** linked to the new Play listing + (`de.softwareapp_hb.fotodup.finder.free`). The AdMob App ID is tied to that package; + do not reuse the old paid app's AdMob app unless the Play listing is the same. +2. Create one **Banner** ad unit. Copy: + - the **App ID** (`ca-app-pub-…~…`); + - the **banner unit ID** (`ca-app-pub-…/…`). +3. Put both in `local.properties` (git-ignored) or pass them to Gradle: + + ```properties + admob.appId=ca-app-pub-XXXXXXXXXXXXXXXX~YYYYYYYYYY + admob.bannerUnitId=ca-app-pub-XXXXXXXXXXXXXXXX/NNNNNNNNNN + ``` + + The defaults in `app/build.gradle.kts` are Google's public **test** ids; they are + safe to click but produce no revenue. The build logs a warning while they are in + use. +4. Create a **UMP message** under *Privacy & messaging* in AdMob, publish it, and + test it with a debug device. The app calls + `requestConsentInfoUpdate()` → `loadAndShowConsentFormIfRequired()` before + `MobileAds.initialize()`. +5. Optional but recommended: publish an `app-ads.txt` on the developer website that + Play points to. It is a website file, not an app asset. + +## 3. Play Console setup + +### 3.1 Publish the new listing as a free app + +The freemium build uses **`applicationId = de.softwareapp_hb.fotodup.finder.free`**, so +it is a **new Play listing**, separate from the old paid app at +`de.softwareapp_hb.fotodup.finder`. Create the new app as **Free** from the start — +new apps are free by default. Do **not** change the old paid listing's price; it can +remain for existing customers or be unpublished once they have migrated. This avoids +Play's irreversible paid → free change entirely. + +### 3.2 Create the in-app product + +1. *Monetise > Products > In-app products > Create product*. +2. Product ID: **`pro_no_ads`** (must exactly match `ProProduct.ID`). +3. Type: **One-time product** (non-consumable). +4. Set a price; the app displays Play's localized `formattedPrice`, so no code + change is needed to change it. +5. **Activate** the product. An inactive product is not returned by + `queryProductDetailsAsync()`. + +### 3.3 Test purchases + +1. Add a **license tester** under *Setup > License testing*. +2. Upload the freemium build to an **internal testing** track. +3. Install from the internal-testing link with the tester account. +4. Test: buy, cancel, pending (if available), restore, reinstall, and a second + device with the same account. +5. Use a **promo code** or license-tester purchase, never a real charge, for your + own end-to-end check. + +Billing cannot be tested from a local debug APK signed with a debug key and not +installed through Play; `BillingClient` will report `BILLING_UNAVAILABLE` or +`SERVICE_DISCONNECTED`. + + +## 4. App configuration + +`app/build.gradle.kts` reads three values, in order: Gradle property +(`-Padmob.appId=...`), `local.properties`, then the default test value. + +| Key | BuildConfig / manifest | Default | +|---|---|---| +| `admob.appId` | `manifestPlaceholders["admobAppId"]` → AdMob `APPLICATION_ID` meta-data | Google test app id | +| `admob.bannerUnitId` | `BuildConfig.ADMOB_BANNER_UNIT_ID` | Google test adaptive-banner unit | +| `legacyPro.cutoffEpochMs` | `BuildConfig.LEGACY_PRO_CUTOFF_EPOCH_MS` | `0` (disabled) | + +`local.properties.example` is the template. Never commit the real file. + +## 5. Code map + +| Class | Role | +|---|---| +| `monetization/ProProduct.kt` | product id + SharedPreferences keys | +| `monetization/ProStore.kt` | Billing connection, product query, purchase, acknowledgement, restore, local cache, legacy migration | +| `monetization/ProState.kt` | UI state (`isPro`, `priceText`, `billingAvailable`, `purchaseInProgress`, `message`) | +| `monetization/LegacyPro.kt` | pure install-time cutoff predicate | +| `monetization/AdsController.kt` | UMP consent + `MobileAds.initialize` + privacy options | +| `monetization/AdsState.kt` | `initialized`, `canRequestAds`, `privacyOptionsRequired`, `error` | +| `monetization/AdPolicy.kt` | pure banner gate | +| `ui/ads/BannerAdSlot.kt` | one adaptive `AdView`, lifecycle, destroy on dispose | +| `ui/pro/ProSheet.kt` | benefits, price, buy, restore, pending/unavailable | +| `ui/scanner/ScannerScreen.kt` | bottom slot, Options menu entry, sheet visibility | + +`FotoDupApplication` creates `ProStore` and `AdsController` next to +`ScanController`. `MainActivity` starts consent/ads only for a non-Pro install and +refreshes purchases on resume. + +## 6. Consent and purchase flows + +### Consent + +1. `ConsentInformation.requestConsentInfoUpdate(activity, params, ...)`. +2. On success, `UserMessagingPlatform.loadAndShowConsentFormIfRequired(activity)`. +3. Read `canRequestAds()` and `privacyOptionsRequirementStatus`. +4. Only then `MobileAds.initialize(appContext)`. +5. The banner is composed only when `AdPolicy.shouldShowBanner(...)` is true. +6. If UMP requires it, the Options menu shows **Privacy options**, which calls + `showPrivacyOptionsForm()`. + +If the consent request fails (offline, no Play services), the app keeps working and +does not request an ad unless UMP already has a usable answer. + +### Purchase + +1. `ProSheet` calls `ScannerViewModel.purchasePro(activity)`. +2. `ProStore.purchase()` queries product details if needed, then + `launchBillingFlow(activity, params)`. +3. `onPurchasesUpdated()` filters `pro_no_ads` and requires `PURCHASED`. +4. Pro is granted locally, cached, and the banner disappears immediately. +5. If the purchase is not acknowledged, `KEY_PENDING_ACK` stores the token; + `acknowledgePurchase()` is retried on the next refresh. +6. On app resume, `queryPurchasesAsync()` reconciles the cache with Play. + +## 7. Grandfathering paid customers + +The app was previously sold as a paid app. Play Billing cannot tell an install +whether it was bought as a paid app, so `LegacyPro` compares +`PackageInfo.firstInstallTime` with a cutoff: + +```properties +# Epoch milliseconds of the first freemium release. +legacyPro.cutoffEpochMs=1793491200000 # 2026-11-01T00:00:00Z +``` + +Because the freemium build has a **new applicationId** +(`de.softwareapp_hb.fotodup.finder.free`), its own first-install time can never +predate the cutoff. `ProStore` therefore reads the earliest first-install time of: + +- the new freemium package; and +- the old paid package `de.softwareapp_hb.fotodup.finder`, declared in `` + in the manifest. + +- An install before the cutoff is granted Pro and the decision is persisted in + `KEY_ORIGIN_RESOLVED` / `KEY_LEGACY_PRO`. +- A later successful Play query cannot revoke that grant. +- A cutoff of `0` disables the migration. +- The old paid app must still be installed the first time the freemium app runs. + Uninstalling the old app first, clearing app data, or a restore that resets + `firstInstallTime` loses the signal. For those users, use a promo code or a manual + support flow. A server-side purchase history would be stronger, but it contradicts + the no-account, no-backend design. + +Set the cutoff **before** uploading the first freemium build. If the app was never +actually sold, leaving it at `0` is correct. + + + +## 8. Play Console declarations and Data Safety + +The freemium build **does** contain ads and **does** use the advertising ID. These +answers change from the pre-freemium listing. + +| Console item | Answer | +|---|---| +| **Ads** (*App content*) | **Yes, my app contains ads** | +| **Advertising ID** | **Yes** — the ads SDK merges `AD_ID` and the Privacy Sandbox permissions | +| **Data safety** | Google Mobile Ads collects/shares data for advertising, analytics and fraud prevention (see below) | +| **Photo and video permissions** | unchanged: only `READ_MEDIA_IMAGES` / selected-photos access; the ad SDK never reads photos | +| **App access** | still “all functionality available without special access”; no login | +| **Content rating** | re-confirm; the app is a general-purpose utility, not child-directed | +| **Permissions audit** | re-audit the **merged release manifest**; expect `INTERNET`, `ACCESS_NETWORK_STATE`, `AD_ID`, `ACCESS_ADSERVICES_*`, `WAKE_LOCK`, `com.android.vending.BILLING` and the framework's dynamic-receiver permission in addition to the photo/notification/FGS set | + +Google's published disclosure for the Mobile Ads SDK lists: + +- **IP address** — may be used to estimate general location; +- **user product interactions** — app launch, taps, video views; +- **diagnostic information** — launch time, hang rate, energy usage; +- **device and account identifiers** — Android advertising ID, app set ID, and + identifiers related to signed-in accounts where applicable. + +All of it is encrypted in transit with TLS. Ad ID collection is optional at the +manifest level; this app keeps it because the free tier relies on advertising. The +in-app **Privacy options** entry point and Android's ad-ID controls give users a +way to change their choice. + +`PRIVACY.md` must stay consistent with these answers. Purchases are handled entirely +by Google Play; the app never receives payment details. + +## 9. Testing matrix + +| Case | How | +|---|---| +| Test banner | Debug build with the default test ids; a Play-services device shows a “Test Ad” label | +| No banner for Pro | `DebugProToggle.GRANT_PRO`, or a license-tester purchase | +| Consent required | UMP debug geography / test device; see the UMP docs | +| Privacy options | Menu appears only when `privacyOptionsRequirementStatus == REQUIRED` | +| Purchase | Internal testing track + license tester | +| Cancel | Reopen the Play sheet and press back | +| Restore | Reinstall, then **Restore purchase** with the same account | +| Pending | Use a delayed-payment test instrument if available; Pro must not activate | +| Offline Pro | Turn on airplane mode after a purchase; the cached entitlement keeps ads off | +| Refund/revoke | Refund in the Console, reopen the app; a successful Play query removes Pro unless legacy | +| Billing unavailable | AOSP AVD with no Play services; the sheet says purchases are unavailable and the scanner still works | +| Ad load failure | No network; the banner is absent, the app does not crash | + +For UMP testing outside the EEA, temporarily add a debug-only +`ConsentDebugSettings` in `AdsController.ensureInitialized()` before the update: + +```kotlin +val debugSettings = ConsentDebugSettings.Builder(activity) + .setDebugGeography(ConsentDebugSettings.DebugGeography.DEBUG_GEOGRAPHY_EEA) + .addTestDeviceHashedId("YOUR-HASHED-ID") // from the UMP logcat line + .build() +val params = ConsentRequestParameters.Builder() + .setConsentDebugSettings(debugSettings) + .build() +``` + +Keep it behind `BuildConfig.DEBUG` and remove it before a release build; the production +path must not force a geography. + +## 10. Troubleshooting + +| Symptom | Check | +|---|---| +| “Banner failed to load” | AdMob app id / unit id, network, test device, UMP `canRequestAds()` | +| No ad view at all | `isPro`, `AdsState.canRequestAds`, `AdsState.initialized`; the gate is intentional | +| `APPLICATION_ID` missing crash | `admob.appId` placeholder / manifest meta-data | +| `BILLING_UNAVAILABLE` | Play Store installed/updated, app installed from Play internal testing, license tester | +| `queryProductDetails` returns nothing | product `pro_no_ads` exists and is **active**, app uploaded to a testing track | +| Purchase granted but ads return | successful Play query found no purchase (refund/account mismatch) and the install is not legacy | +| Purchase not acknowledged | check `KEY_PENDING_ACK`; the next refresh retries; Play refunds after 3 days | +| Privacy options missing | UMP says the form is not required in this region | +| Ads load on a Pro device | `ProStore` cache/query, then `MainActivity` skip logic; check `DebugProToggle` state | + +## 11. Limitations + +- Entitlement is **client-side** and can be tampered with on a rooted device. This + is the deliberate cost of having no account/backend. +- A paid customer who uninstalls the old app before the first freemium launch, or who + uninstalls/reinstalls the new app, clears data, or restores to a device that resets + `firstInstallTime`, may lose the legacy grant. Use a promo code/support flow for + those users. +- The legacy ads SDK is in maintenance mode; migrating to GMA Next-Gen is a future + change with a different API. +- Store screenshots and the feature graphic predate the banner and Pro sheet; the + listing needs a re-shoot before the freemium release. +- The AOSP emulators used for tablet screenshots have no Play services, so ads and + Billing cannot be validated there. + diff --git a/docs/PLAY_RELEASE_CHECKLIST.md b/docs/PLAY_RELEASE_CHECKLIST.md index c96f1f5..686af6c 100644 --- a/docs/PLAY_RELEASE_CHECKLIST.md +++ b/docs/PLAY_RELEASE_CHECKLIST.md @@ -5,34 +5,35 @@ the rest are things you must do in the Play Console / with your own accounts. ## 1. Identity and signing -- [x] Final **application id** chosen: `de.softwareapp_hb.fotodup.finder` +- [x] Final **application id** chosen: `de.softwareapp_hb.fotodup.finder.free` (`applicationId` in `app/build.gradle.kts`). It can **never be changed after the - first release**, so treat it as locked. `namespace` and the Kotlin package of - the same name are aligned with it; debug builds append `.debug`. + first release**, so treat it as locked. This is a **new Play listing**, separate + from the old paid app at `de.softwareapp_hb.fotodup.finder`; the code package and + `namespace` deliberately stay `de.softwareapp_hb.fotodup.finder`, and debug builds + append `.debug` → `de.softwareapp_hb.fotodup.finder.free.debug`. - [x] Generate an **upload keystore** (keep it safe; if you lose it you cannot publish updates) — **[code]** done: `fotodup-upload.jks` in the project root (git-ignored, `alias upload`), `CN=Hadrian Burkhardt, L=Potsdam, C=DE`. - [x] Copy `keystore.properties.example` to `keystore.properties` and fill it in. **[code]** done — the file is in place, and the Gradle build picks it up automatically and signs release builds; without it the release APK stays unsigned. -- [ ] Enable **Play App Signing** in the Play Console and upload the certificate of - your *upload* key: +- [ ] Enable **Play App Signing** for the **new** app in the Play Console and upload the + certificate of your *upload* key (the same upload key can sign both listings): ```bash keytool -exportcert -alias upload -keystore fotodup-upload.jks -rfc > upload_cert.pem ``` Upload key fingerprint (SHA-256), to confirm the right key was registered: `AA:8C:3D:6C:D0:55:46:50:48:ED:04:3E:AF:34:2B:66:B4:13:87:C9:E0:DA:29:70:5A:0D:18:47:08:1A:4C:7A`. - Enrolment happens with the first upload: Google then holds the app signing key and this - one only signs uploads. + Enrolment happens with the first upload of the new listing: Google then holds that + app's signing key and this one only signs uploads. - [ ] Store the keystore + passwords in a password manager / secure vault. Back it up. ## 2. Versioning -- [x] Set `versionName` (user-visible) **[code]** — `1.0.2` in `app/build.gradle.kts`. -- [x] `versionCode` **[code]** — currently **3**. It is the counter Play orders uploads by, and - every later upload must be higher. **2 is already used**: Play rejects re-uploading the 1.0.1 - bundle with *"Version code 2 has already been used. Try another version code."* — 1 was the - 1.0.0 build, so 1.0.2 takes **3**. +- [x] Set `versionName` (user-visible) **[code]** — `1.1.0` in `app/build.gradle.kts`. +- [x] `versionCode` **[code]** — currently **4**. It is the counter Play orders uploads by, and + every later upload must be higher. Codes 1–3 were consumed by 1.0.0–1.0.2, so the + freemium build takes **4**. ## 3. Build the release artefacts @@ -41,14 +42,17 @@ the rest are things you must do in the Play Console / with your own accounts. ./gradlew :app:assembleRelease # -> APK for local testing ``` -- [x] **[code]** verified 2026-10-18: `bundleRelease` and `assembleRelease` both succeed. - `app/build/outputs/bundle/release/app-release.aab` is 2,940,935 bytes - (`sha256 534e5ae9c9a62ca13c93dd2da52d8228ec72aed14a1fe830f6e0def17b22e9f5`) and is signed with - the upload key. The release APK reports `versionCode=3 versionName=1.0.2 targetSdk=36` and - exactly the permission set listed in step 5 — **no `INTERNET`**, so "nothing leaves the - device" holds in the shipped artefact, not just in the source manifest. - (The 1.0.1 build is the one Play recorded as `versionCode` 2: 2,944,100 bytes, - `sha256 f8e6a29a…`.) +- [ ] **Build and record the 1.1.0 artefacts.** The 1.0.2 record is historical + (2,940,935 bytes, `sha256 534e5ae9…`). The freemium build adds the ads/UMP/Billing + dependencies and the AdMob manifest entry, so its size and hash must be re-measured + after real AdMob ids are configured. Verify the release APK reports package + `de.softwareapp_hb.fotodup.finder.free`, `versionCode=4 versionName=1.1.0 + targetSdk=36` and the permission set in step 5 (including `INTERNET`, `AD_ID` and + `BILLING`). + Local validation with the default test ids (2026-10-20): APK 3,655,562 bytes, + `sha256 931d2b21…`; signed AAB 7,680,301 bytes, `sha256 03abb548…`. + Re-measure both after setting the real ids/cutoff — the ids change the manifest and + therefore the artefacts. - [ ] Upload the **`.aab`** (not the APK) to the Play Console. ⚠️ **Expect a native-debug-symbols warning here, and ignore it.** Play scans the bundle, finds `base/lib//libandroidx.graphics.path.so`, and reports *"This App Bundle contains native @@ -79,47 +83,34 @@ Ready-to-paste copy and the generated graphics live in [docs/STORE_LISTING.md](STORE_LISTING.md) (milestone M10). Everything below is a Console action except the items marked **[code]**. -- [ ] ⚠️ **Confirm App pricing is set to paid before rolling out — it is the one irreversible - decision.** Play, *Set up your app's prices*: *"You can change your app from paid to free. Once your app has - been offered for free, the app can't be changed to paid. If you want to charge for the app, you - need to create a new app with a new package name and set a price."* **`versionCode` 2 (1.0.1) - has already been uploaded and consumed**, so check *Products > App pricing* before this - rollout: if it still offers **Make your app paid**, do it now — once the app is offered for - free that option is gone for good. In the Console: - 1. **Set up a payments profile** with your tax rates (Play asks the first time you set a price). - 2. **Products > App pricing** → *"Your app is"* → **Make your app paid**, and enter the base price - **€2.99** (one-time). Leave *"Default price includes tax"* off unless €2.99 is meant to be the - final gross price in the EU — off, the €2.99 is a **net** figure and the buyer is charged the - gross price: **€3.56** in Germany (19% VAT), **€3.59** in a 20% market such as Austria or - France. **Verified live after publishing: the listing reads €3.59** — the Console shows the - price you typed, the storefront shows the price the buyer pays, and Play prices the page for - the country of the viewing account rather than the country you are sitting in. What each - setting does to the sticker and to your payout: - [STORE_LISTING › What the buyer actually pays](STORE_LISTING.md#what-the-buyer-actually-pays). - 3. Check the **local prices** Play derives for each country — a country with no price is a - country where the app is unavailable. - 4. [ ] **Launch sale: 50% off (€1.49) for 14 days.** A sale can only be created *after* the app is - published (*App pricing > Sales > Create sale*), it can be **live for 1–14 days at most**, and - **30 days must pass between one sale ending and the next starting** — so this is a single - deadline-driven window, not a permanently lower launch price. Percentage discounts must be - between 10% and 100%. The original price is struck through everywhere except in 12 EU member - states and the UK (Germany does show it) — and that crossed-out figure is the **gross** price. - **Verified live:** the sale reads **€1.79** (€1.77 in Germany), the same VAT gross-up as the - base price: 1.49 × 1.20 and 1.49 × 1.19. - 5. [ ] **Test the paid listing end to end**: install your own copy through a **promo code** - rather than a real purchase. A giveaway code is the only trial mechanism a paid app has, and - it doubles as the check that a buyer really does receive a working app. - **[code]** nothing to build: no Billing dependency, no `com.android.vending.BILLING` in the - merged manifest. Rationale, the fee arithmetic and the sale rules: - [STORE_LISTING](STORE_LISTING.md) › App pricing. +- [ ] **Freemium Console setup — this replaces the old paid-app step.** + 1. Create the **new Play app** for `de.softwareapp_hb.fotodup.finder.free` and + publish it as **Free** (new apps are free by default). Do **not** change the old + paid listing's price; it can stay for existing customers or be unpublished. + 2. *Monetise > Products > In-app products* → create **`pro_no_ads`**, type **One-time + product**, set the price, **Activate** it. The product id must match + `ProProduct.ID` exactly; an inactive product is not returned by Play. + 3. AdMob → create/link the Android app, one **Banner** unit and a **UMP message**. + Put the ids in `local.properties` (`admob.appId`, `admob.bannerUnitId`) or pass + `-Padmob.appId=...`; never commit them. + 4. Set `legacyPro.cutoffEpochMs` to the instant of the first freemium release. + Installs older than that are grandfathered into Pro; a `0` cutoff disables the + migration. Because the new app has a different applicationId, this only works + when the old paid app is still installed on the first freemium launch. Tell + existing customers to keep the old app installed for that first run, or use a + promo code/support flow. + 5. Add **license testers**, upload to **internal testing**, and test buy, cancel, + pending, restore, reinstall and a second device with the same account. Use a promo + code or a license-tester purchase, never a real charge. + 6. Update the **Ads**, **Advertising ID** and **Data Safety** answers in step 5. + Full steps: [MONETIZATION](MONETIZATION.md); rationale and copy: + [STORE_LISTING › App pricing](STORE_LISTING.md#app-pricing). - [ ] App name (≤ 30 chars): "Foto Dup Finder" (15 chars). -- [ ] Short description (≤ 80 chars) — two options are drafted and length-checked in - STORE_LISTING.md (69 and 65 chars). **Neither says "free"**: the app is paid, so the claim would - be false, and Play's metadata policy keeps price and promotional wording out of the title, - icon and developer name. -- [ ] Full description (≤ 4000 chars) — drafted and length-checked in STORE_LISTING.md (2 426 chars, - so there is room to grow). The one price line ("Pay once, then own it…") sits in the body for - the same policy reason. +- [ ] Short description (≤ 80 chars) — two freemium options are drafted and length-checked + in STORE_LISTING.md. “Free” is now accurate, but Play's metadata policy still keeps + price and promotional wording out of the title, icon and developer name. +- [ ] Full description (≤ 4000 chars) — drafted in STORE_LISTING.md. It states the free + tier / one-time Pro distinction in the body, not as a promotional gimmick. - [x] **App icon** 512×512 PNG **[code]** — `tools/make-store-assets.sh` renders it from the same vectors as the adaptive icon in `res/drawable/ic_launcher_*`. - [x] **Feature graphic** 1024×500 PNG **[code]** — same script. @@ -183,23 +174,31 @@ action except the items marked **[code]**. > the hosted policy. If you want the policy in another language, host a translated > copy yourself and link it from the listing. - [ ] Complete the **Data safety** form: - - *Does your app collect or share any required user data types?* → **No**. - - Data types accessed: **Photos** — processed on-device only, not collected. - - *Is all user data encrypted in transit?* → N/A (no transmission). - - *Do you provide a way for users to request data deletion?* → Uninstalling - removes all app data. - - The **paid** model changes none of the above: the purchase happens in the Play Store app, not in - this one. Play's own guidance is that using a payment service such as *"Google Play's billing - system"* to complete transactions does **not** require declaring the data that service collects - in connection with its processing — and this app contains no payment code at all, so it receives - nothing either way. Re-read that if a Billing dependency is ever added - (step 9); the app's own answers would still be "no", but the *purchase handling* would move - into the app and the answers would need a fresh look. -- [x] Confirm the **permission set** the Console will show. **[code]** done 2026-10-13: `aapt2 dump - badging` on the release APK reports exactly the table below (plus - `…DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION`) — and **no `INTERNET`**. Re-check from the - *merged* release manifest rather than the source one after any dependency change, so nothing - a library quietly adds slips past: + - *Does your app collect or share any required user data types?* → **Yes**. + - **Device or other IDs** → collected and shared (advertising ID, app set ID, + account-related identifiers where applicable). Purpose: **Advertising or + marketing**, **Analytics**, **Fraud prevention, security and compliance**. + - **App activity** → collected and shared (app launch, taps, video views) for + advertising/analytics. + - **Diagnostics** → collected and shared (launch time, hang rate, energy usage). + - **Location** → **Approximate location**, collected/shared if the Console treats the + ads SDK's IP-based estimate as location; the app itself requests no location + permission. + - **Photos** → **not collected**: read and processed on-device only. + - *Is all user data encrypted in transit?* → **Yes** (Google states TLS for the ads + SDK; Play Billing is handled by Google). + - *Do you provide a way for users to request data deletion?* → The developer holds + no server-side data. Uninstalling/clearing app storage removes the local index and + Pro cache; users can reset/delete the advertising ID in Android Settings and change + consent through **Privacy options** where UMP requires it. + - **Purchases** are handled entirely by Google Play. The app never receives payment + details; the optional `pro_no_ads` entitlement is cached locally. + - The full data-type list and the source are in + [MONETIZATION › Play Console declarations](MONETIZATION.md#8-play-console-declarations-and-data-safety). + Re-read the form if the AdMob/UMP configuration or the Billing dependency changes. +- [x] Confirm the **permission set** the Console will show. **[code]** the freemium build adds + the ads and Billing permissions; re-check from the *merged* release manifest rather than the + source one after any dependency change, so nothing a library quietly adds slips past: | Declared permission | Why | From | |---|---|---| @@ -209,17 +208,23 @@ action except the items marked **[code]**. | `WRITE_EXTERNAL_STORAGE` (`maxSdkVersion=29`) | legacy delete on Android 10 only | app | | `FOREGROUND_SERVICE`, `FOREGROUND_SERVICE_DATA_SYNC` | keep a scan alive | app | | `POST_NOTIFICATIONS` | scan-progress notification | app | + | `INTERNET`, `ACCESS_NETWORK_STATE` | free-tier ads/consent + Pro purchase | app / Ads SDK | + | `com.google.android.gms.permission.AD_ID` | advertising ID | Ads SDK | + | `ACCESS_ADSERVICES_AD_ID`, `ACCESS_ADSERVICES_ATTRIBUTION`, `ACCESS_ADSERVICES_TOPICS` | Privacy Sandbox | Ads SDK | + | `WAKE_LOCK` | ad rendering | Ads SDK | + | `com.android.vending.BILLING` | one-time `pro_no_ads` purchase | Billing SDK | | `…DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION` | framework-generated, not user-facing | AndroidX | - Deliberately **absent**: `INTERNET` and `MANAGE_EXTERNAL_STORAGE`. Both are - load-bearing for the "nothing leaves the device" claim, so re-check after any new - dependency: + `MANAGE_EXTERNAL_STORAGE` must remain **absent**. `INTERNET` is load-bearing for ads + and Billing, so the old “no network permission” claim no longer holds; the remaining + promise is narrower and still true: the app's own code never uploads photos, + thumbnails, hashes or filenames. Audit the merged manifest with: ```bash ./gradlew :app:processReleaseMainManifest grep -A1 ' default; over a hand-picked subset it would be meaningless, because a selection is not a > sample of the library — it is the part the duplicates are not in. > - > Nothing is uploaded: the app declares no INTERNET permission and all hashing happens on the - > device. Photos are only read. Any deletion requires an explicit selection by the user and - > always goes through Android's own confirmation dialog (`MediaStore.createDeleteRequest` / - > `createTrashRequest`) — never silently — and the app never requests - > `MANAGE_EXTERNAL_STORAGE`. Partial access (`READ_MEDIA_VISUAL_USER_SELECTED`) is declared - > and supported as a reduced mode for users who prefer to hand over fewer photos. + > Nothing is uploaded: photos are read and hashed entirely on the device. The only + > network use is the free tier's ads/consent SDK and the optional Pro purchase, and + > neither ever receives a photo, thumbnail, hash or filename. Any deletion requires an + > explicit selection by the user and always goes through Android's own confirmation + > dialog (`MediaStore.createDeleteRequest` / `createTrashRequest`) — never silently — and + > the app never requests `MANAGE_EXTERNAL_STORAGE`. Partial access + > (`READ_MEDIA_VISUAL_USER_SELECTED`) is declared and supported as a reduced mode for + > users who prefer to hand over fewer photos. …and **682 characters**, for a box with less room than that: @@ -285,8 +292,9 @@ action except the items marked **[code]**. > duplicates of a picked photo are precisely the files the picker never hands over — a > selection cannot answer "what is duplicated in my library". The app also calibrates its > similarity threshold from the library's own pairwise distance distribution, which needs the - > whole library to mean anything. Nothing is uploaded (the app has no INTERNET permission) - > and deletion always goes through Android's confirmation dialog. + > whole library to mean anything. Photos are processed on-device and never uploaded; the + > only network use is ads/consent and the optional Pro purchase, and deletion always goes + > through Android's confirmation dialog. Nothing in any of them is aspirational — every claim is a place in the code, so it can be defended if Play comes back with questions: @@ -298,7 +306,7 @@ action except the items marked **[code]**. | the threshold is fitted per library | `AdaptiveThreshold.choose()` estimates the unrelated-photo distribution from the scan's own pairwise histogram and returns the widest threshold keeping the *expected* number of accidental matches in budget; under `MIN_SAMPLE` = 200 pairs it falls back to the policy ceiling | | a selection cannot stand in for a library | that histogram is built from every pair in the scan — the phone's 5,385-photo library fitted to *pHash ≤ 10 bits* and said so on screen, while the 22-photo tablet library was too small to fit and used its ceiling (`(default)`) | | a constant threshold cannot work | `AdaptiveThreshold` KDoc and README § scan pipeline: the widest pHash threshold with zero false pairs falls from **13 (120 images) to 5 (2 880)** as a library grows | - | nothing leaves the device | no `INTERNET` in the merged release manifest — the `aapt2` audit in the item above | + | photos never leave the device | `ScanEngine` / `PhotoHasher` operate on local bytes and the SQLite index; no photo, thumbnail, hash or filename is sent. Only AdMob/UMP/Billing use the network (see [MONETIZATION](MONETIZATION.md)) | | deletion is never silent | `MediaDeleter` → `MediaStore.createDeleteRequest` / `createTrashRequest`; no `MANAGE_EXTERNAL_STORAGE` | | partial access is real, not a gesture | `AppPermissions.MediaAccess.PARTIAL` / `hasPartialAccess()`, with a banner and a prompt to upgrade to full access | @@ -333,7 +341,8 @@ action except the items marked **[code]**. > The app finds duplicate photos on the device. The user starts a scan and may leave > the app while it runs; the foreground service keeps that user-initiated scan alive > and shows its progress. The scan reads the photo library and writes a small local - > index of file hashes. It performs no network access and transfers no data. + > index of file hashes. The scan service itself performs no network access; ads, + > consent and the optional Pro purchase are separate and never receive photo data. 2. **User impact if the task is deferred or interrupted.** A scan is not deferrable work — the user is watching for a result — so there is no WorkManager/JobScheduler fallback: @@ -451,29 +460,27 @@ action except the items marked **[code]**. typically rated Everyone / 3+). - [ ] **App access** → *All functionality is available without special access*: no login, no account, nothing gated. -- [ ] **Ads** → *No, my app does not contain ads* (and no ad SDK in - `gradle/libs.versions.toml` to contradict the answer). -- [ ] **Advertising ID** → *No, my app does not use advertising ID.* The question adds "This - includes any SDKs that your app imports that use advertising ID", so the answer has to come - from the dependency graph rather than from the source: `play-services-ads-identifier` is what - provides the ID and it merges `AD_ID` into the manifest on its own, so adding any ad or - analytics SDK would flip this answer to *Yes* without one line of app code changing. Audited - 2026-10-14 against the shipped artefacts rather than against intentions: +- [ ] **Ads** → **Yes, my app contains ads.** The free tier shows one AdMob banner; + Pro removes it. Play asks whether the app *contains* ads, not whether every user + sees them, so the answer is Yes. +- [ ] **Advertising ID** → **Yes, my app uses advertising ID.** The question adds "This + includes any SDKs that your app imports that use advertising ID"; the Google Mobile + Ads SDK merges `AD_ID` and the Privacy Sandbox permissions, and Play Billing merges + `BILLING`. Audited against the merged release manifest, not against intentions: - | Check | Command | Result | + | Check | Command | Expected | |---|---|---| - | no advertising/analytics SDK, direct **or transitive** | `./gradlew --offline -q :app:dependencies --configuration releaseRuntimeClasspath \| grep -iE 'gms\|firebase\|ads\|billing\|play-services'` | no output | - | no `AD_ID` and no Privacy Sandbox permission in the release APK | `aapt2 dump badging app/build/outputs/apk/release/app-release.apk \| grep -i permission` | exactly the audit table above — 7 requested, plus the framework's `…DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION` | - | the same for the **`.aab`**, which is the artefact Play scans | `unzip -p app/build/outputs/bundle/release/app-release.aab base/manifest/AndroidManifest.xml \| strings \| grep -x 'AD_ID'` | 0 hits | - | no Play Services classes in the shipped code | `unzip -p app/build/outputs/apk/release/app-release.apk classes.dex \| grep -a -c 'com/google/android/gms'` | 0 | - | nothing could be sent even if an ID were read | the permission audit above | no `INTERNET` | + | ads + Billing dependencies, direct or transitive | `./gradlew -q :app:dependencies --configuration releaseRuntimeClasspath \| grep -iE 'play-services-ads\|billing\|user-messaging'` | `play-services-ads`, `billing`, `user-messaging-platform` | + | `AD_ID` and Privacy Sandbox permissions in the release APK | `aapt2 dump badging app/build/outputs/apk/release/app-release.apk \| grep -i permission` | the permission table above, including `AD_ID` and `ACCESS_ADSERVICES_*` | + | the same for the **`.aab`** Play scans | `unzip -p app/build/outputs/bundle/release/app-release.aab base/manifest/AndroidManifest.xml \| strings \| grep -E 'AD_ID\|BILLING'` | both present | + | Play Services classes in the shipped code | `unzip -p app/build/outputs/apk/release/app-release.apk classes.dex \| grep -a -c 'com/google/android/gms'` | greater than 0 (ads SDK) | + | network is possible | the permission audit above | `INTERNET` present | - This is the machine-checked version of what [PRIVACY.md](../PRIVACY.md) promises in words - ("does not collect … advertising identifiers", "does not contain advertising SDKs or - third-party trackers"), so re-run the first two rows after **any** dependency change — - including one that looks unrelated. This is the declaration a stray library can answer - wrongly on the app's behalf, and the *Data safety* form's *Device or other IDs* answer is - *No* for the same reason. + This is the machine-checked version of what [PRIVACY.md](../PRIVACY.md) now says: + photos are processed on-device, while Google Mobile Ads collects/shared ad data for + advertising, analytics and fraud prevention. Re-run the audit after **any** + dependency change. The *Data safety* form's *Device or other IDs* answer is + **Yes** for the same reason. - [ ] Select the target audience (not designed for children). - [ ] Answer the remaining *App content* declarations **No** / not applicable: news app, @@ -498,13 +505,25 @@ action except the items marked **[code]**. - [x] Test with a library of several thousand photos to sanity-check scan time. **[code]** done on the test device: the 5,363-photo library scans in **20.2 s cold / 11.0 s warm**, and the screenshot run over 5,385 photos finished in **11.1 s** (6 unreadable files skipped). +- [x] **Freemium build on the real phone** (Xiaomi M2101K7AG, Android 12 / API 31): + **5,373 photos, 19 groups, 47 photos involved, 40.1 MB reclaimable, 25.5 s** + (signatures 2.2 s · exact 42 ms · perceptual 22.1 s), pHash cut fitted to ≤ 10 bits, + 6 unreadable. The AdMob **adaptive test banner loaded**, the free/Pro toggle removed + it, the Pro sheet rendered, and **Buy Pro** showed the expected + “purchases unavailable” message because `pro_no_ads` is not active in the Console yet. + No app-level fatal; the only logcat fatal was the separate `uiautomator` dump tool. + **Warm retest on the same phone:** the cached index brings the same **5,373-photo** + library down to **3.0 s** (signatures 675 ms · exact 4 ms · perceptual 939 ms), + still **19 groups / 47 photos / 40.1 MB**. Buy Pro still reports “purchases + unavailable” because this debug build was sideloaded and `pro_no_ads` is not active + on the internal track yet; that is the expected gate, not a crash. - [ ] Verify no crashes in *Play Console > Quality > Android vitals* after rollout. ## 7. Release notes ("What's new") and rollout -⚠️ **Which block applies:** `versionCode` **2** (1.0.1) is already in Play — its upload is what -consumed the code — so the next upload is **1.0.2 / `versionCode` 3** and takes the 1.0.2 block -below. The initial-release block is kept for the record; it was the 1.0.1 upload. +⚠️ **Which block applies:** `versionCode` **4** (1.1.0) is the freemium build, so paste the +1.1.0 block below. The 1.0.2 and initial-release blocks are kept for the record and are +historical — the initial block still says “no ads”, which was true only of the paid build. Release notes are **not stored in this repo** — they are typed into the Play Console @@ -539,7 +558,17 @@ Ready-to-paste block for the first release: • No ads, no account, works fully offline -Ready-to-paste block for **1.0.2** (the `versionCode` 3 build): +Ready-to-paste block for **1.1.0** (the freemium build, `versionCode` 4): + + + • Foto Dup Finder is now free to download and use + • The free version is supported by a single banner; a one-time Pro purchase removes it + • Every duplicate-finding feature stays free + • Existing paid customers keep the ad-free experience + • Privacy options are available where required + + +Ready-to-paste block for **1.0.2** (the `versionCode` 3 build, historical): • Maintenance release with compatibility fixes @@ -564,27 +593,39 @@ Ready-to-paste block for **1.0.1** (the scan-robustness patch): - [ ] Watch for newer AGP; when it supports it, update `compileSdk` to 37 and bump the Compose BOM and Coil together (see the version note in the README). - [ ] Optionally add crash reporting later — but note this would change the Data - safety answers, so weigh it against the "no data leaves the device" promise. + safety answers, so weigh it against the “photos never leave the device” promise. -## 9. Monetisation — decided: one-time paid app, no billing +## 9. Monetisation — freemium ads + one-time Pro -**The decision is made: Foto Dup Finder is a one-time paid app** (rationale, the €2.99 base price, -the €1.49 launch sale and the irreversibility rule: [STORE_LISTING](STORE_LISTING.md) › App pricing). -The Console work is in step 4; **nothing in this repository changes**, because a price on the listing -adds no code, no permission and no Data Safety answer — which is exactly what a free app with a Pro -unlock could not claim. +**Current model: freemium.** The app is free to download. The free tier shows one +anchored adaptive AdMob banner; a one-time Play Billing product **`pro_no_ads`** +removes it. Pro removes ads and nothing else — every scan, selection and deletion +feature stays free. Existing paid installs are grandfathered through +`legacyPro.cutoffEpochMs`. + +The Console work is in step 4 and the declarations are in step 5; the full setup and +data-disclosure details are in [MONETIZATION](MONETIZATION.md). Rationale and current +copy: [STORE_LISTING › App pricing](STORE_LISTING.md#app-pricing). Standing rules: -- **Ads: never.** Every ad SDK needs the `INTERNET` permission to fetch anything, and the - merged-manifest check in step 5, [PRIVACY.md](../PRIVACY.md) and the Data Safety answers all rest - on that permission being absent. -- **In-app purchases: deliberately absent.** If that ever changes, the requirement is Play Billing - **8+** (latest published: 9.1.0, with an extension available to Nov 1, 2026). Worth knowing before - the decision is re-litigated: the **Billing Library itself does not add `INTERNET`** — - `com.android.billingclient:billing:9.1.0`'s manifest declares only `com.android.vending.BILLING` - and `` for the billing service, which was checked by unpacking the AAR. What *would* - change is the store copy (the "pay once" line), `PRIVACY.md`, the acknowledgement/restore flow, and - the fact that a purchase can only be verified on an internal testing track — never locally. -- **Refunds and support** follow Play's policy for a paid app; keep the contact address in +- **One banner, no interstitials.** Do not add an interstitial, app-open, native or + rewarded format without a product decision and a UX/privacy review. +- **Consent before ads.** UMP must resolve before `MobileAds.initialize()`; a refused + or unresolved consent means no ad request. Pro users skip ad initialisation entirely. +- **Pro never gates a feature.** It removes the banner; a scan limit or a locked + deletion flow would change the product promise and the store copy. +- **Billing is one-time and acknowledged.** Play Billing 9.1.0, product `pro_no_ads`, + pending purchases enabled, acknowledgement retried. The entitlement is client-side + and cached; Play re-verifies on resume. +- **Grandfather paid customers.** Keep the install-time cutoff and document its + limitations; uninstall/reinstall can lose it. +- **Keep Data Safety and `PRIVACY.md` in step.** Google Mobile Ads collects/shares ad + data (ad ID, interactions, diagnostics, IP); photos remain on-device. The **Ads** and + **Advertising ID** answers are **Yes**. +- **Secrets stay out of the repo.** Real AdMob ids and the legacy cutoff live in + `local.properties` or CI Gradle properties; test ids may stay in the build defaults. +- **Re-shoot the store assets.** The committed screenshots and feature graphic predate + the banner and Pro sheet; the freemium listing needs new captures. +- **Refunds and support** follow Play policy; keep the contact address in [PRIVACY.md](../PRIVACY.md) current. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index fec3667..3f61e9f 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -1,6 +1,6 @@ # Roadmap -Foto Dup Finder is built against a fixed milestone plan (**M0–M10**). This file is the +Foto Dup Finder is built against a fixed milestone plan (**M0–M11**). This file is the single source of truth for what is done and what remains. Before this file existed the plan lived only in developer notes, and the [CHANGELOG](../CHANGELOG.md) refers to milestone labels (`M7`, `M8`). @@ -20,8 +20,9 @@ Legend: ✅ done · 🚧 in progress · ⏳ not started · 💡 candidate (propo | M6 | Release config & Play readiness | ✅ | R8/minify, optional signing, `.aab`, [PLAY_RELEASE_CHECKLIST](PLAY_RELEASE_CHECKLIST.md), [PRIVACY.md](../PRIVACY.md), README | | M7 | On-device validation & hardening | ✅ | Foreground `dataSync` service, one failure boundary per file, `core/DecodeMath`, hostile fixtures ([EDGE_CASE_TESTING](EDGE_CASE_TESTING.md)), `versionName` → 1.0.0 | | M8 | Localisation groundwork | ✅ | Every user-visible string in `res/values/strings.xml` with real ``, shared `text/TextRes.kt`; **English is the only locale** | -| M9 | Monetisation | ✅ | **Decided: a one-time paid app** — no free tier, no trial, no subscription and no in-app purchase, so there is **no Billing code** and no new permission. Checked before deciding: `com.android.billingclient:billing:9.1.0`'s manifest declares only `com.android.vending.BILLING`, so IAP would *not* have added `INTERNET` either — but a price on the listing is the one model that changes nothing at all about the "no internet permission" claim. Base price **€2.99** one-time with a **50% launch sale at €1.49**, both set in the Console (*Products > App pricing*). €1 as the *base* price was considered and rejected: a sale can always be added, but a low anchor cannot be undone, and a paid app's first transaction is its only transaction. Free → paid becomes impossible after the first upload, so this had to be settled before release. Rationale, copy changes and Console steps: [STORE_LISTING](STORE_LISTING.md) › App pricing, [PLAY_RELEASE_CHECKLIST](PLAY_RELEASE_CHECKLIST.md) step 4 | +| M9 | Monetisation | ✅ | **Revised from paid to freemium.** Free tier with one anchored AdMob banner + UMP consent; a one-time Play Billing product (`pro_no_ads`) removes it. Pro only removes ads — every scan/selection/deletion feature stays free. Existing paid installs are grandfathered through `legacyPro.cutoffEpochMs`. Setup, Data Safety and Console steps: [MONETIZATION](MONETIZATION.md) | | M10 | Store assets | ✅ | `tools/make-store-assets.sh` renders the 512×512 icon and the 1024×500 feature graphic from the app's own vectors; `tools/make-store-screenshots.sh` normalises device captures to Play's 2:1 limit, one directory per form factor (`phone` → 1080×2160, `tablet-7in` → 1200×1920, `tablet-10in` → 1600×2560); `tools/make-demo-photos.py` generates the photo library the results captures are taken over, so no real photos are published; all listing copy is drafted and length-checked in [STORE_LISTING](STORE_LISTING.md). The phone set was re-shot on a real device after a real permission grant, and the two tablet sets were captured on AOSP AVDs (see the blocker below); the finished assets — icon, feature graphic, the twelve normalised screenshots and the demonstration video — are committed, so Gitea serves them publicly and pushing is the deployment step | +| M11 | Freemium implementation | ✅ | AdMob anchor banner + UMP consent, Play Billing `pro_no_ads`, Pro sheet, ad gate, legacy paid-install migration, focused tests, [codemap](codemap.md) / [codemap.mmd](codemap.mmd), [AGENTS.md](../AGENTS.md), [MONETIZATION](MONETIZATION.md), README/PRIVACY/CHANGELOG/store-doc updates. **Remaining:** publish the new free Play listing at `…finder.free`, create/activate `pro_no_ads`, add the AdMob app/unit + UMP message, set the legacy cutoff, update Data Safety / Ads / Advertising ID, and re-shoot the screenshots with the banner and Pro sheet | ## Release blockers (work that is not a numbered milestone) @@ -30,9 +31,9 @@ Legend: ✅ done · 🚧 in progress · ⏳ not started · 💡 candidate (propo | ~~Large-library scan stall~~ ✅ **fixed — verified on device** | The 5,363-photo library used to freeze at *“74 / 100 · Comparing file signatures…”* (a **blocked syscall**: zero CPU, workers sleeping). `BoundedCall` now abandons a stuck provider call **and** trips a stall breaker after three consecutive timeouts. **Verified on the real test device (Android 12 / MIUI): the scan completes — 20.2 s cold, 11.0 s warm, 15 groups, 6 unreadable — where it used to hang.** Covered by `BoundedCallTest` and `ScanEngineEndToEndTest` | | ~~Unreleased `BoundedCall` fix~~ ✅ | The provider-call deadline shipped in **1.0.1** (`versionCode` 2) | | **Play Console: foreground-service declaration** | Declaring the `dataSync` type (App content › Foreground service permissions) is release-blocking. **[code]** the manifest already declares it, [PLAY_RELEASE_CHECKLIST](PLAY_RELEASE_CHECKLIST.md) step 5 carries all four things the form asks for (description, defer/interrupt impact, use case **Local processing: Other**, video link), and the **video now exists**: recorded on the test device on 2026-10-14 with `INSTALL=0 WARMUP=0 tools/record-fgs-demo.sh`, then verified frame by frame rather than assumed — intro at 0 s, the scan starting, **~6 s of the shade with the live "Finding duplicate photos / Looking for visually similar photos… / CANCEL" notification while the scan kept running**, and the results at the end. It is committed, and that is what published it — the link is the file's **page** in Gitea (`/src/branch/main/…`), which plays it anonymously. The `/raw/` URL is deliberately not the link: Gitea sends `Content-Security-Policy: default-src 'none'` with raw responses, so a browser navigating to the video sits on a blank tab even though the bytes are perfect. Pasting the page URL into the declaration is all that is left. Two details of the take are recorded in step 5 because they each cost an attempt: a *warm* scan is 5.4 s, shorter than the shade takes to open, so `WARMUP=0` films the cold one; and MIUI refuses `adb install` outright, so `INSTALL=0` records with the build already on the device. On a KVM-less emulator the same video cannot be made at all: every scan start dies as `am_crash … ForegroundServiceDidNotStartInTimeException` → *Force finishing activity* with no `am_kill`, i.e. emulation is too slow to reach `startForeground()` inside Android's budget (QEMU's `-icount` clock dilation made it work once, not reproducibly) | -| **Remaining Play paperwork** | Console actions only, no code: **confirm Play App Signing enrolment from the 1.0.1 upload**, the **hosted privacy policy URL** (the working copy is now published to Gitea as [`fishfacegit/foto-duplicate-finder`](https://gitea.softwareapp-hb.de/fishfacegit/foto-duplicate-finder), so the policy renders at a public, login-free URL and only the Console paste is left), **Data safety**, the **Photo/video permissions** declaration, the **content rating / audience / app access / ads / advertising ID / export** questions, and the **listing copy + the three screenshot sets** (phone, 7-inch and 10-inch, all captured), plus the **paid-app setup**: a payments profile with tax rates, the €2.99 price and the 14-day €1.49 launch sale on *Products > App pricing* — the price must be confirmed before the next rollout, because free → paid is not possible once the app has been offered for free (M9). Keystore, `versionCode`, listing copy, graphics, permission audit and the signed `.aab` (`sha256 534e5ae9…`, `versionCode` 3) are all in place; rollout goes internal → closed → production. Step-by-step: [PLAY_RELEASE_CHECKLIST](PLAY_RELEASE_CHECKLIST.md) | -| ~~Store screenshots need one re-shoot~~ ✅ **done — verified on device** | The old captures showed the *Photo access needed* banner (an app-op is not a grant) and `03-results.png` showed the developer's own library. After a real grant the set was re-shot over the generated demo library: **01-empty** (no tap needed — results and selection live in `ScannerViewModel`, so force-stop + relaunch returns to the empty state with the grant still in place), **02-scanning** (`5353 / 5385`), **03-results** (**17 groups, 54 of 5385 photos, 83.5 MB reclaimable**; the headline group's 43.1 MB out-ranks the device's own 39.8 MB, so no real photo is in frame) and **04-options**. Captures are taken by watching for UI **text** changes, because MIUI refuses synthetic taps (`INJECT_EVENTS`). The demo library is deleted from the test device afterwards — MediaStore **5,386 → 5,364** rows, and the 22 stale rows it leaves in the hash index are pruned by `PhotoIndexStore.pruneTo` on the next scan. Deliberately not captured: the staged state and the system confirmation dialog, because staging clears the demo group and would put real photos back in frame. Details: [STORE_LISTING](STORE_LISTING.md) | -| ~~Tablet store screenshots outstanding~~ ✅ **done — captured on AVDs** | Play has a **7-inch tablet** and a **10-inch tablet** screenshot slot of its own (asking for **≥ 4** screenshots on large screens). Both are now captured on AOSP Android 12 AVDs — `Nexus 7 2013` (1200×1920, `sw600dp`) and `medium_tablet` (1600×2560, `sw800dp`) — because this machine exposes no `/dev/kvm`: they ran in **pure software emulation** (`-accel off -no-window -gpu swiftshader_indirect`), ≈3 min to boot, with `hide_error_dialogs` on so SystemUI's ANR dialog could not sit in frame. Four screens per tablet over the same generated demo library: empty, scanning (20 / 22), results (**2 groups · 16 of 22 photos · 43.7 MB reclaimable**, 39.7 s / 53.1 s) and Options. `tools/make-store-screenshots.sh` is form-factor aware (`FORM_FACTOR=phone\|tablet-7in\|tablet-10in`) and the tablet form factors crop **0 px** of chrome, because a tablet frame is already inside Play's 2:1 cap. Recipe: [STORE_LISTING](STORE_LISTING.md) | +| **Remaining Play paperwork** | Console actions only, no code: the **hosted privacy policy URL** (the working copy is now published to Gitea as [`fishfacegit/foto-duplicate-finder`](https://gitea.softwareapp-hb.de/fishfacegit/foto-duplicate-finder), so the policy renders at a public, login-free URL and only the Console paste is left), **Data safety**, the **Photo/video permissions** declaration, the **content rating / audience / app access / ads / advertising ID / export** questions, and the **listing copy + the three screenshot sets** (phone, 7-inch and 10-inch, all captured), plus the **freemium setup**: publish the new listing at `de.softwareapp_hb.fotodup.finder.free` as **Free**, create and activate the one-time product `pro_no_ads`, add the AdMob app/banner unit and UMP message, set `legacyPro.cutoffEpochMs` to the first freemium release, and update the **Ads / Advertising ID / Data Safety** answers ([MONETIZATION](MONETIZATION.md)). The old paid listing at `.finder` and its €2.99 price/sale are left untouched. Confirm **Play App Signing for the new app** (the same upload key can sign both listings). Keystore, `versionCode`, listing copy, graphics, permission audit and the signed `.aab` (the 1.0.2 `versionCode` 3 build is historical; the 1.1.0 validation build is in [PLAY_RELEASE_CHECKLIST](PLAY_RELEASE_CHECKLIST.md) step 3) are in place; rollout goes internal → closed → production. Step-by-step: [PLAY_RELEASE_CHECKLIST](PLAY_RELEASE_CHECKLIST.md) | +| ~~Store screenshots need one re-shoot~~ ✅ **done for the paid build — freemium re-shoot pending** | The old captures showed the *Photo access needed* banner (an app-op is not a grant) and `03-results.png` showed the developer's own library. After a real grant the set was re-shot over the generated demo library: **01-empty** (no tap needed — results and selection live in `ScannerViewModel`, so force-stop + relaunch returns to the empty state with the grant still in place), **02-scanning** (`5353 / 5385`), **03-results** (**17 groups, 54 of 5385 photos, 83.5 MB reclaimable**; the headline group's 43.1 MB out-ranks the device's own 39.8 MB, so no real photo is in frame) and **04-options**. Captures are taken by watching for UI **text** changes, because MIUI refuses synthetic taps (`INJECT_EVENTS`). The demo library is deleted from the test device afterwards — MediaStore **5,386 → 5,364** rows, and the 22 stale rows it leaves in the hash index are pruned by `PhotoIndexStore.pruneTo` on the next scan. Deliberately not captured: the staged state and the system confirmation dialog, because staging clears the demo group and would put real photos back in frame. **The freemium build additionally needs the banner and the Pro sheet in frame; re-shoot before the 1.1.0 listing.** Details: [STORE_LISTING](STORE_LISTING.md) | +| ~~Tablet store screenshots outstanding~~ ✅ **done for the paid build — freemium re-shoot pending** | Play has a **7-inch tablet** and a **10-inch tablet** screenshot slot of its own (asking for **≥ 4** screenshots on large screens). Both are now captured on AOSP Android 12 AVDs — `Nexus 7 2013` (1200×1920, `sw600dp`) and `medium_tablet` (1600×2560, `sw800dp`) — because this machine exposes no `/dev/kvm`: they ran in **pure software emulation** (`-accel off -no-window -gpu swiftshader_indirect`), ≈3 min to boot, with `hide_error_dialogs` on so SystemUI's ANR dialog could not sit in frame. Four screens per tablet over the same generated demo library: empty, scanning (20 / 22), results (**2 groups · 16 of 22 photos · 43.7 MB reclaimable**, 39.7 s / 53.1 s) and Options. `tools/make-store-screenshots.sh` is form-factor aware (`FORM_FACTOR=phone\|tablet-7in\|tablet-10in`) and the tablet form factors crop **0 px** of chrome, because a tablet frame is already inside Play's 2:1 cap. Recipe: [STORE_LISTING](STORE_LISTING.md) | | **Device-only verifications** | RAW/DNG files, a *real* iPhone HEIC with a non-upright EXIF orientation, permission revoked mid-scan, and the Android 14 “Selected photos” flow. ✅ The **index-reuse** check is done: after a scan the index holds **5,363 rows, 5,357 with a perceptual hash**, and a second scan runs in **11.0 s vs 20.2 s** cold | ## Candidate milestones (proposed, not scheduled) @@ -47,8 +48,9 @@ Legend: ✅ done · 🚧 in progress · ⏳ not started · 💡 candidate (propo ## Suggested order 1. ✅ **Done** — the scan-stall hardening and the `BoundedCall` fix shipped as **1.0.1** - (`versionCode` 2). 1.0.2 (`versionCode` 3) is the build to upload, because Play has already - consumed code 2. Only the on-device re-check of the 5,363-photo scan remains. + (`versionCode` 2); **1.0.2** (`versionCode` 3) was the last paid build. The next upload is + **1.1.0** (`versionCode` 4), the freemium build, which also needs the Play Console changes in + [MONETIZATION](MONETIZATION.md). Only the on-device re-check of the 5,363-photo scan remains. 2. Finish the Play Console paperwork and roll out through **internal → closed → production**. 3. ✅ **Done** — **M10 store assets**: the icon and feature graphic are generated from the app's own vectors, the screenshot normaliser enforces Play's 2:1 limit, the listing copy is @@ -58,10 +60,12 @@ Legend: ✅ done · 🚧 in progress · ⏳ not started · 💡 candidate (propo and the 7-inch and 10-inch tablet sets were captured on AOSP AVDs in software emulation (1200×1920 and 1600×2560), so all three screenshot sets now exist. 4. **Colour signature** — the flat-colour false-positive fix. -5. ✅ **Done** — **M9 monetisation**: decided as a **one-time paid app (€2.99, launched with a 14-day - 50% sale at €1.49)**, which needs no code at all. The remaining work is Console-only — a payments - profile, the price and the launch sale on *Products > App pricing* — and the price has to be - confirmed before the next rollout, because free → paid stops being possible once the app has been - offered for free. +5. ✅ **Done — M9/M11 freemium**: free tier with one anchored AdMob banner, one-time + Play Billing `pro_no_ads` removes it, UMP consent, legacy paid-install + grandfathering, tests and docs. The remaining work is Console-only — publish the new + free listing at `.finder.free`, create/activate `pro_no_ads`, add the AdMob app/unit + and UMP message, set the legacy cutoff, update Ads/Advertising ID/Data Safety, and + re-shoot the store screenshots with the banner and Pro sheet. See + [MONETIZATION](MONETIZATION.md). Deliberately deferred: **video support** and the **“similar shots”** section. diff --git a/docs/STORE_LISTING.md b/docs/STORE_LISTING.md index 5dafcf9..ac92496 100644 --- a/docs/STORE_LISTING.md +++ b/docs/STORE_LISTING.md @@ -118,8 +118,8 @@ in `ScannerViewModel` (only the hash index is persisted), so force-stopping and returns to the empty state with the grant still in place: ```bash -adb shell am force-stop de.softwareapp_hb.fotodup.finder.debug -adb shell am start -n de.softwareapp_hb.fotodup.finder.debug/de.softwareapp_hb.fotodup.finder.MainActivity +adb shell am force-stop de.softwareapp_hb.fotodup.finder.free.debug +adb shell am start -n de.softwareapp_hb.fotodup.finder.free.debug/de.softwareapp_hb.fotodup.finder.MainActivity adb exec-out screencap -p > store-assets/raw-screenshots/phone/01-empty.png ``` @@ -192,7 +192,7 @@ adb shell settings put system user_rotation 3 # tablet10 only; the Nexus 7 is # 4. The phone set's prerequisites: the app, the permission, the demo library. adb install -r app/build/outputs/apk/debug/app-debug.apk -adb shell pm grant de.softwareapp_hb.fotodup.finder.debug android.permission.READ_EXTERNAL_STORAGE +adb shell pm grant de.softwareapp_hb.fotodup.finder.free.debug android.permission.READ_EXTERNAL_STORAGE python3 tools/make-demo-photos.py adb push demo-photos/foto-dup-demo /sdcard/DCIM/foto-dup-demo adb shell content call --uri content://media --method scan_file --arg /sdcard/DCIM/foto-dup-demo @@ -200,8 +200,8 @@ adb shell content call --uri content://media --method scan_file --arg /sdcard/DC # 5. Capture. `01` is one screencap. The other three need a tap, so their coordinates come from # `uiautomator dump` instead of guesswork, and a screencap burst *started before the tap* is what # catches the short scanning screen — 22 photos scan in seconds even under emulation. -adb shell am force-stop de.softwareapp_hb.fotodup.finder.debug -adb shell am start -n de.softwareapp_hb.fotodup.finder.debug/de.softwareapp_hb.fotodup.finder.MainActivity +adb shell am force-stop de.softwareapp_hb.fotodup.finder.free.debug +adb shell am start -n de.softwareapp_hb.fotodup.finder.free.debug/de.softwareapp_hb.fotodup.finder.MainActivity adb exec-out screencap -p > store-assets/raw-screenshots/tablet-7in/01-empty.png # ... burst frames into /tmp, tap "Start scan" (7-inch 600 1155, 10-inch 800 1465), keep the frame # showing "Looking for visually similar photos… N / 22" for 02 and the one after it for 03, @@ -292,21 +292,40 @@ enough, so the capture never depends on tap timing; that is how `04-options.png` ## App pricing -**Decision: a one-time paid app — a free download is off the table.** Foto Dup Finder is sold on -Google Play at a single price: no free tier, no trial, no subscription, no in-app purchase. Nothing -in this repository changes because of that decision — it lives in the Play Console, and the app -carries **no Billing code at all** (see [PLAY_RELEASE_CHECKLIST](PLAY_RELEASE_CHECKLIST.md) step 4). +**Current decision: freemium, as a new listing.** The freemium build uses +`applicationId = de.softwareapp_hb.fotodup.finder.free`, so it is a **new Play +listing**, separate from the old paid app at `de.softwareapp_hb.fotodup.finder`. +Publish it as **Free** (new apps are free by default); do not change the old paid +listing's price. The free tier shows one anchored adaptive AdMob banner; a one-time +in-app purchase (`pro_no_ads`) removes it. There is no subscription, no trial and no +account, and Pro only removes ads — every duplicate-finding, selection and deletion +feature stays free. -Why paid rather than free-with-a-Pro-unlock: +Why freemium replaced the paid listing: -- The app is a **single-purpose utility with no running costs** — no servers, no sync, no accounts — - so there is nothing a subscription would fund and nothing to keep charging for. -- Play Billing would merge `com.android.vending.BILLING` into the manifest and put a purchase screen - into an app whose whole pitch is "no account, no tracking, nothing leaves the device". A price on - the listing costs **zero permissions and changes zero Data Safety answers** — a claim no other - monetisation of this app can make. -- There is no ad SDK and there never will be: an ad SDK adds the `INTERNET` permission, and the - merged-manifest and Data Safety claims below would immediately stop being true. +- A free download is the only way to reach users who will not pay up front for a + single-purpose utility. The ad-supported tier funds the app; Pro gives the people + who value it a clean, ad-free experience. +- The purchase stays **one-time**, matching the old paid-app promise and avoiding a + subscription for something with no running server cost. +- Existing paid customers are grandfathered into Pro through the install-time cutoff + when the old paid app is still installed on the first freemium launch, so going free + does not take anything away from them. Customers who removed the old app need a + promo code or support flow. +- The cost is explicit: the ads SDK adds `INTERNET`, `ACCESS_NETWORK_STATE`, `AD_ID` + and the `ACCESS_ADSERVICES_*` permissions; Billing adds + `com.android.vending.BILLING`. The merged-manifest and Data Safety answers below + reflect that. + +**Play Console work:** set *Monetise › Products › App pricing* to **Free**, create +and activate the one-time product `pro_no_ads`, add the AdMob app/banner unit and a +UMP message, and update the **Ads**, **Advertising ID** and **Data Safety** +declarations. Full steps: [MONETIZATION](MONETIZATION.md). The price is read from Play +at runtime, so no code change is needed to change it. + +> **Historical record — the paid-app rationale below is superseded.** It is kept for +> the release history, not as current guidance. The app is no longer sold once, does +> carry Billing and ads, and no longer has the "no INTERNET permission" claim. ⚠️ **The choice is only reversible while the app has not been offered for free.** Play's rule, from *Set up your app's prices*: *“You can change your app from paid to free. Once your app has been @@ -420,28 +439,38 @@ time. Use a promo code, never a real purchase, for your own end-to-end buying te ### Short description (max 80 characters) - Find and remove duplicate photos. Ad-free, works offline, no uploads. + Find duplicate photos. Free with ads; Pro removes them. -Alternative, if the no-account promise should lead: +Alternative, if the privacy promise should lead: - Find and delete duplicate photos. No ads, no uploads, no account. + Find duplicate photos, offline. Free with ads; optional ad-free Pro. -Neither option may say "free": the app is paid, so the claim would simply be false. Play's metadata -policy also bans price and promotional wording in the **app title, icon and developer name** -("free for limited time only" is its own example), which is why the price story below lives in the -description body and is written as a plain statement of fact — no discounts, no urgency, nothing -that reads as a promotion. +The two options are **55** and **68** characters, both inside Play's 80-character +limit. The app is free to download, so “free” is accurate now. Play's metadata policy +still bans price and promotional wording in the **app title, icon and developer name** +(“free for limited time only” is its own example); the free/Pro distinction belongs +in the description body, stated as fact rather than as an urgency device. ### Full description (max 4000 characters) - Find and remove duplicate photos, then get the space back. Foto Dup Finder does one - job and does it without ads, without an account and without ever uploading anything. +The draft below is **2,701 characters**, leaving room for review or a new feature +paragraph. + + Find and remove duplicate photos, then get the space back. Foto Dup Finder does + one job, keeps your photos on your device, and gives you a clean, ad-free + experience with a one-time Pro purchase. + + FREE WITH ONE BANNER, PRO WITHOUT ADS + • The free tier has every feature and one small banner at the bottom. + • A one-time Pro purchase removes the banner. No subscription, no account. + • Nothing is locked behind Pro — scanning, selecting and deleting stay free. WHY IT IS DIFFERENT - • Pay once, then own it. No ads, no banners, no interstitials, no subscriptions and no - in-app purchases — there is nothing else to buy, now or later. - • No internet permission at all, so the app has no way to upload your photos. - • No account, no sign-in, no tracking, no analytics. + • Your photos never leave your device. Only the optional ad/consent SDK and + Google Play Billing use the network. + • No account, no sign-in, no app-level tracking or analytics. The ads SDK's data + use is described in the privacy policy. + • No in-app currency, no subscription, nothing else to buy. WHAT IT DOES • Finds exact copies: files that are byte-for-byte identical, even when their names @@ -468,29 +497,27 @@ that reads as a promotion. 4. Tap "Remove all selected" and confirm once for the whole batch. YOUR PHOTOS STAY YOURS - Foto Dup Finder declares no internet permission, ships no advertising or analytics - SDKs, and stores nothing besides a local index of file hashes so the next scan can be - quick. No photo ever leaves your phone, and uninstalling the app removes the index - with it. + Foto Dup Finder stores nothing besides a local index of file hashes so the next + scan can be quick. No photo ever leaves your phone, and uninstalling the app + removes the index with it. Ads and purchases need a connection; finding duplicates + does not. GOOD TO KNOW • Requires Android 8.0 or newer. - • Sold through Google Play as a one-time purchase — no subscription, no in-app - purchases, no account. + • Free to download. One optional one-time Pro purchase removes the banner. • Photos moved to the trash can be restored from your gallery app until the trash is emptied (Android 11 and newer). - • Works fully offline, in flight mode, always. + • Duplicate scanning works fully offline, in flight mode, always. -Every claim above is checkable against this repository: no `INTERNET` permission in the -merged manifest, no ad or analytics dependency in `gradle/libs.versions.toml`, `minSdk 26` -in `app/build.gradle.kts`, and the second-run speed-up is the persistent hash index in -`data/PhotoIndexStore.kt`. +Every claim above is checkable against this repository: the ad/Billing dependencies in +`gradle/libs.versions.toml`, the merged-manifest permissions (including `INTERNET`, +`AD_ID` and `BILLING`), `minSdk 26` in `app/build.gradle.kts`, and the second-run speed-up is +the persistent hash index in `data/PhotoIndexStore.kt`. -The price is the one claim that is *not* in here, because it is a Play Console setting -(`Products > App pricing`) rather than code. What *is* checkable is the rest of the monetisation -story — the absence of it: no Billing dependency in `gradle/libs.versions.toml`, and no -`com.android.vending.BILLING` in the merged manifest (see -[PLAY_RELEASE_CHECKLIST](PLAY_RELEASE_CHECKLIST.md) step 5). +The price is *not* in the app: it is a Play Console setting (and Play's localized +`formattedPrice` is what the Pro sheet shows). The product id **`pro_no_ads`** is in +`monetization/ProProduct.kt`; the free/Pro gate, consent and Data Safety answers are +documented in [MONETIZATION](MONETIZATION.md). ### Category and tags @@ -510,7 +537,7 @@ story — the absence of it: no Billing dependency in `gradle/libs.versions.toml | Tag | Verdict | Reason | |---|---|---| | **Photography** | ✅ use | The app's subject *is* the user's photo library, and someone who reads "find duplicate photos" sees immediately why the tag is there. This is the only photo-domain tag that applies. Available while the category is *Tools*; if the category is *Photography* it is the category itself and therefore redundant. | - | **Privacy & security** | ⚠️ optional | Defensible: the listing *leads* with "no internet permission at all", "no account, no tracking, no analytics", and that is visible to an unfamiliar user — Google's test. But it pulls in people browsing privacy tools who are not after a photo cleaner. Add it only if that discovery surface is wanted. | + | **Privacy & security** | ⚠️ optional | Defensible: the listing leads with on-device photo processing, “no account, no tracking, no analytics” and “your photos never leave your device”. That is visible to an unfamiliar user — Google's test. But it pulls in people browsing privacy tools who are not after a photo cleaner, and the app now has ads, so the claim is narrower than it used to be. Add it only if that discovery surface is wanted. | | *anything else* | ❌ | Nothing else in the list describes this app; see below. | Tags cannot express *"duplicate"* at all, so **search discovery rests on the title and short diff --git a/docs/codemap.md b/docs/codemap.md new file mode 100644 index 0000000..dc17274 --- /dev/null +++ b/docs/codemap.md @@ -0,0 +1,496 @@ +# Foto Dup Finder — Code Map + +A navigable map of the freemium Android app: its static dependency structure, the +scan pipeline, the two-step deletion flow, and the free/Pro monetisation paths. + +> **Status:** living document. Update it whenever a module, permission, product id, +> scan phase or ownership rule changes. The standalone graph is +> [`codemap.mmd`](codemap.mmd); agent-specific rules live in +> [`../AGENTS.md`](../AGENTS.md). + +## 1. Reading guide + +| Notation | Meaning | +|---|---| +| Solid arrow `A --> B` | compile-time import/dependency or a direct runtime call | +| Dotted arrow `A -.-> B` | implements a contract, indirect use, or an external SDK/service | +| `subgraph` | architectural layer or feature area | +| `[(...)]` | external resource: MediaStore, SQLite, SharedPreferences, Google services | +| `free`/`pro` | the two monetisation states; they differ **only** by the banner | + +Mermaid renders natively on GitHub, GitLab, Gitea and VS Code's Markdown preview. +The full standalone graph is [`codemap.mmd`](codemap.mmd); the diagrams below focus +on the flows that are hard to read from a static graph. + +## 2. Layered architecture + +```mermaid +flowchart TB + subgraph ENTRY["Entry"] + app["FotoDupApplication
ScanController + ProStore + AdsController"] + main["MainActivity
edge-to-edge, consent, purchase refresh"] + end + + subgraph UI["UI — Compose"] + screen["ScannerScreen"] + vm["ScannerViewModel"] + sections["ScannerSections"] + groups["GroupSection"] + banner["BannerAdSlot"] + proSheet["ProSheet"] + end + + subgraph DOMAIN["Domain"] + controller["ScanController"] + engine["ScanEngine"] + models["ScanModels"] + end + + subgraph DATA["Data"] + source["MediaStorePhotoSource"] + hasher["PhotoHasher"] + index["PhotoIndexStore"] + deleter["MediaDeleter"] + end + + subgraph CORE["Core — pure Kotlin"] + hashing["Hashing"] + perceptual["PerceptualHash"] + rgb["RgbDHash"] + grouper["DuplicateGrouper"] + policy["DuplicatePolicy"] + end + + subgraph MONETIZATION["Monetization"] + proStore["ProStore"] + ads["AdsController"] + adPolicy["AdPolicy"] + legacy["LegacyPro"] + end + + mediaStore[("MediaStore")] + db[("photo_index.db")] + prefs[("pro_entitlement prefs")] + play[("Play Billing")] + admob[("AdMob")] + ump[("UMP")] + + main --> app + main --> screen + main --> ads + screen --> vm + screen --> banner + screen --> proSheet + vm --> controller + vm --> proStore + vm --> ads + vm --> deleter + controller --> engine + controller --> models + engine --> source + engine --> hasher + engine --> index + engine --> grouper + engine --> policy + source -.-> mediaStore + hasher -.-> mediaStore + index -.-> db + hasher --> hashing + hasher --> perceptual + hasher --> rgb + grouper --> policy + banner --> adPolicy + proStore --> legacy + proStore -.-> prefs + proStore -.-> play + ads -.-> ump + ads -.-> admob +``` + +### Layer responsibilities + +| Layer | Owns | Must not do | +|---|---|---| +| `core/` | hashing, dHash/pHash, grouping, thresholds, decode maths | import Android | +| `data/` | MediaStore, file reads, SQLite cache, deletion requests, permissions | decide UI policy | +| `domain/` | scan orchestration, process-scoped scan state, progress models | know about Compose | +| `service/` | foreground-service notification for a running scan | contain scan logic | +| `monetization/` | UMP consent, Mobile Ads init, Play Billing entitlement, legacy cutoff | decide scan/delete behaviour | +| `ui/` | Compose screen, selection/staging, ad slot, Pro sheet | hash or delete photos directly | +| `text/` | enum-to-resource mappings shared by UI and notification | contain user-visible literals | + + +## 3. Compile-time dependency graph + +The standalone [`codemap.mmd`](codemap.mmd) is the complete node/edge graph. The +allowed direction of dependencies is intentionally narrow: + +| From | May depend on | Notes | +|---|---|---| +| `core/` | Kotlin + `java.security`/`java.io` only | no Android imports; covered by JVM tests | +| `data/` | `core/` | Android framework + MediaStore access lives here | +| `domain/` | `core/`, `data/` | no Compose, no Activity | +| `service/` | `domain/`, `R`, notification APIs | mirrors `ScanController`, no scan logic | +| `monetization/` | Android SDKs, Play Billing, UMP, Ads, `BuildConfig`, `R` | no photo access | +| `ui/` | `core/`, `data/`, `domain/`, `monetization/`, `text/` | the only layer that knows Compose | +| `text/` | `core/`, `domain/`, `R` | maps enums to strings for UI *and* notification | + +Two consequences worth preserving: + +- `core/` stays testable on a plain JVM. The benchmark and edge-case harnesses rely + on that, as do the fast unit tests. +- The ad/Billing layer never touches the photo pipeline. A failed ad request, a + refused consent or an unavailable Play Store cannot stop a scan or a deletion. + +## 4. Scan runtime flow + +```mermaid +sequenceDiagram + actor User + participant UI as ScannerScreen + participant VM as ScannerViewModel + participant SC as ScanController + participant SVC as ScanService + participant SE as ScanEngine + participant MS as MediaStorePhotoSource + participant PH as PhotoHasher + participant IDX as PhotoIndexStore + participant DG as DuplicateGrouper + + User->>UI: Scan + UI->>VM: startScan() + VM->>SC: start(policy) + SC->>SVC: start foreground service + SC->>SE: scan(policy) + SE->>MS: loadPhotos() + MS-->>SE: List + SE->>IDX: loadAll() + IDX-->>SE: cached IndexEntry rows + SE->>SE: group by size (exact candidates only) + SE->>PH: quick signatures (same-size candidates) + PH->>MS: read first/last 32 KB + SE->>PH: SHA-256 (buckets with 2+ members) + SE->>PH: pHash + RGB dHash (one decode each) + PH->>MS: thumbnail or fallback decode + SE->>IDX: upsert + pruneTo() + SE->>DG: group(exact, perceptual, policy, fit) + DG-->>SE: List + SE-->>SC: ScanProgress.Finished(ScanResult) + SC-->>VM: StateFlow + VM-->>UI: groups, summary, selection + SC->>SVC: stop foreground service +``` + +### Phases + +| Phase | What runs | Parallel? | +|---|---|---| +| `LOADING` | `MediaStorePhotoSource.loadPhotos()` | no | +| `SIGNATURES` | cheap size + head/tail signature, only same-size candidates | yes, CPU-bound | +| `CONTENT` | full SHA-256, only signature buckets with 2+ members | yes | +| `PERCEPTUAL` | pHash + RGB dHash for every readable photo (skipped for `EXACT_ONLY`) | yes | +| `GROUPING` | union-find clustering, adaptive threshold fit | no | + +`ScanController` owns the only running scan. It survives activity recreation and +keeps going when the app is backgrounded because `ScanService` holds a `dataSync` +foreground service for the duration. The ViewModel only mirrors progress; it never +owns the scan. + +Three failure boundaries matter: + +- `BoundedCall` gives every provider call a deadline, so one wedged file cannot + freeze the scan. +- `withTimeoutOrNull` around per-photo hashing skips a photo that is too expensive + to decode. +- A failed photo is counted in `ScanResult.unreadableCount`; it does not abort the + scan. + + + +## 5. Monetisation flow + +### 5.1 Free tier: consent before any ad request + +```mermaid +flowchart TD + launch["App launch"] --> cache{"Cached Pro or
legacy paid install?"} + cache -->|yes| noAds["No ad SDK init
BannerAdSlot absent"] + cache -->|no| consent["ConsentInformation
requestConsentInfoUpdate()"] + consent --> form["loadAndShowConsentFormIfRequired()"] + form --> can{"canRequestAds()?"} + can -->|no| noAds + can -->|yes| init["MobileAds.initialize()"] + init --> gate{"AdPolicy.shouldShowBanner()
!isPro && consent && initialized"} + gate -->|true| banner["BannerAdSlot
anchored adaptive AdView"] + gate -->|false| noAds +``` + +The gate is deliberately conservative. A missing network, a missing Play services +install, a consent refusal or a failed SDK init all end at **no banner**, never at a +crash or a blank placeholder. `AdPolicy` is a pure function and is unit-tested +without Android. + +### 5.2 Pro: one-time purchase + +```mermaid +sequenceDiagram + actor User + participant Sheet as ProSheet + participant VM as ScannerViewModel + participant Store as ProStore + participant Play as Google Play Billing + + User->>Sheet: Buy Pro / Buy for €X + Sheet->>VM: purchasePro(activity) + VM->>Store: purchase(activity) + Store->>Play: queryProductDetailsAsync(pro_no_ads) + Play-->>Store: ProductDetails + formattedPrice + Store->>Play: launchBillingFlow(activity, productDetails) + Play-->>User: Play purchase sheet + Play-->>Store: onPurchasesUpdated(result, purchases) + Store->>Store: filter product id, require PURCHASED + Store->>Play: acknowledgePurchase(token) + Store-->>VM: ProState(isPro = true, priceText = ...) + VM-->>Sheet: state update + Sheet-->>User: closes, banner removed +``` + +**Purchase states that matter** + +| Play result | What `ProStore` does | +|---|---| +| `PURCHASED` | grants Pro locally, acknowledges, removes the banner immediately | +| `PENDING` | does **not** grant Pro; shows `message_purchase_pending` | +| `USER_CANCELED` | no grant, no error message | +| `ITEM_ALREADY_OWNED` | refreshes purchases and grants if Play reports the product | +| `SERVICE_DISCONNECTED` / unavailable | keeps the cached entitlement, shows an unavailable message | + +Acknowledgement is retried from `KEY_PENDING_ACK` on the next refresh. Play refunds +an unacknowledged one-time purchase after three days, so this retry is not optional. + + + +### 5.3 Entitlement state machine + +```mermaid +stateDiagram-v2 + [*] --> Free + Free --> Pending: purchase returns PENDING + Pending --> Pro: Play later reports PURCHASED + Pending --> Free: payment cancelled + Free --> Pro: purchase PURCHASED + Pro --> Free: successful Play query returns no purchase + Pro --> Pro: offline / query failure (cached entitlement kept) + Free --> Pro: legacy install before cutoff + note right of Pro + Legacy Pro is independent of Play. + It is never revoked by a purchase query. + end note +``` + +### 5.4 Monetisation classes + +| Class | Responsibility | Never does | +|---|---|---| +| `ProStore` | Billing connection, product details, purchase, acknowledgement, cached entitlement, legacy migration | read photos or decide UI | +| `AdsController` | UMP consent update/form, `MobileAds.initialize`, privacy-options form | request an ad itself | +| `AdPolicy` | pure banner gate (`!isPro && canRequestAds && initialized`) | touch Android | +| `LegacyPro` | pure install-time cutoff predicate | know about Billing | +| `BannerAdSlot` | one `AdView`, adaptive size, pause/resume/destroy | reload on recomposition | +| `ProSheet` | price, benefits, buy/restore, pending/unavailable states | gate a scan feature | + +### 5.5 Legacy paid installs + +The app was previously sold as a one-time paid app. Play does not expose "this app +was bought as paid" through Billing, so the best available signal is +`PackageInfo.firstInstallTime`: + +- set `legacyPro.cutoffEpochMs` to the instant of the first freemium release; +- every install older than that instant is treated as a paid install and gets Pro; +- `KEY_ORIGIN_RESOLVED` persists the decision so a later Play query cannot revoke it; +- a cutoff of `0` disables the migration. + +Known limits: uninstall/reinstall, clearing app data, or a restore that resets +`firstInstallTime` loses the grandfather. A server-side purchase history would be +stronger, but it contradicts the app's no-account, no-backend design. + + + +## 6. Two-step deletion flow + +```mermaid +sequenceDiagram + actor User + participant UI as ScannerScreen + participant VM as ScannerViewModel + participant SC as ScanController + participant MD as MediaDeleter + participant OS as Android system dialog + participant MS as MediaStore + + User->>UI: Tick photos + UI->>VM: toggleSelected(id) + User->>UI: Remove all selected + UI->>VM: markSelectedForRemoval() + VM->>VM: markedForRemovalIds += selectedIds + Note over VM: rows disappear from the list
nothing is deleted yet + User->>UI: Apply + UI->>VM: applyMarkedForRemoval() + VM->>MD: createDeleteRequest(uris, useTrash) + MD->>OS: createDeleteRequest / createTrashRequest + OS-->>User: one confirmation for the whole batch + User-->>OS: Allow + OS-->>VM: onSystemDeleteResult(confirmed = true) + VM->>SC: removePhotos(deletedIds) + SC-->>VM: result without deleted rows + VM->>MS: rows already removed by the system + VM-->>UI: selected/marked sets pruned +``` + +Rules that must not change: + +- Staging is **not** deletion. No system dialog appears until **Apply**. +- Android 11+ always goes through `MediaStore.createDeleteRequest` or + `createTrashRequest`. The app never requests `MANAGE_EXTERNAL_STORAGE`. +- The banner lives below the action bar and is separated by padding, so it cannot + intercept an Apply tap. +- A fresh scan clears stale staging, because the row ids belong to the old result. + +## 7. Local persistence + +| Store | Owner | Content | Backup | +|---|---|---|---| +| `photo_index.db` (`photo_index` table) | `PhotoIndexStore` | MediaStore id, size, modified stamp, quick signature, SHA-256, pHash, RGB dHash | **excluded** from backup/transfer; it is device-specific cache | +| `pro_entitlement` SharedPreferences | `ProStore` | `is_pro`, `legacy_pro`, `install_origin_resolved`, `pending_ack_token` | included in Android backup; Play re-verifies on the next connection | +| UMP consent state | Google UMP SDK | consent choices / privacy-options requirement | managed by the SDK | +| AdMob / Billing SDK state | Google SDKs | ad and purchase caches | managed by the SDKs | +| Scan results | `ScanController` (memory only) | groups + record map | lost on process death; a re-scan rebuilds it | + +The index is a **cache**, never a source of truth. `DB_VERSION` must be bumped when +the meaning of a stored hash changes; `onUpgrade` drops and rebuilds the table. +Photo pixels are never written to the database or to preferences. + + + +## 8. File index + +Paths are relative to `app/src/main/java/de/softwareapp_hb/fotodup/finder/` unless noted. + +| File | Responsibility | +|---|---| +| `FotoDupApplication.kt` | creates the three process-scoped singletons: `ScanController`, `ProStore`, `AdsController` | +| `MainActivity.kt` | edge-to-edge, starts consent/ad init for free users, refreshes purchases on resume, hosts `ScannerScreen` | +| **core/** | | +| `core/Hashing.kt` | cheap size/head/tail signature + SHA-256 | +| `core/PerceptualHash.kt` | 64-bit pHash via 32×32 grayscale → DCT → 8×8 block | +| `core/RgbDHash.kt` | one 64-bit difference hash per colour channel | +| `core/PhotoFingerprint.kt` | bundles the pHash and RGB dHash for one photo | +| `core/DuplicateGrouper.kt` | exact + perceptual grouping, banded candidates, union-find, per-scan threshold fit | +| `core/DuplicateGroup.kt` | group model, suggested keep/remove, display order | +| `core/DuplicatePolicy.kt` | Exact / Balanced / Aggressive presets | +| `core/AdaptiveThreshold.kt` | fits the pHash cut to the candidate population | +| `core/DisjointSet.kt` | union-find | +| `core/DecodeMath.kt` | decode/downscale maths shared by the hasher and tests | +| `core/ByteUtils.kt` | bounded stream reads | +| **data/** | | +| `data/MediaStorePhotoSource.kt` | MediaStore query → `PhotoRecord` | +| `data/PhotoRecord.kt` | photo metadata + content URI | +| `data/PhotoHasher.kt` | signature, SHA-256, thumbnail/fallback decode, perceptual hashes | +| `data/PhotoIndexStore.kt` | SQLite `photo_index` cache (`DB_VERSION 3`) | +| `data/MediaDeleter.kt` | `createDeleteRequest` / `createTrashRequest`, legacy API 26–29 delete | +| `data/AppPermissions.kt` | full/partial/none access state and requestable permission list | +| `data/BoundedCall.kt` | hard deadline + stalled-provider breaker | +| **domain/** | | +| `domain/ScanController.kt` | process-scoped scan state, start/cancel, `removePhotos`, error clearing | +| `domain/ScanEngine.kt` | tiered scan pipeline | +| `domain/ScanModels.kt` | `ScanPhase`, `ScanProgress`, `ScanResult`, `ScanTimings` | +| `domain/Parallel.kt` | bounded parallel fan-out for CPU work | +| **service/** | | +| `service/ScanService.kt` | `dataSync` foreground service + progress notification + Cancel action | +| **monetization/** | | +| `monetization/ProProduct.kt` | `pro_no_ads` id and preference keys | +| `monetization/ProStore.kt` | Billing connection, purchase/acknowledge/restore, entitlement cache, legacy migration | +| `monetization/ProState.kt` | Pro UI state | +| `monetization/AdsController.kt` | UMP consent + Mobile Ads init + privacy options | +| `monetization/AdsState.kt` | consent/init state | +| `monetization/AdPolicy.kt` | pure banner gate | +| `monetization/LegacyPro.kt` | pure paid-install cutoff predicate | +| **text/** | | +| `text/TextRes.kt` | `ScanPhase` / `DuplicatePolicy` → string resource | +| **ui/** | | +| `ui/scanner/ScannerScreen.kt` | scaffold, permissions, options menu, Pro entry, bottom slot, Pro sheet | +| `ui/scanner/ScannerViewModel.kt` | selection, staging, deletion, Pro actions, state collection | +| `ui/scanner/ScannerUiState.kt` | all scanner state including `pro` and `ads` | +| `ui/scanner/ScannerSections.kt` | access banner, progress, empty state | +| `ui/scanner/GroupSection.kt` | summary card, group cards, staging buttons | +| `ui/components/PhotoThumbnail.kt` | selectable photo tile | +| `ui/components/ContextExt.kt` | `Context.findActivity()` for Billing/UMP | +| `ui/ads/BannerAdSlot.kt` | adaptive `AdView`, lifecycle, no ad for Pro/refused consent | +| `ui/pro/ProSheet.kt` | benefits, localized price, buy/restore, pending/unavailable | +| `ui/theme/*` | Material 3 theme, colours, type, edge-to-edge | +| **debug/** | | +| `src/debug/.../DebugScanTrigger.kt` | adb-driven scan for the test device | +| `src/debug/.../DebugProToggle.kt` | adb-driven free/Pro switch | +| **tests** | | +| `app/src/test/.../core/*` | hashing, pHash, grouping, threshold, group maths | +| `app/src/test/.../data/BoundedCallTest.kt` | provider deadline/breaker | +| `app/src/test/.../domain/ScanEngineEndToEndTest.kt` | real pipeline against `FakeMediaStoreProvider` | +| `app/src/test/.../monetization/AdPolicyTest.kt` | banner gate | +| `app/src/test/.../monetization/LegacyProTest.kt` | grandfathered-install boundaries | +| `app/src/test/.../bench/*` | opt-in similarity/scale benchmark harness | + + + +## 9. Change-impact matrix + +| Change | Primary files | Required checks | +|---|---|---| +| Hash algorithm / signature | `core/Hashing.kt`, `data/PhotoHasher.kt` | `HashingTest`, `ScanEngineEndToEndTest`, `DB_VERSION` bump | +| pHash / RGB dHash | `core/PerceptualHash.kt`, `core/RgbDHash.kt`, `data/PhotoHasher.kt` | `PerceptualHashTest`, benchmark, `DB_VERSION` bump | +| Grouping / threshold fit | `core/DuplicateGrouper.kt`, `core/AdaptiveThreshold.kt`, `core/DuplicatePolicy.kt` | `DuplicateGrouperTest`, `AdaptiveThresholdTest`, `GroupingScaleTest` | +| Scan pipeline stage | `domain/ScanEngine.kt`, `domain/ScanModels.kt`, `text/TextRes.kt`, `strings.xml` | `ScanEngineEndToEndTest`, progress UI/notification | +| SQLite schema | `data/PhotoIndexStore.kt` | `DB_VERSION` bump, end-to-end test, `pruneTo` path | +| Permission set | `AndroidManifest.xml`, `data/AppPermissions.kt` | merged-manifest audit, Play checklist, `PRIVACY.md` | +| Ad placement / format | `ui/ads/BannerAdSlot.kt`, `ui/scanner/ScannerScreen.kt` | `AdPolicyTest`, device with Play services, policy review | +| Consent / privacy options | `monetization/AdsController.kt`, `strings.xml` | UMP debug geography, `PRIVACY.md`, Data Safety | +| Product id / price | `monetization/ProProduct.kt`, Play Console | `MONETIZATION.md`, internal-track purchase, restore test | +| Entitlement / legacy cutoff | `monetization/ProStore.kt`, `monetization/LegacyPro.kt`, build config | `LegacyProTest`, purchase/refund/offline cases | +| Pro UI | `ui/pro/ProSheet.kt`, `ui/scanner/ScannerViewModel.kt` | free/Pro/debug toggle, pending/unavailable states | +| Version / release | `app/build.gradle.kts`, `CHANGELOG.md` | `versionCode` higher, `assembleRelease`, `bundleRelease` | +| Codemap | `docs/codemap.md`, `docs/codemap.mmd` | Mermaid syntax, architecture review | +| Agent rules | `AGENTS.md` | commands and invariants still true | + +## 10. Runtime ownership rules + +- **ScanController** is the only owner of the running scan and its result. The + ViewModel mirrors it; it must never start a second scan or keep its own result. +- **ScannerViewModel** owns selection, staging, expanded groups and the delete + dialog hand-off. These are UI concerns and survive configuration changes. +- **ProStore** is the only owner of the entitlement. The UI renders + `ProState.isPro`; it must never guess Pro from a local flag or a price string. +- **AdsController** is the only owner of consent and SDK initialisation. + `BannerAdSlot` owns the `AdView` lifecycle and requests exactly one banner. +- **MediaDeleter** owns the system consent request. No other class may delete a + photo or bypass the two-step staging flow. +- **ScanService** mirrors `ScanController`; it contains no scanning logic. +- **core/** stays pure Kotlin. A new Android import there is an architecture bug. + +## 11. Keeping the map accurate + +When a module, permission, product or flow changes: + +1. Update the affected node/edge in [`codemap.mmd`](codemap.mmd). +2. Update the matching diagram, file index and change-impact row here. +3. Update [`../AGENTS.md`](../AGENTS.md) if an architectural rule or command changed. +4. Update `README.md`, `PRIVACY.md`, `CHANGELOG.md`, `docs/ROADMAP.md`, + `docs/MONETIZATION.md`, `docs/STORE_LISTING.md` and + `docs/PLAY_RELEASE_CHECKLIST.md` when the change affects users, permissions, + monetisation or release steps. +5. Verify the Mermaid syntax in a Markdown preview before committing. +6. Run `./gradlew :app:testDebugUnitTest :app:lintDebug :app:assembleDebug`. + +> The map describes the current freemium build. Deferred features (video +> duplicates, a separate "similar shots" list, subscriptions) are **not** implied +> by it and must be added explicitly when they land. + + diff --git a/docs/codemap.mmd b/docs/codemap.mmd new file mode 100644 index 0000000..7cb055c --- /dev/null +++ b/docs/codemap.mmd @@ -0,0 +1,164 @@ +%% Foto Dup Finder — standalone code map +%% Render with a Mermaid-enabled Markdown preview, GitHub/GitLab, or the Mermaid CLI. +%% Full narrative, runtime flows and change-impact matrix: docs/codemap.md +flowchart TB + + subgraph ENTRY["App entry"] + app["FotoDupApplication
process singletons"] + main["MainActivity
edge-to-edge + consent"] + theme["FotoDupTheme"] + end + + subgraph UI["UI — Jetpack Compose"] + screen["ScannerScreen
permissions, scaffold, menu"] + vm["ScannerViewModel
selection, deletion, Pro actions"] + uiState["ScannerUiState"] + sections["ScannerSections
banner, progress, empty state"] + groups["GroupSection
summary + group cards"] + thumb["PhotoThumbnail"] + banner["BannerAdSlot
adaptive AdView"] + proSheet["ProSheet
one-time purchase"] + textRes["text/TextRes"] + end + + subgraph DOMAIN["Domain"] + scanController["ScanController
process-scoped scan owner"] + scanEngine["ScanEngine
tiered pipeline"] + scanModels["ScanModels
progress, result, phase"] + parallel["Parallel
bounded CPU fan-out"] + end + + subgraph SERVICE["Service"] + scanService["ScanService
dataSync foreground service"] + end + + subgraph DATA["Data — Android"] + mediaSource["MediaStorePhotoSource"] + hasher["PhotoHasher
signature, SHA-256, pHash"] + indexStore["PhotoIndexStore
SQLite hash cache"] + deleter["MediaDeleter
system consent"] + permissions["AppPermissions"] + bounded["BoundedCall
provider deadlines"] + photoRecord["PhotoRecord"] + end + + subgraph CORE["Core — pure Kotlin, no Android imports"] + hashing["Hashing
quick + SHA-256"] + phash["PerceptualHash
64-bit pHash"] + rgb["RgbDHash
RGB difference hashes"] + grouper["DuplicateGrouper
union-find + fit"] + policy["DuplicatePolicy"] + adaptive["AdaptiveThreshold"] + group["DuplicateGroup"] + dsu["DisjointSet"] + decode["DecodeMath"] + bytes["ByteUtils"] + fingerprint["PhotoFingerprint"] + end + + subgraph MONETIZATION["Monetization"] + proStore["ProStore
Billing + entitlement cache"] + adsController["AdsController
UMP + Mobile Ads"] + proState["ProState"] + adsState["AdsState"] + adPolicy["AdPolicy
banner gate"] + legacy["LegacyPro
paid-install cutoff"] + product["ProProduct
pro_no_ads"] + end + + subgraph DEBUG["Debug only"] + debugScan["DebugScanTrigger"] + debugPro["DebugProToggle"] + end + + mediaStore[("MediaStore
photo library")] + sqlite[("photo_index.db")] + prefs[("pro_entitlement
SharedPreferences")] + admob[("Google AdMob")] + ump[("Google UMP")] + play[("Google Play Billing")] + notification[("Scan notification")] + + + app --> scanController + app --> proStore + app --> adsController + + main --> app + main --> screen + main --> theme + main --> adsController + + screen --> vm + screen --> sections + screen --> groups + screen --> banner + screen --> proSheet + screen --> theme + screen --> textRes + + vm --> uiState + vm --> scanController + vm --> proStore + vm --> adsController + vm --> deleter + + sections --> uiState + sections --> textRes + groups --> uiState + groups --> thumb + banner --> adPolicy + proSheet --> proState + + scanController --> scanEngine + scanController --> scanService + scanController --> scanModels + scanEngine --> scanModels + scanEngine --> parallel + scanEngine --> mediaSource + scanEngine --> hasher + scanEngine --> indexStore + scanEngine --> grouper + scanEngine --> policy + scanEngine --> adaptive + scanEngine --> group + scanService --> scanController + scanService --> notification + + mediaSource --> photoRecord + mediaSource --> permissions + mediaSource --> bounded + mediaSource -.->|query| mediaStore + hasher --> hashing + hasher --> phash + hasher --> rgb + hasher --> fingerprint + hasher --> decode + hasher --> bounded + hasher -.->|read bytes and thumbnails| mediaStore + indexStore --> photoRecord + indexStore -.->|SQLite| sqlite + deleter -.->|system delete request| mediaStore + + hashing --> bytes + phash --> decode + rgb --> decode + grouper --> group + grouper --> dsu + grouper --> policy + grouper --> adaptive + group --> fingerprint + + proStore --> product + proStore --> proState + proStore --> legacy + proStore -.->|query purchases and acknowledge| play + proStore -.->|entitlement cache| prefs + adsController --> adsState + adsController -.->|consent form| ump + adsController -.->|initialize| admob + banner -.->|AdView request| admob + + debugScan -.-> scanController + debugPro -.-> proStore + diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 7ffbb19..fac9442 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -18,6 +18,14 @@ coil = "3.5.0" # Kotlin libraries coroutines = "1.9.0" +# Monetisation. +# play-services-ads 25.5.0 requires minSdk 24 and compileSdk 34+, so it fits this app +# (minSdk 26, compileSdk 36). It is the stable legacy SDK; the GMA Next-Gen SDK is the +# migration path, but it is a different API surface and adds READ_BASIC_PHONE_STATE. +playServicesAds = "25.5.0" +userMessagingPlatform = "4.0.0" +billing = "9.1.0" + # Testing junit = "4.13.2" robolectric = "4.17" @@ -44,6 +52,10 @@ kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx- coil-compose = { group = "io.coil-kt.coil3", name = "coil-compose", version.ref = "coil" } +play-services-ads = { group = "com.google.android.gms", name = "play-services-ads", version.ref = "playServicesAds" } +user-messaging-platform = { group = "com.google.android.ump", name = "user-messaging-platform", version.ref = "userMessagingPlatform" } +billing-ktx = { group = "com.android.billingclient", name = "billing-ktx", version.ref = "billing" } + junit = { group = "junit", name = "junit", version.ref = "junit" } robolectric = { group = "org.robolectric", name = "robolectric", version.ref = "robolectric" } diff --git a/local.properties.example b/local.properties.example new file mode 100644 index 0000000..13bd821 --- /dev/null +++ b/local.properties.example @@ -0,0 +1,15 @@ +## This file is machine-specific and must NOT be committed (see .gitignore). +## Copy it to `local.properties` and adjust the paths/ids. +sdk.dir=/path/to/Android/Sdk + +## AdMob ---------------------------------------------------------------- +## Create the Android app in AdMob and a banner ad unit, then paste the ids. +## Leave these out to use Google's public test ids (safe, no revenue). +# admob.appId=ca-app-pub-XXXXXXXXXXXXXXXX~YYYYYYYYYY +# admob.bannerUnitId=ca-app-pub-XXXXXXXXXXXXXXXX/NNNNNNNNNN + +## Legacy paid customers ------------------------------------------------- +## Epoch milliseconds of the first freemium release. Installs older than this +## are treated as paid-app installs and keep Pro. Leave unset (0) to disable +## grandfathering. Example: 2026-11-01T00:00:00Z = 1793491200000 +# legacyPro.cutoffEpochMs=1793491200000