Compare commits

..

10 Commits

Author SHA1 Message Date
SoftwareApp 9c17d65088 docs: add first-release notes for the freemium listing 2026-10-20 09:36:06 +02:00
SoftwareApp 22091dd808 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 <queries>
- 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
2026-10-20 09:28:29 +02:00
SoftwareApp 3afa7d777d fix: cut 1.0.2 with versionCode 3, because Play has already used 2
Play Console rejected the 1.0.1 bundle with "Version code 2 has already been used. Try another
version code." - the upload consumed code 2, so re-uploading that artifact can never succeed. The
next release therefore takes versionCode 3 and versionName 1.0.2, which also gives the pending
edge-to-edge fix a version of its own instead of leaving it unreleased.

Rebuilt both artefacts from the new configuration and checked them rather than assuming the bump
propagated: aapt2 dump badging on the release APK reports versionCode='3' versionName='1.0.2'
targetSdk=36, apksigner confirms the upload certificate (AA:8C:3D:6C:...:4C:7A), and the permission
set is unchanged - still no INTERNET. The AAB is 2,940,935 bytes (sha256 534e5ae9...), and the
unit suite is green: 80 tests, 0 failures, 0 errors.

The documents that carried versionCode 2 as the next upload are corrected: the checklist's
versioning step now quotes the rejection, its artifact row carries the new size and hash, ROADMAP
points at versionCode 3, and the 1.0.1 figures stay as history rather than being overwritten.

The first-upload language around pricing is no longer true either, so it is rewritten: code 2 has
already been uploaded, which means the Console pricing state has to be checked before this rollout
instead of set from scratch. If Products > App pricing still offers "Make your app paid", it has to
be done before the app is offered for free, because that switch is one-way.

CHANGELOG records the new 1.0.2 section with both the versionCode explanation and the edge-to-edge
fix, and the checklist gains a ready-to-paste 1.0.2 "What's new" block.
2026-10-18 16:59:50 +02:00
SoftwareApp bb250d1675 fix: set up edge-to-edge without Android 15's deprecated window APIs
Play's release dashboard listed Window.setStatusBarColor, Window.setNavigationBarColor and
LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES under "deprecated APIs or parameters for
edge-to-edge", starting in vr.b, xr.b and zr.b. None of those are app code: the R8 mapping
resolves vr/xr/zr to androidx.activity's EdgeToEdgeApi26/29/35, and a dexdump of the release
DEX finds six calls to the two colour setters, all reached through
ComponentActivity.enableEdgeToEdge(). Its per-API implementations still paint the bar scrims
(API 21/26/29) and select SHORT_EDGES on API 28/29, which Android 15 deprecates for apps
targeting SDK 35+.

MainActivity now calls ui/theme/EdgeToEdge.applyEdgeToEdge() instead. It keeps the parts that
still matter - setDecorFitsSystemWindows(false), navigation-bar contrast off, cutout mode
"always" on API 30+, and light/dark bar icons read from the system night mode - and drops the
scrim writes. The transparent bars continue to come from the XML theme, which does not
compile into a DEX call, so pre-35 devices look unchanged; API 28/29 keep the platform
default cutout mode rather than the deprecated SHORT_EDGES. The insets handling in
ScannerScreen (TopAppBar and navigationBarsPadding) is untouched.

Verified on the connected Android 12 device in both light and dark mode: the window reports
layoutInDisplayCutoutMode=always and the expected LIGHT_STATUS_BAR/LIGHT_NAVIGATION_BAR
flags, and the screenshots show content behind both bars with readable icons. The rebuilt
release APK and AAB contain zero references to setStatusBarColor/setNavigationBarColor and
no androidx.activity.EdgeToEdge classes; testDebugUnitTest and lintDebug pass (only the
pre-existing OldTargetApi warning). CHANGELOG records the change.
2026-10-18 16:48:02 +02:00
SoftwareApp 7b92da4f8b feat: give Google Ads the App campaign layer, costed against what a sale pays
docs/AD_COPY.md is the new home for the ad copy: five headlines (30 characters) and five
descriptions (90 each), five spares of each for rotation, and the rule that decides the wording —
the app is paid, so "free" cannot appear, and the creatives therefore say "No ads. No uploads.
Fully offline." rather than "Ad-free". The doc checks itself: a python block reads its own tables
and asserts each count and cap, verified against a deliberately over-length row (31 characters with
a stale count) before it was trusted.

It also records the arithmetic the campaign has to clear, because the Console hides it: the price
entered there is *net* and the buyer is charged VAT on top. The live listing reads EUR 3.59 with the
sale at EUR 1.79 — 2.99 x 1.20 and 1.49 x 1.20, the 20% column — where the documents had predicted
only the German 19% figures of 3.56 and 1.77. STORE_LISTING now separates the two numbers, says
which one the strikethrough shows (the gross one, not the EUR 2.99 typed in), and quantifies making
EUR 2.99 the sticker: the tax comes out of the developer's share, so EUR 2.54 a sale becomes
EUR 2.14. PLAY_RELEASE_CHECKLIST carries the correction at the step that enters the price.

For a paid app the install *is* the purchase, so the ceiling is the net per sale — EUR 2.54 at base,
EUR 1.27 during the launch sale — and a target of EUR 0.16 is not a target but a delivery stop: it
implies a 16x return on ad spend that no auction clears. The doc recommends Maximise conversions
first, a EUR 5/day budget sized by what a wrong answer costs, an in-market or custom-segment
audience only if one is wanted at all, and stop/scale rules for the week after. HTML5 last, text,
images and video first — Google's own guidance, quoted.

tools/make-store-assets.sh now renders that image set — 1200x628, 1200x1200, 320x480 — from three
new SVG sources that reuse the icon motif and gradient of icon.svg and feature-graphic.svg verbatim
and embed the committed 03-results screenshot. Two of its checks exist because the first versions
were wrong: comparing the finished PNG with the requested size can never fail, since
--export-width forces it, so the check moved to the *declared* canvas (a sandbox edit to 1200x600
now fails loudly), and --export-area-page is pinned because the cards bleed — the drawing bbox is
1200x710, which an older Inkscape would have squashed into the page. -strip drops the tIME Inkscape
stamps on every render, so two consecutive runs are byte-identical and a rebuild leaves no fake diff
(measured: 0 differing pixels with and without it).

The SVGs are sources, not uploads — Google Ads rejects SVG — so each says so in its header and the
script prints which PNGs to upload. store-assets/app-campaign/ holds those: 8-bit RGB, no alpha.

README points at both the new doc and the new output. No CHANGELOG entry: none of this is an app
change.
2026-10-15 18:02:44 +02:00
SoftwareApp 64431d5757 docs: answer the Advertising ID declaration from the dependency graph, not from the source
Play asks whether the app uses advertising ID "including any SDKs that your app imports that use
advertising ID", and that clause is the whole difficulty: the ID comes from
play-services-ads-identifier, which merges AD_ID into the manifest by itself - so one unrelated
dependency could turn this answer into a false statement without a line of app code changing. The
answer is No, and the checklist now records how that was established on 2026-10-14 against the
artefacts rather than against intentions:

- the release runtime classpath contains no gms/firebase/ads/billing/play-services entry at all, so
  there is no direct *or transitive* SDK that would ask for the ID
- aapt2 dump badging on the release APK lists the seven permissions the audit table already
  documents plus the framework's DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION - no AD_ID, and no
  Privacy Sandbox permission either
- the same check on base/manifest/AndroidManifest.xml inside the .aab finds nothing, which matters
  because the bundle is the artefact Play's own scanner reads
- the shipped classes.dex contains no com.google.android.gms classes, and the app has no INTERNET
  permission, so an ID could not be transmitted even if one were read

The last two rows are the ones to re-run after any dependency change: they are cheap, and this is
the declaration a stray library answers wrongly on the app's behalf. The same reasoning answers Data
safety's device-identifiers question, which the item now says out loud.

ROADMAP: the remaining-paperwork row names the advertising ID question rather than leaving it
implied by "ads".
2026-10-14 13:48:04 +02:00
SoftwareApp 6315af1f92 docs: cut the Photo and video permissions answer to the Console's 250-character box
The field takes 250 characters, not the 1 689 the draft assumed, so the answer is now 243
characters - measured, not estimated, and deliberately pure ASCII, because one curly quote or dash
pasted from a doc would silently shift the count:

  The app needs READ_MEDIA_IMAGES to read every photo, because duplicate detection compares each
  photo with every other. A picker exposes only selected files, and a photo's duplicates are
  exactly the files it withholds. All hashing is on-device.

What survived the cut is the sentence that carries the argument: the reason the permission is
needed is the same reason the picker cannot work - duplicates are, by definition, the files nobody
selected. What went is the statistical-fit paragraph and the delete path, neither of which a
reviewer needs in order to judge *this* question, and both of which are still in the longer drafts.

Also here: a 228-character alternate that opens with the comparison rather than the permission, and
the two long versions re-labelled as fallbacks for anywhere not capped at 250 (Play sometimes
follows up by email). The evidence table stays unchanged - it is the defence if the answer is
questioned, not part of what gets pasted.
2026-10-14 13:43:13 +02:00
SoftwareApp fe28373433 docs: correct the Balanced/Aggressive pHash ceilings in the README table
The table said 12 and 18 bits; DuplicatePolicy says 15 and 22, and the device agrees: with a
22-photo library the fit has too little data and falls back to the ceiling, and the results screen
prints "similarity cut: pHash <= 15 bits (default)" - 15, not 12.

The RGB column of the same table already matched the enum (60 and 84), which is what a pHash-only
edit looks like: the ceilings were evidently retuned and this one column was not carried along.

The old 18 was not invented - it is the measured F1 optimum that AGGRESSIVE's doc comment calls out
("set above the measured F1 optimum (~18 on real photographs)"), i.e. the value the ceiling is
deliberately placed above rather than the ceiling itself. Saying so here keeps the corrected row
from reading as though a measured optimum had been changed.
2026-10-14 13:38:33 +02:00
SoftwareApp 23bbc4104b docs: draft the Photo and video permissions declaration answer
The Console flags READ_MEDIA_IMAGES as undeclared and asks a specific question per permission - why
the Android photo picker does not fully support the app, and why the permission is needed. The old
draft here answered only the second half, in general terms, so it is replaced with an answer in the
order the form asks, at two lengths (1 689 chars, and 682 for a small box).

The picker half is what a reviewer actually weighs, and the code makes it concrete instead of
rhetorical: a picker hands over the items the user selects, while the duplicates of a picked photo
are precisely the files it never hands over - and the app's similarity threshold is fitted per scan
from the library's own pairwise hash-distance histogram (AdaptiveThreshold will not fit at all below
200 pairs), which no hand-picked subset can supply. The selection is not a sample of the library,
it is the part the duplicates are not in.

Both claims sit in a table next to their source in the code, together with the other things the
answer asserts - no INTERNET, deletion only through createDeleteRequest/createTrashRequest, and
partial access implemented rather than merely declared - so the text can be defended if Play asks.

Also written down: the form asks about READ_MEDIA_IMAGES only, since
READ_MEDIA_VISUAL_USER_SELECTED is the narrow half of the pair and needs no justification; if a
video is asked for as well, the foreground-service demo is a fallback but was filmed for a different
question; and a refusal would not require code changes, because the partial mode already runs - what
would be lost is the promise.
2026-10-14 13:38:33 +02:00
SoftwareApp 68dcbc5db6 docs: the video's link is its Gitea page, not the raw URL, which its own CSP blocks
Checked the way a browser does it rather than the way curl does, and curl had given a false green:
Gitea sends `Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; sandbox` with
every /raw/ response. That is deliberate - it is what makes serving raw HTML and SVG safe - but it
also blocks the media load when a browser navigates straight to a video, so the tab stays blank with
no error. The same URL plays fine as a subresource, which is exactly why the file's page in Gitea
shows a player: that page embeds <video controls src=".../raw/branch/main/...mp4">.

So the declaration's link is the /src/ page URL, and /raw/ is documented as the curl-and-download
URL instead. Everything verified about both URLs is written down in step 5 - including the two ways
to get a player with no Gitea chrome around it, if that is ever wanted: an unlisted YouTube upload,
or dropping the header for this one path on the Gitea host's Caddy proxy, which must stay scoped to
store-assets/ precisely because that header is what protects raw HTML and SVG.

The file itself was never the problem: 200, video/mp4, Content-Disposition: inline, bytes
sha256-identical to the recording, and Range: bytes=0-99 -> 206 with the matching Content-Range.
2026-10-14 13:28:49 +02:00
44 changed files with 4095 additions and 280 deletions
+357
View File
@@ -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 `<queries>`) 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 `<plurals>`.
- 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 `<plurals>`.
- [ ] 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.
+70
View File
@@ -10,6 +10,76 @@ 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
- **`versionCode` 3 instead of 2.** Play already holds a bundle with `versionCode` 2 and rejects
re-uploading it (*"Version code 2 has already been used"*), so this patch takes the next code.
`versionName` moves to 1.0.2 with it.
### Fixed
- **Play Console no longer reports deprecated edge-to-edge APIs.** The release build contained
`Window.setStatusBarColor`, `Window.setNavigationBarColor` and
`LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES`, all of which Android 15 deprecates for apps
targeting SDK 35+. They came from `ComponentActivity.enableEdgeToEdge()` (androidx.activity
1.13.0), whose per-API-level implementations still set the status/navigation bar scrims and use
the deprecated cutout mode on API 28/29. `ui/theme/EdgeToEdge` now performs the same setup with
current APIs only: `WindowCompat.setDecorFitsSystemWindows`, navigation-bar contrast off, cutout
mode `always` on API 30+, and light/dark bar icons following the system night mode. `MainActivity`
calls it instead of `enableEdgeToEdge()`; the theme still supplies the transparent bars below
API 35, and the existing inset handling in `ScannerScreen` is unchanged.
## [1.0.1] — 2026-10-13 · versionCode 2
### Fixed
+91 -22
View File
@@ -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: <https://policies.google.com/privacy>.
## 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
+124 -30
View File
@@ -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
@@ -52,18 +63,25 @@ 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!)
│ ├── 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
├── 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
@@ -121,8 +157,8 @@ Sensitivity presets (both values are ceilings; the pHash one is adapted per scan
| Policy | pHash ceiling | RGB ceiling | Notes |
|---|---|---|---|
| Exact copies only | – | – | byte-identical files, no decoding at all |
| Balanced (default) | 12 bits | 60 / 192 | the recommended setting |
| Aggressive | 18 bits | 84 / 192 | catches heavier re-edits |
| Balanced (default) | 15 bits | 60 / 192 | the recommended setting |
| Aggressive | 22 bits | 84 / 192 | catches heavier re-edits |
Banding gives *exact* candidate recall for pHash distances up to 7 (see the comment in
`DuplicateGrouper`).
@@ -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,20 +231,40 @@ 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) and
(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), [`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` and `tools/make-store-screenshots.sh` regenerate them from the
app's own icon vectors and from `adb` captures — always inside the repo, never in `$HOME`.
`tools/make-store-assets.sh` regenerates the Play icon and feature graphic *and* the Google Ads
App-campaign image set ([`store-assets/app-campaign/`](store-assets/app-campaign/), one composed
file per orientation — see [docs/AD_COPY.md](docs/AD_COPY.md)), and
`tools/make-store-screenshots.sh` turns `adb` captures into Play screenshots — always inside the
repo, never in `$HOME`.
Screenshots are kept per form factor (`store-assets/{raw-,}screenshots/{phone,tablet-7in,tablet-10in}/`)
because Play gives phones and each tablet size a slot of their own: `FORM_FACTOR=tablet-7in`
selects the 7-inch pipeline, and the tablet runs deliberately crop no system chrome because a
@@ -192,8 +273,10 @@ device, the tablet sets on AOSP AVDs; see [docs/STORE_LISTING.md](docs/STORE_LIS
`python3 tools/make-demo-photos.py` draws the synthetic photo library the results screenshot is
captured over, so the listing never shows a real one. The finished assets are **committed** —
including the foreground-service demonstration video that [the declaration](docs/PLAY_RELEASE_CHECKLIST.md)
links to — and Gitea serves them without a login (`…/raw/branch/main/store-assets/…`), so pushing
is the deployment step and that URL is the link itself.
links to — and Gitea serves them without a login, so pushing is the deployment step:
`…/src/branch/main/store-assets/…` is the page a browser opens (and the shape Play's video link
takes, because a `/raw/` URL carries a `default-src 'none'` CSP that stops a video playing inline),
`…/raw/branch/main/…` is the bytes.
User-visible changes are tracked in [CHANGELOG.md](CHANGELOG.md); the Play "What's new"
text you type per release is separate and lives only in the Play Console.
@@ -224,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
+64 -3
View File
@@ -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 = 2
versionName = "1.0.1"
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)
+6 -2
View File
@@ -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" />
<receiver
android:name=".debug.DebugProToggle"
android:exported="true"
tools:ignore="ExportedReceiver" />
</application>
</manifest>
@@ -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"
}
}
+35
View File
@@ -31,6 +31,26 @@
<!-- Android 13+: shows the scan progress notification (optional, never required). -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<!--
Free-tier ads and the optional Pro purchase are the only network users. Photo
processing never leaves the device. The Google Mobile Ads SDK also merges
AD_ID, WAKE_LOCK and the ACCESS_ADSERVICES_* Privacy Sandbox permissions into
the merged manifest; billing-ktx merges com.android.vending.BILLING. The release
checklist audits the MERGED manifest, not this source file.
-->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--
The freemium build has the applicationId `…finder.free`, while the old paid app
is `…finder`. If the paid app is still installed, LegacyPro reads its
firstInstallTime to grandfather the purchase. This package-visibility query is
the only cross-package signal available without a backend.
-->
<queries>
<package android:name="de.softwareapp_hb.fotodup.finder" />
</queries>
<application
android:name=".FotoDupApplication"
android:allowBackup="true"
@@ -44,6 +64,21 @@
android:theme="@style/Theme.FotoDupFinder"
tools:targetApi="33">
<!--
Required by the Google Mobile Ads SDK. The value comes from
`admob.appId` in local.properties (or -Padmob.appId=...); the default is
Google's public test app id, which is safe for debug builds.
-->
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="${admobAppId}" />
<meta-data
android:name="com.google.android.gms.ads.flag.OPTIMIZE_INITIALIZATION"
android:value="true" />
<meta-data
android:name="com.google.android.gms.ads.flag.OPTIMIZE_AD_LOADING"
android:value="true" />
<activity
android:name=".MainActivity"
android:exported="true"
@@ -2,14 +2,21 @@ package de.softwareapp_hb.fotodup.finder
import android.app.Application
import de.softwareapp_hb.fotodup.finder.domain.ScanController
import de.softwareapp_hb.fotodup.finder.monetization.AdsController
import de.softwareapp_hb.fotodup.finder.monetization.ProStore
/**
* Application entry point.
*
* Deliberately lightweight: the app has no background singletons, no dependency
* injection graph and no network access. Image loading uses Coil's default loader,
* and the duplicate index lives in a small SQLite database opened lazily by the
* data layer.
* Deliberately lightweight: the app has no dependency-injection graph. Three
* process-scoped objects are created here so they outlive any activity:
*
* - [ScanController] owns the running scan (kept alive by `ScanService`);
* - [ProStore] owns the Play Billing entitlement and its local cache;
* - [AdsController] owns UMP consent and Mobile Ads initialisation.
*
* Photo data never leaves the device. The only network users are the ad SDK and
* Play Billing.
*/
class FotoDupApplication : Application() {
@@ -21,8 +28,18 @@ class FotoDupApplication : Application() {
lateinit var scanController: ScanController
private set
/** Play Billing entitlement plus the free-tier ad gate. */
lateinit var proStore: ProStore
private set
/** UMP consent + Google Mobile Ads initialisation. */
lateinit var adsController: AdsController
private set
override fun onCreate() {
super.onCreate()
scanController = ScanController(this)
proStore = ProStore(this)
adsController = AdsController(this)
}
}
@@ -3,18 +3,32 @@ package de.softwareapp_hb.fotodup.finder
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import de.softwareapp_hb.fotodup.finder.ui.scanner.ScannerScreen
import de.softwareapp_hb.fotodup.finder.ui.theme.FotoDupTheme
import de.softwareapp_hb.fotodup.finder.ui.theme.applyEdgeToEdge
class MainActivity : ComponentActivity() {
private val app: FotoDupApplication
get() = application as FotoDupApplication
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
// AndroidX's enableEdgeToEdge() would do this too, but it still uses APIs that are
// deprecated on Android 15; see applyEdgeToEdge() for the details.
applyEdgeToEdge()
// Consent must be resolved before the ad SDK is initialised. A Pro user never
// reaches the ad SDK at all, which also keeps the privacy options form out of
// their way.
if (!app.proStore.state.value.isPro) {
app.adsController.ensureInitialized(this)
}
setContent {
FotoDupTheme {
Surface(
@@ -26,4 +40,11 @@ class MainActivity : ComponentActivity() {
}
}
}
override fun onResume() {
super.onResume()
// Picks up purchases completed while the app was backgrounded (including a
// pending purchase that Play has now charged). Throttled inside ProStore.
app.proStore.refreshPurchases()
}
}
@@ -0,0 +1,16 @@
package de.softwareapp_hb.fotodup.finder.monetization
/**
* The single rule that decides whether the free tier's banner may be requested.
*
* Deliberately pure so it can be unit-tested without Android, Play services or an
* AdMob account. A Pro user never reaches the ad gate, and consent must be in place
* before the SDK may be initialised.
*/
object AdPolicy {
fun shouldShowBanner(
isPro: Boolean,
canRequestAds: Boolean,
initialized: Boolean,
): Boolean = !isPro && canRequestAds && initialized
}
@@ -0,0 +1,124 @@
package de.softwareapp_hb.fotodup.finder.monetization
import android.app.Activity
import android.content.Context
import android.util.Log
import com.google.android.gms.ads.MobileAds
import com.google.android.ump.ConsentInformation
import com.google.android.ump.ConsentRequestParameters
import com.google.android.ump.UserMessagingPlatform
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
/**
* Owns the Google User Messaging Platform (UMP) consent flow and initialises the
* Mobile Ads SDK once consent has been resolved.
*
* The banner is only allowed to request an ad when [AdsState.canRequestAds] and
* [AdsState.initialized] are both true. That makes a missing network, a missing Play
* services install or a consent refusal a quiet "no ad" rather than a crash.
*/
class AdsController(context: Context) {
private val appContext = context.applicationContext
private val consentInformation: ConsentInformation =
UserMessagingPlatform.getConsentInformation(appContext)
private val _state = MutableStateFlow(AdsState())
val state: StateFlow<AdsState> = _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"
}
}
@@ -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,
)
@@ -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 `<queries>` 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
}
@@ -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"
}
@@ -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,
)
@@ -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<ProState> = _state.asStateFlow()
private var billingClient: BillingClient? = null
private var productDetails: ProductDetails? = null
private var connecting = false
private var lastQueryAtMs = 0L
private var pendingPurchaseActivity: WeakReference<Activity>? = 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<Purchase>?) {
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
}
}
@@ -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())
}
}
@@ -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
}
@@ -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)
}
}
@@ -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) {
@@ -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,
@@ -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
@@ -0,0 +1,55 @@
package de.softwareapp_hb.fotodup.finder.ui.theme
import android.app.Activity
import android.content.res.Configuration
import android.os.Build
import android.view.WindowManager
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsControllerCompat
/**
* Draws the activity edge-to-edge using only window APIs that are still current on Android 15.
*
* `ComponentActivity.enableEdgeToEdge()` (androidx.activity 1.13.0) still calls
* `Window.setStatusBarColor()` and `Window.setNavigationBarColor()` in its API 21/26/29
* implementations, and it sets `LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES` on API 28/29. All
* three are deprecated for apps targeting SDK 35 and therefore appear in Play Console as
* "Your app uses deprecated APIs or parameters for edge-to-edge".
*
* The window itself is already transparent because of the theme, so the colour-scrim half of
* `enableEdgeToEdge()` is unnecessary. What remains is letting the window lay out behind the
* system bars, keeping the navigation-bar scrim off, and choosing light or dark bar icons for
* the current theme.
*
* Call this from `Activity.onCreate()`, after `super.onCreate()` and before setting content.
*/
fun Activity.applyEdgeToEdge() {
// Lay out behind the status and navigation bars instead of letting the decor view inset
// them. On API 35+ this is a no-op: the platform already enforces edge-to-edge there.
WindowCompat.setDecorFitsSystemWindows(window, false)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// The navigation bar is transparent (see the theme), and without this Android 10+ draws
// its own translucent contrast scrim over the gesture/button area.
window.isNavigationBarContrastEnforced = false
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// Allow the app to draw into the display cutout on every edge. API 28/29 would need the
// now-deprecated SHORT_EDGES mode for that, so those versions keep the platform default
// instead; Android 15 ignores the mode because edge-to-edge is mandatory there.
window.attributes = window.attributes.apply {
layoutInDisplayCutoutMode =
WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
}
}
val darkTheme = (resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) ==
Configuration.UI_MODE_NIGHT_YES
WindowInsetsControllerCompat(window, window.decorView).apply {
// Dark icons on a light background and light icons on a dark one — the same system
// night-mode flag that drives FotoDupTheme.
isAppearanceLightStatusBars = !darkTheme
isAppearanceLightNavigationBars = !darkTheme
}
}
+32 -2
View File
@@ -29,13 +29,13 @@
<!-- Photo access banner -->
<string name="access_needed_title">Photo access needed</string>
<string name="access_needed_body">The app needs permission to read your photos so it can find duplicates. Nothing ever leaves your device.</string>
<string name="access_needed_body">The app needs permission to read your photos so it can find duplicates. Your photos never leave your device.</string>
<string name="access_limited_title">Limited photo access</string>
<string name="access_limited_body">You granted access to selected photos only. Grant full access to scan your whole library.</string>
<!-- Intro / empty state -->
<string name="intro_title">Find and remove duplicate photos</string>
<string name="intro_body">Fast, ad-free and completely offline. Your photos are never uploaded.</string>
<string name="intro_body">Fast, private and completely on-device. Your photos are never uploaded. The free version is supported by ads; Pro removes them.</string>
<!-- Scan phases (also used by the progress notification) -->
<string name="phase_loading">Reading your photo library…</string>
@@ -116,6 +116,36 @@
<string name="message_nothing_deleted">Nothing was deleted</string>
<string name="message_not_confirmed">Deletion was not confirmed</string>
<!-- Monetisation: free tier with one banner, Pro removes it -->
<string name="menu_remove_ads">Remove ads</string>
<string name="menu_pro_active">Pro — ads removed</string>
<string name="menu_privacy_options">Privacy options</string>
<string name="pro_title">Remove ads with Pro</string>
<string name="pro_subtitle">One-time purchase. No subscription, no account.</string>
<string name="pro_benefit_ads">No banner ads</string>
<string name="pro_benefit_all_features">Every duplicate-finding feature stays free</string>
<string name="pro_benefit_support">Supports the app\'s development</string>
<string name="pro_price">One-time purchase · %1$s</string>
<string name="pro_price_unknown">One-time purchase</string>
<string name="pro_buy">Buy Pro</string>
<string name="pro_buy_price">Buy for %1$s</string>
<string name="pro_purchasing">Opening Google Play…</string>
<string name="pro_restore">Restore purchase</string>
<string name="pro_not_now">Not now</string>
<string name="pro_close">Close</string>
<string name="pro_active">Pro is active. Ads are removed.</string>
<string name="pro_unavailable">Purchases are unavailable right now. Check Google Play and your connection, then try again.</string>
<string name="message_purchase_pending">Your purchase is pending. Pro activates once Google Play confirms the payment.</string>
<string name="message_purchase_failed">The purchase could not be completed. Please try again.</string>
<string name="message_purchase_unavailable">Purchases are unavailable right now. Check Google Play and your connection.</string>
<string name="message_purchase_not_found">No purchase was found for this Google account.</string>
<string name="message_purchase_restored">Purchase restored. Ads are removed.</string>
<string name="message_pro_already">Pro is already active on this Google account.</string>
<string name="message_ads_removed">Ads removed. Thank you for supporting the app!</string>
<string name="message_privacy_unavailable">Privacy options are unavailable right now. Please try again later.</string>
<!-- Progress notification -->
<string name="notification_channel_name">Scan progress</string>
<string name="notification_channel_description">Shows progress while duplicate photos are being searched for</string>
@@ -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))
}
}
@@ -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))
}
}
+321
View File
@@ -0,0 +1,321 @@
# Google Ads copy (App campaign)
Ready-to-paste ad copy for a Google Ads **App campaign**, the advertising counterpart of the Play
Store listing in [STORE_LISTING](STORE_LISTING.md). Same voice, same claims, same honesty rules —
only the format is different: an App campaign asset group takes **5 headlines of at most 30
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.
## Headlines (max 30 characters)
| # | Headline | Chars |
|---|---|---|
| 1 | Find Duplicate Photos | 21 |
| 2 | Delete Duplicate Photos | 23 |
| 3 | Duplicate Photo Cleaner | 23 |
| 4 | Reclaim Storage Fast | 20 |
| 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 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 | 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 | 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), 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
Rotate these in one at a time and let the campaign decide; they are all in-spec.
| Headline | Chars | Angle |
|---|---|---|
| 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 |
| Description | Chars | Angle |
|---|---|---|
| Choose Exact, Balanced or Aggressive. Move to trash or delete permanently — your call. | 86 | The control the app actually exposes |
| 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 account, no uploads. Free with one banner; a one-time Pro purchase removes it. | 81 | Privacy plus the honest model |
## Rules this copy follows
- **“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.
- **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)
An App campaign ad group accepts five asset types, and the Console shows a ceiling for each. **Only
the first is writing work** — the other four are creative, and three of them are optional:
| Asset | Console ceiling | Verdict |
|---|---|---|
| Headlines + descriptions | 5 + 5 | **Done** — the copy above. The only asset you must write. |
| Images | 20 | **Three shipped** (below) — one per orientation, which is what the slots need. |
| Videos | 20 | **Yes, 1–2 real ones** — the highest-value non-text asset, and must be on YouTube. |
| HTML5 / playable | 20 | **Skip.** Google's own guidance, verbatim: *"HTML5 assets can be more difficult and expensive to create than the previous asset types. We strongly recommend uploading the maximum number of text, image, and video assets before building for HTML5."* |
Text-only is a valid starting point: Google generates what is missing — from the Play listing (icon,
screenshots, description) and from the assets you do supply, which is why the App campaigns help ships
an article called *About auto-generated video ads*. What it cannot generate is a **good** creative, so
the question is not "is this overkill" but "what does the next €1 of work buy".
### Images: three orientations, not twenty files
App campaigns serve landscape, square and portrait placements, and an asset is matched to a
placement's orientation — so twenty landscape images still leave the portrait and square slots empty.
Three are committed, one per orientation, and each is composed rather than resized:
| Orientation | Size the Console asks for | File |
|---|---|---|
| Landscape (1.91:1) | 1200 × 628 | `store-assets/app-campaign/landscape-1200x628.png` |
| Square (1:1) | 1200 × 1200 | `store-assets/app-campaign/square-1200x1200.png` |
| Portrait (2:3) | 320 × 480 | `store-assets/app-campaign/portrait-320x480.png` |
**Upload the PNG, not the SVG.** Google Ads takes raster image assets — PNG or JPG — and an `.svg`
is a vector source it rejects. The three `.svg` files are sources in exactly the way
`tools/store-assets/icon.svg` is the source of `store-assets/icon-512.png`; the `.png` files in the
table above are what goes into the Console. They are 8-bit truecolour RGB with **no alpha channel**
(checked in the PNG header, colour type 2) and 424 KB / 845 KB / 89 KB, so there is nothing about
them an uploader can object to.
`./tools/make-store-assets.sh` builds all three from `tools/store-assets/app-campaign-*.svg`, which
are the editable sources. They reuse the icon motif and the green gradient of `icon.svg` /
`feature-graphic.svg` verbatim, so the ad, the store listing and the launcher icon cannot drift apart,
and they embed the committed results screenshot — `screenshots/phone/03-results.png`, 83.5 MB
reclaimable with the `BEST` badge, the whole pitch in one frame — rather than a real library.
Three properties are worth keeping if they are ever edited:
- **A rebuild is byte-identical.** Inkscape stamps `tIME` on every render, so the script strips the
ancillary chunks: two consecutive runs produce identical files, and regenerating them never leaves
a fake "modified" entry in git.
- **The layout is measurable, not eyeballed.** Every text and image element carries an id, so
`inkscape --query-all tools/store-assets/app-campaign-landscape.svg` prints the real bounding box
of the name, both taglines and the screenshot card — the taglines end at x=608 while the card
starts at x=760, and the square's text ends 70 px above its card.
- **The bleed is deliberate.** Each card runs off the canvas edge, which is what makes the crop look
intentional instead of a stuck-on rectangle — and the reason the script pins Inkscape's export
area to the page (the drawing bbox is 1200 × 710 for the landscape file; exporting *that* would
squash the composition into 1200 × 628).
The script asserts each file's exact pixel size, flattens it to 8-bit RGB (an ad is shown on the
placement's own background, so alpha is a liability) and flags anything over 5 MB, the size the
Google Ads image uploader accepts. Current sizes: 424 KB, 845 KB, 89 KB.
### Videos: re-use the recording that already exists
Every video asset is served from YouTube — *"Since all video assets are served from YouTube, you must
upload directly to this platform to be eligible for selection."* So the cheapest honest start is the
committed screen recording the foreground-service declaration already links to
(`store-assets/fgs-demo/foreground-service-demo.mp4`, ~20 s on the real device: scan → notification →
results), uploaded to YouTube as **unlisted** and pasted in as a video asset. It is a demonstration,
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.
### 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
pays. So before commissioning images or shooting video, run the text-only version and read **cost per
purchase**, not cost per click: while it is above €2.54 the campaign loses money no matter how good
the creatives are, and no asset pack fixes that. Creative work is justified by a working funnel, not
the other way round.
#### What to set as the target cost per install
For this app **cost per install and cost per purchase are the same number**: there is no free download
to count, so the only install event that exists is one the buyer paid for. The break-even threshold is
therefore this app's net per sale, not the CPI of some free app in the same category:
| Your price | Net per sale (≈) | Break-even cost per install | Target that leaves margin |
|---|---|---|---|
| €2.99, base | €2.54 | €2.54 | ≤ €1.27 (50% of net) |
| €1.49, launch sale | €1.27 | €1.27 | ≤ €0.63 (50% of net) |
A target of **€0.16 is not a target, it is a wish**: 6% of the base net (12% during the sale), an
implied return on ad spend of ~16×. No auction sells a paid-app purchase that cheaply, and Smart
Bidding does not chase a target below the clearing price — it simply stops delivering, so the symptom
is not expensive installs but *no* installs, and the campaign reads as "limited by bid" rather than
"too expensive".
Set it in this order instead:
1. **Maximise conversions, no target**, on a small daily budget for two to three weeks. The point is
not profit yet, it is to *measure* the cost per purchase this app actually clears at.
2. Then set the target **25–40% below** that measured figure — and never above break-even. If the
measurement lands above €2.54, the finding is that this app cannot profitably buy installs at
€2.99, which is a result and not a failure: the whole point of a small test is to learn that for
the price of three weeks' budget instead of a year's.
3. During the 14-day launch sale the bar drops to €1.27, so a campaign that breaks even at base price
loses money while the sale runs. Either pause the ads for that window or write it off as launch
spend.
Rule of thumb for the volume Smart Bidding needs to learn a target: on the order of 15–30 conversions
a month. At €1–2 a purchase that is only €15–60 of budget, so budget is rarely the binding constraint
here — delivery is, and the target is what caps it.
#### The settings to actually type in
| Field | Value | Why |
|---|---|---|
| Campaign goal | **App installs** (the only conversion this app has) | A paid app's install *is* the purchase |
| Bidding, first 2–3 weeks | **Maximise conversions, no target** | Any number before a measurement is a guess |
| Bidding, after that | Target cost per install **€1.25** at base price, **€0.60** while the sale runs | 50% of net: the most you can pay and keep half the revenue |
| Daily budget | **€5/day** | Monthly cap €152; Google may spend up to 2× the daily budget on one day but never more than 30.4× in a month |
| 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 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
An App campaign gives you almost no manual targeting: no keywords at all, and at campaign level only
location and language. The one lever the ad group offers is **audience segments** — and adding one
*narrows* delivery rather than merely observing it, unlike the observation-only audiences a Search
campaign uses. Two consequences for a €5/day test:
- **Delivery is the binding constraint already.** A €1.25 target on a conversion as scarce as a paid
install leaves Google very little room, and a narrow audience leaves less. Leave the field **empty**
for the first run; the copy and the creatives do the qualifying.
- **A segment cannot fix the arithmetic.** It changes who sees the ad, not what a purchase pays you. If
cost per purchase is €5 without a segment, no audience choice turns that into €1.25.
If a segment is wanted anyway, take **exactly one** — at this budget two ad groups could never both
gather enough conversions to be compared:
- **In-market: photo/video software.** People actively shopping in the category, which is as close as a
pre-built audience gets to this app's buyer.
- **A custom segment built from intent terms** — the only keyword-like lever an App campaign has:
"duplicate photos", "delete duplicate photos", "free up phone storage", "photo cleaner", in the
campaign's own language.
Deliberately *not* the affinity audience *photography enthusiasts*: those are people who like taking and
keeping photos, and this app's buyer wants them gone. Same reasoning that keeps the *Photo editor* tag
off the listing ([STORE_LISTING › Category and tags](STORE_LISTING.md#category-and-tags)).
One audience type is unavailable by design: **your own data / remarketing**. No SDK, no analytics, no
account — so there is no list to build one from, and adding an SDK to obtain one would falsify the
listing's central claim ([PRIVACY.md](../PRIVACY.md)). Google's pre-built audiences and custom segments
are all this app can use.
If the ad group offers audience expansion or optimised targeting, leave it **on**: with no segments set it
changes nothing, and with one set it lets Google reach beyond it, which is what a small budget wants.
#### Why €5/day rather than the arithmetic's €1/day
Learning a target wants ~15–30 conversions a month, which at €1.25 a purchase is only €19–38 — so that
formula would say €1/day, below what an App campaign reliably serves at and too slow to teach anything
in three weeks. The other way to size a budget is as money you are willing to spend to *learn the
number*, and that is capped by what a wrong answer costs:
| Spend over 3 weeks at €5/day | If cost per purchase lands at | Purchases | Net revenue | Outcome |
|---|---|---|---|---|
| €105 | €0.63 (the sale-price bar) | ~167 | €424 | +€319 |
| €105 | €1.25 (the target) | ~84 | €213 | +€108 |
| €105 | €2.54 (base break-even) | ~41 | €105 | ±€0 |
| €105 | €5.00 | ~21 | €53 | −€52 |
The worst case there is losing ~€52 while acquiring 21 paying customers, and the second worst is
breaking even — which is what a bounded experiment should look like. Review at ~€105 spent:
- **Cost per purchase ≤ €1.25** → it works. Raise the daily budget in 20–30% steps and let it re-learn.
- **€1.25–2.54** → profitable only at the base price, so never run it during a sale window.
- **> €2.54, or no purchase after ~€50 spent** → switch it off. The finding is that this app cannot
buy installs profitably at €2.99, and that is precisely what the test was for.
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: **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
Any edit has to be re-measured before it goes into the Console — the limits are hard.
```bash
python3 - <<'EOF'
import pathlib
CAPS = {'Headline': 30, 'Description': 90}
fence, header, checked = False, None, 0
for number, line in enumerate(pathlib.Path('docs/AD_COPY.md').read_text(encoding='utf-8').splitlines(), 1):
if line.strip().startswith('```'):
fence = not fence
continue
if fence or not line.startswith('|'):
header = None # a non-table line ends the table
continue
cells = [c.strip() for c in line.strip().strip('|').split('|')]
if all(set(c) <= set('-# ') for c in cells):
continue # separator row
if header is None:
header = cells
continue
label = [i for i, h in enumerate(header) if h in CAPS]
if not label:
continue # not an asset-copy table (e.g. the asset-type table)
copy, kind = cells[label[0]], header[label[0]]
declared = int(cells[header.index('Chars')])
assert len(copy) == declared, f'line {number}: counted {len(copy)}, listed {declared}: {copy!r}'
assert len(copy) <= CAPS[kind], f'line {number}: {len(copy)} > {CAPS[kind]}: {copy!r}'
checked += 1
print(f'{checked} assets in spec')
EOF
```
It reads the document itself, so a headline or description edited here but not re-measured fails the
run rather than shipping at 31 or 91 characters.
+5 -5
View File
@@ -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
```
+274
View File
@@ -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 `<queries>`
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.
+300 -120
View File
@@ -5,32 +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.1` in `app/build.gradle.kts`.
- [x] `versionCode` **[code]** — currently **2**. It is the counter Play orders uploads by, so the
first upload will be 2 and every later upload must be higher.
- [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
@@ -39,12 +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-13: `bundleRelease` and `assembleRelease` both succeed.
`app/build/outputs/bundle/release/app-release.aab` is 2,944,100 bytes
(`sha256 f8e6a29a0daf60d025409e19be878c3e8f1359a06b3f9fca300bb4aec9ebb726`) and is signed with
the upload key. The release APK reports `versionCode=2 versionName=1.0.1 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.
- [ ] **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/<abi>/libandroidx.graphics.path.so`, and reports *"This App Bundle contains native
@@ -75,38 +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]**.
- [ ] ⚠️ **App pricing — do this before the first upload; 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."* This release has not been
uploaded yet (`versionCode` 2 is the first), so a paid app is still possible; after the first
upload to any track it is not. 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, a German buyer pays €3.56.
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).
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.
@@ -170,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 |
|---|---|---|
@@ -196,33 +208,120 @@ 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 '<uses-permission' \
app/build/intermediates/merged_manifests/release/processReleaseManifest/AndroidManifest.xml \
| grep -oE 'android.permission.[A-Z_]+' | sort -u
| grep -oE '[A-Za-z0-9_.]*permission\.[A-Z_]+|com\.android\.vending\.BILLING' | sort -u
```
(Match `<uses-permission` only. A bare `android.permission.` grep also picks up
`android.permission.DUMP`, which AndroidX puts on its profile-installer *receiver* —
a component restriction, not a permission the app requests.)
- [ ] Answer the **Photo and video permissions** declaration in the Console. The app
requests `READ_MEDIA_IMAGES` (plus `READ_MEDIA_VISUAL_USER_SELECTED` for Android 14
partial access) and deletes only user-selected files through the system dialog.
Paste:
- [ ] Answer the **Photo and video permissions** declaration (App content › Photo and video
permissions). It lists `READ_MEDIA_IMAGES` as *undeclared* and asks one question per
permission — in a box with a hard **250-character** limit:
> **Read media images** — Describe why the Android photo picker or other system pickers do
> not fully support your app's core functionality, and why your app needs to use the
> `READ_MEDIA_IMAGES` permission.
Paste — **243** of the 250 characters, pure ASCII so the count cannot drift on paste:
> The app needs READ_MEDIA_IMAGES to read every photo, because duplicate detection compares
> each photo with every other. A picker exposes only selected files, and a photo's duplicates
> are exactly the files it withholds. All hashing is on-device.
One sentence carries the whole argument: the reason the permission is needed *is* the reason
the picker cannot work. A picker hands over the files the user selected, and duplicates are
by definition the files nobody selected — the copies of a picked photo live in the part of
the library the picker never exposes. The closing sentence is there because a permission
declaration is also a privacy statement, and 25 characters is a cheap way to say it. If you
would rather open with the comparison than with the permission, this fits too (**228**):
> Finding duplicates requires comparing every photo with every other, so the app must read
> the whole library via READ_MEDIA_IMAGES. A picker exposes only selected files, and a
> photo's duplicates are exactly the files it withholds.
The longer versions below are kept for anywhere that is *not* capped at 250 — Play sometimes
follows up by email, and both read well wherever more detail is wanted. **1 689 characters**:
> Foto Dup Finder's core functionality is finding duplicate and visually similar photos
> across the user's whole photo library, and letting the user delete the copies. Reading the
> photo library is that entire operation.
>
> The Android photo picker cannot support it. The picker only grants access to the items the
> user selects in that session, and the duplicates are by definition outside that selection:
> the copies of a picked photo are other files, in other folders, that the picker never hands
> over. Comparing only the picked items tells the user nothing they did not already know;
> finding the groups requires comparing every photo in the library with every other photo.
>
> The app also needs the whole library to calibrate itself. It estimates the distance
> distribution of unrelated photos from the library's own pairwise perceptual-hash distances
> and sets the widest similarity threshold whose expected number of accidental matches stays
> in budget. Below a few hundred pairs that fit is impossible and the app falls back to a
> 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: 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:
> Foto Dup Finder's only function is finding duplicate and similar photos across the user's
> whole photo library and letting them delete the copies: reading the library is the feature.
> The Android photo picker grants access only to the items a user selects, while the
> 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. 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:
| The answer claims … | … and this is where that is true |
|---|---|
| the app reads the whole library | `MediaStorePhotoSource.loadPhotos()` queries the image collection with a `null` selection — metadata only, pixels later and lazily |
| duplicate detection needs every pair | `DuplicateGrouper` clusters by exact SHA-256 *and* perceptual fingerprints, union-find over the whole scan |
| 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 |
| 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 |
Three notes for filling the form in. (1) The declaration asks about `READ_MEDIA_IMAGES` only:
`READ_MEDIA_VISUAL_USER_SELECTED` is the *narrow* half of the pair and needs no justification,
so do not volunteer it as though it were the broad one. (2) If that screen also asks for a
**video**, the recorded foreground-service demo does show a full 5,385-photo library scan and
the groups it found, which is the functionality this declaration is about — but it was filmed
to answer the foreground-service question, so it is a fallback rather than the intended
answer, and a take focused on this question (open → grant → scan → groups) may be asked for.
(3) If the declaration were refused, the app already runs in the partial mode it implements
(banner + subset scan), so nothing would need rewriting — what would be lost is the promise
("find the duplicates you forgot about"), which is why the answer above is the one to stand
behind.
> Foto Dup Finder is a photo-cleanup tool. Reading the photo library **is** its core
> functionality: it compares photos on the device to find exact and near duplicates
> and lets the user remove the copies they select. Nothing is uploaded — the app
> declares no network permission. Deletion always goes through the system consent
> dialog (`MediaStore.createDeleteRequest`); the app never requests
> `MANAGE_EXTERNAL_STORAGE`.
- [ ] Declare the **foreground service type**. This is the release-blocking item for the
Android 14+ review. **[code]** The manifest already matches what you will declare:
@@ -242,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:
@@ -283,23 +383,38 @@ action except the items marked **[code]**.
CANCEL"*, 13–18 s) while the scan kept running behind it, and the finished results
(*17 duplicate groups · 54 of 5,385 photos*) at the end.
**The link to paste** is the committed file's own URL — no login, no second host:
**The link to paste** is the file's page in Gitea — what the repository's own *view* of
the file opens, and what plays it:
```
https://gitea.softwareapp-hb.de/fishfacegit/foto-duplicate-finder/raw/branch/main/store-assets/fgs-demo/foreground-service-demo.mp4
https://gitea.softwareapp-hb.de/fishfacegit/foto-duplicate-finder/src/branch/main/store-assets/fgs-demo/foreground-service-demo.mp4
```
Checked from outside this network: **200**, `Content-Type: video/mp4`,
`Content-Length: 1847900` and `Content-Disposition: inline`, so a reviewer's browser plays
it in the tab rather than prompting a download, and the served bytes are identical to the
recording (sha256 match). A `Range: bytes=0-99` request answers **206** with exactly those
100 bytes even though `Accept-Ranges` is not advertised, so seeking works and a player can
start without fetching the whole file first — which matters here because `screenrecord`
writes the `moov` atom at the very end of the file. Two things to know before pasting: the
URL is pinned to `main`, so a re-shoot has to **overwrite the file in place** rather than
be added alongside it; and replacing the video at all means resubmitting the declaration.
(An unlisted YouTube upload of the same file works equally well if a link that survives
future commits is preferred — but then it is a second place to keep in step.)
⚠️ **Not the `/raw/` URL**, even though that is the file itself. Gitea answers raw
responses with `Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline';
sandbox` — a deliberate guard against raw HTML and SVG — and that blocks the media load of a
document that navigates straight to a video: the tab stays blank with no error, which is
exactly how this behaved in a browser. The same URL is fine as a *subresource*: the page
above embeds `<video controls src="…/raw/branch/main/…mp4">`, which is why previewing the
file plays it and opening `/raw/` does not. Use `/raw/` for `curl` and downloads, never as
the link in the form.
Verified about the **page** URL: **200** anonymously, containing that `<video controls>`
element. Verified about the **raw** URL, from outside this network and unauthenticated:
**200**, `Content-Type: video/mp4`, `Content-Length: 1847900`, `Content-Disposition:
inline`, bytes sha256-identical to the recording, and `Range: bytes=0-99` → **206** with
exactly those 100 bytes although `Accept-Ranges` is not advertised (which matters because
`screenrecord` writes the `moov` atom at the very end of the file). Two things to know
before pasting: the URL is pinned to `main`, so a re-shoot has to **overwrite the file in
place** rather than be added alongside it; and replacing the video at all means resubmitting
the declaration.
If a link with no Gitea chrome around the player is preferred later, there are two ways and
neither is needed for the declaration: an unlisted YouTube upload of the same file, or a
rule on the Gitea host's Caddy proxy dropping the header for this one path
(`@fgsdemo path …/store-assets/fgs-demo/*.mp4` plus `header_down @fgsdemo
-Content-Security-Policy`) — **scoped to `store-assets/` only**, since that header is what
makes raw HTML and SVG safe to serve. Neither was tried from here.
Both flags exist because this take found two traps worth knowing before a re-shoot:
@@ -345,8 +460,28 @@ 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).
- [ ] **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 | Expected |
|---|---|---|
| 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) 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,
government app, financial features, health, COVID-19 contact tracing.
@@ -370,13 +505,27 @@ 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 first:** `versionCode` is already **2** (`versionName` 1.0.1), because
1.0.1 was cut before anything reached Play — so the *first* upload is 1.0.1 and takes the
**initial release** block. The 1.0.1 block below applies only once 1.0.0 exists on a track.
⚠️ **Which block applies:** the freemium app is a **new `.free` listing**, so its first
release uses the “new freemium listing” block below. The 1.0.2 and initial-release
blocks are kept for the history of the old paid listing; the old initial block still
says “no ads”, which was true only of the paid build. The 1.1.0-update block has been
replaced because the plan is a new listing, not an in-place price change.
Release notes are **not stored in this repo** — they are typed into the Play Console
@@ -400,15 +549,34 @@ Rules (per Google's *Prepare and roll out a release* guide):
- For app updates list only user-visible changes; the full developer history belongs
in [CHANGELOG.md](../CHANGELOG.md).
Ready-to-paste block for the first release:
Ready-to-paste block for the **new freemium listing's first release** (313 chars):
<en-US>
Initial release.
• Finds exact and near-duplicate photos
• Suggests which copy to keep
• Moves photos to the trash or deletes them via the system dialog
• No ads, no account, works fully offline
• Find exact and near-duplicate photos
• Keep the best copy and remove the rest in one confirmed batch
• Move photos to the trash or delete them permanently
• Free with one small banner; a one-time Pro purchase removes it
• Photos are processed on your device and never uploaded
</en-US>
Optional German block for the same release (360 chars):
<de-DE>
Erste Veröffentlichung.
• Exakte und ähnliche doppelte Fotos finden
• Das beste Foto behalten und den Rest in einem bestätigten Schritt entfernen
• Fotos in den Papierkorb verschieben oder endgültig löschen
• Kostenlos mit einem kleinen Banner; ein einmaliger Pro-Kauf entfernt ihn
• Fotos werden auf dem Gerät verarbeitet und nie hochgeladen
</de-DE>
Ready-to-paste block for **1.0.2** (the `versionCode` 3 build, historical):
<en-US>
• Maintenance release with compatibility fixes
</en-US>
Ready-to-paste block for **1.0.1** (the scan-robustness patch):
@@ -430,27 +598,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 `<queries>` 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.
+17 -12
View File
@@ -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 `<plurals>`, 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)
@@ -29,10 +30,10 @@ 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: Gitea serves the raw file with `Content-Type: video/mp4` and `Content-Disposition: inline`, verified by hash from outside the network, so pasting that 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: the **first upload + Play App Signing enrolment**, 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 / 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 set before the first upload, because free → paid is not possible afterwards (M9). Keystore, `versionCode`, listing copy, graphics, permission audit and the signed `.aab` (`sha256 f8e6a29a…`) 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) |
| **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: 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,7 +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). 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
@@ -57,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 must happen
before the first upload, 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.
+146 -69
View File
@@ -5,7 +5,8 @@ graphics are generated from the app's own vectors, so they can be regenerated af
branding change instead of being edited by hand.
See [PLAY_RELEASE_CHECKLIST](PLAY_RELEASE_CHECKLIST.md) § 4 for where these fit in the
release.
release. Ad copy to drive traffic *to* this listing — a Google Ads **App campaign**'s five
headlines and five descriptions — lives in [AD_COPY](AD_COPY.md).
## Graphics
@@ -30,10 +31,11 @@ Screenshots live **one directory per form factor**, because Play gives phones, 7
```
store-assets/raw-screenshots/{phone,tablet-7in,tablet-10in}/ git-ignored `adb` captures
store-assets/screenshots/{phone,tablet-7in,tablet-10in}/ the files that get uploaded — committed
store-assets/app-campaign/ Google Ads image set, one per orientation — committed
```
```bash
./tools/make-store-assets.sh # icon + feature graphic -> store-assets/
./tools/make-store-assets.sh # icon + feature graphic + app-campaign/ -> store-assets/
./tools/make-store-screenshots.sh # phone -> screenshots/phone/
FORM_FACTOR=tablet-7in ./tools/make-store-screenshots.sh # 7-inch -> screenshots/tablet-7in/
FORM_FACTOR=tablet-10in ./tools/make-store-screenshots.sh # 10-inch -> screenshots/tablet-10in/
@@ -41,15 +43,19 @@ python3 tools/make-demo-photos.py # synthetic photo li
```
Committing `store-assets/` is also what *publishes* it: Gitea serves every committed file without a
login, at
login, and pushing the commit **is** the deployment step — there is no separate upload, so a
re-shot screenshot or re-recorded video goes live the moment it is pushed. There are two URL shapes,
and which one is right depends on what does the reading:
```
https://gitea.softwareapp-hb.de/fishfacegit/foto-duplicate-finder/raw/branch/main/<path>
https://gitea.softwareapp-hb.de/fishfacegit/foto-duplicate-finder/raw/branch/main/<path> the bytes — curl, downloads
https://gitea.softwareapp-hb.de/fishfacegit/foto-duplicate-finder/src/branch/main/<path> a page — what a browser opens
```
so pushing the commit **is** the deployment step — there is no separate upload, and a re-shot
screenshot or re-recorded video goes live as soon as it is pushed. Play's foreground-service
declaration takes its video link from exactly there; the URL is written out in
For media that distinction is not cosmetic: Gitea sends `Content-Security-Policy: default-src
'none'` with `/raw/` responses, so a video opened at a raw URL shows a blank tab, while the same file
plays on its `src` page. Play's foreground-service declaration therefore takes the **page** URL as
its video link; the reasoning and what was verified about both URLs are in
[PLAY_RELEASE_CHECKLIST](PLAY_RELEASE_CHECKLIST.md) step 5.
| Asset | Play's spec | Result | Source |
@@ -112,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
```
@@ -186,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
@@ -194,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,
@@ -286,32 +292,54 @@ 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.
⚠️ **This is the last moment the choice is still reversible.** Play's rule, from *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.”* Nothing has been uploaded yet (`versionCode` 2 is still the first
release), so a paid app is still possible; after the first upload to any track it is not. Going free
later stays one click.
**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.
**Price: one-time, base €2.99 EUR, launched with a 14-day 50% sale at €1.49.** Play derives every
other market from the base price and applies local pricing patterns, so it is one number to maintain
rather than a per-country table.
> **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
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 the pricing state has to be checked in the Console rather than set
from scratch: if *Products > App pricing* still offers **Make your app paid**, do it before rollout;
once the app is offered for free the option is gone. Going free later stays one click.
**Price: one-time, base €2.99 EUR, launched with a 14-day 50% sale at €1.49.** Both are **net** prices:
the Console's price field excludes tax, and the buyer is shown the gross price with VAT added on top
(see *What the buyer actually pays* below), so neither figure is the sticker a customer sees. Play
derives every other market from the base price and applies local pricing patterns, so it is one number
to maintain rather than a per-country table.
**Why the base price is not simply the impulse price.** A €1 base was considered and rejected: Play's
sales let a paid app be discounted whenever you like, but **nothing lets you un-discount it**.
@@ -329,17 +357,58 @@ The arithmetic, at Play's current fee for a paid app's initial purchase (10% + 5
| €1.49 (launch sale) | €1.27 | 2× |
| €1.00 (rejected) | €0.85 | 3× |
This table is **net revenue**: it starts from the price entered in the Console, and the VAT a buyer
pays on top of it — the next section — is not part of it.
Three Console details matter:
- **Leave "Default price includes tax" off unless you mean it.** Off, VAT is added on top: a German
buyer sees **€3.56** for the €2.99 base and **€1.77** during the sale. On, the sticker price is the
gross price and Play takes the tax out of it.
- **Leave "Default price includes tax" off unless you mean it.** Off, VAT is added on top of every
price you enter, and the Console keeps showing the net figure while the buyer is shown the gross
one — the single most confusing thing about selling an app in the EU. Turn it on and the number you
type *is* the sticker price, with Play taking the tax out of your share instead. Both ways are
quantified in *What the buyer actually pays* below.
- **A country you do not set a price for is a country where the app is unavailable.** Play also
enforces a per-country price range — see *currencies and price ranges allowed by country*.
- **Strikethrough is not shown everywhere.** In 12 EU member states (Belgium, Croatia, Czech
Republic, Denmark, Estonia, France, Greece, Hungary, Latvia, Netherlands, Poland, Sweden) and the
UK, buyers see the discounted price with no reference to the original. Germany is *not* one of
them, so "was €2.99" is real for a German buyer — which is why the sale is worth running.
them, so the strikethrough *is* real for a German buyer — which is why the sale is worth running.
The crossed-out figure is a **gross** price (€3.56 in Germany, €3.59 in a 20% market), not the
€2.99 typed into the Console.
### What the buyer actually pays
The Console's price field is **net of VAT** while *Default price includes tax* is off, and the
storefront shows the **gross** price, because EU consumer law requires it. The gap is the *buyer's*
country VAT, not a Console mistake, and it rounds to the cent:
| Entered (net) | Germany, 19% | 20% VAT market (AT, FR, SK, BG) |
|---|---|---|
| €2.99 base | **€3.56** | **€3.59** |
| €1.49 launch sale | **€1.77** | **€1.79** |
Arithmetic: 2.99 × 1.19 = 3.5581 and 2.99 × 1.20 = 3.5880; 1.49 × 1.19 = 1.7731 and
1.49 × 1.20 = 1.7880.
**Observed live after publishing** (checked on the Play listing): the app reads **€3.59**, and
**€1.79** while the 50% launch sale runs. Both match the 20% column exactly, so the storefront that
was checked is a 20% VAT market — Germany reads €3.56 / €1.77. Worth knowing when checking your own
listing: **Play prices the page for the country of the account viewing it**, so a German developer
whose Play account is set to, say, Austria sees the Austrian price even from a German IP.
Three options, in order of how little they change:
- **Accept €3.59/€3.56** → do nothing. You are paid on the net price either way: the VAT is collected
from the buyer and remitted by Google, so the €2.54-a-sale figure above is unaffected. Play's
*Monetise › Earnings* report is the authoritative record of what actually arrived.
- **Make €2.99 the sticker** → turn *Default price includes tax* **on**. Play then treats €2.99 as the
gross price and takes the tax out of it: the German net becomes 2.99 ÷ 1.19 ≈ **€2.51** (≈ €2.49 in
a 20% market), so you net ≈ **€2.14** a sale after the 15% fee instead of €2.54 — about **16% less**,
and the sale price becomes €1.49 gross.
- **Move the number, not the model** → keep the toggle off and choose a net price whose German gross
lands on a price point: **€2.51** net → €2.99 (2.51 × 1.19 = 2.9869). No single net price gives
€2.99 in every market, because each country's VAT differs — that is what the per-country table is
for.
### The launch sale, and the rules that shape it
@@ -370,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
@@ -418,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
@@ -460,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
+496
View File
@@ -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<br/>ScanController + ProStore + AdsController"]
main["MainActivity<br/>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<PhotoRecord>
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<DuplicateGroup>
SE-->>SC: ScanProgress.Finished(ScanResult)
SC-->>VM: StateFlow<ScanState>
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<br/>legacy paid install?"}
cache -->|yes| noAds["No ad SDK init<br/>BannerAdSlot absent"]
cache -->|no| consent["ConsentInformation<br/>requestConsentInfoUpdate()"]
consent --> form["loadAndShowConsentFormIfRequired()"]
form --> can{"canRequestAds()?"}
can -->|no| noAds
can -->|yes| init["MobileAds.initialize()"]
init --> gate{"AdPolicy.shouldShowBanner()<br/>!isPro && consent && initialized"}
gate -->|true| banner["BannerAdSlot<br/>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<br/>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.
+164
View File
@@ -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<br/>process singletons"]
main["MainActivity<br/>edge-to-edge + consent"]
theme["FotoDupTheme"]
end
subgraph UI["UI — Jetpack Compose"]
screen["ScannerScreen<br/>permissions, scaffold, menu"]
vm["ScannerViewModel<br/>selection, deletion, Pro actions"]
uiState["ScannerUiState"]
sections["ScannerSections<br/>banner, progress, empty state"]
groups["GroupSection<br/>summary + group cards"]
thumb["PhotoThumbnail"]
banner["BannerAdSlot<br/>adaptive AdView"]
proSheet["ProSheet<br/>one-time purchase"]
textRes["text/TextRes"]
end
subgraph DOMAIN["Domain"]
scanController["ScanController<br/>process-scoped scan owner"]
scanEngine["ScanEngine<br/>tiered pipeline"]
scanModels["ScanModels<br/>progress, result, phase"]
parallel["Parallel<br/>bounded CPU fan-out"]
end
subgraph SERVICE["Service"]
scanService["ScanService<br/>dataSync foreground service"]
end
subgraph DATA["Data — Android"]
mediaSource["MediaStorePhotoSource"]
hasher["PhotoHasher<br/>signature, SHA-256, pHash"]
indexStore["PhotoIndexStore<br/>SQLite hash cache"]
deleter["MediaDeleter<br/>system consent"]
permissions["AppPermissions"]
bounded["BoundedCall<br/>provider deadlines"]
photoRecord["PhotoRecord"]
end
subgraph CORE["Core — pure Kotlin, no Android imports"]
hashing["Hashing<br/>quick + SHA-256"]
phash["PerceptualHash<br/>64-bit pHash"]
rgb["RgbDHash<br/>RGB difference hashes"]
grouper["DuplicateGrouper<br/>union-find + fit"]
policy["DuplicatePolicy"]
adaptive["AdaptiveThreshold"]
group["DuplicateGroup"]
dsu["DisjointSet"]
decode["DecodeMath"]
bytes["ByteUtils"]
fingerprint["PhotoFingerprint"]
end
subgraph MONETIZATION["Monetization"]
proStore["ProStore<br/>Billing + entitlement cache"]
adsController["AdsController<br/>UMP + Mobile Ads"]
proState["ProState"]
adsState["AdsState"]
adPolicy["AdPolicy<br/>banner gate"]
legacy["LegacyPro<br/>paid-install cutoff"]
product["ProProduct<br/>pro_no_ads"]
end
subgraph DEBUG["Debug only"]
debugScan["DebugScanTrigger"]
debugPro["DebugProToggle"]
end
mediaStore[("MediaStore<br/>photo library")]
sqlite[("photo_index.db")]
prefs[("pro_entitlement<br/>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
+12
View File
@@ -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" }
+15
View File
@@ -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
Binary file not shown.

After

Width:  |  Height:  |  Size: 423 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 845 KiB

+92 -1
View File
@@ -9,6 +9,16 @@
# so every pixel ends up opaque anyway)
# feature-graphic-1024x500.png 1024 x 500 24-bit PNG, no alpha
#
# and the Google Ads *App campaign* image set, one per orientation, in app-campaign/:
# landscape-1200x628.png 1200 x 628 1.91:1 horizontal placements
# square-1200x1200.png 1200 x 1200 1:1 feed / interstitial
# portrait-320x480.png 320 x 480 2:3 vertical placements
#
# The three ad creatives are not scaled copies of one file: Google Ads matches an asset to the
# placement's orientation, so one landscape image leaves the portrait and square slots empty.
# They embed store-assets/screenshots/phone/03-results.png, so run make-store-screenshots.sh
# first if that file is missing — the check below says so instead of rendering an empty hole.
#
# Output lands in ./store-assets/ *inside* the repo, never in $HOME: the editable sources are
# the SVGs in tools/store-assets/ and these PNGs are the files that get uploaded to the Play
# Console, so they belong with the release they were made for. Pass a directory to override.
@@ -38,6 +48,87 @@ render() { # <svg> <width> <height> <filename> <keep-alpha|flatten>
echo "Writing store assets to $out"
render "$here/store-assets/icon.svg" 512 512 icon-512.png keep-alpha
render "$here/store-assets/feature-graphic.svg" 1024 500 feature-graphic-1024x500.png flatten
echo "Done. Screenshots: ./tools/make-store-screenshots.sh # reads store-assets/raw-screenshots/phone/"
# --- Google Ads App campaign creatives ---------------------------------------------------------
# One file per orientation, and each is composed rather than resized: an asset is matched to a
# placement's orientation, so three honest layouts beat twenty near-duplicates. 5 MB is the size the
# Google Ads image uploader accepts, so an oversized file is flagged here instead of at upload time.
ad_max_bytes=$((5 * 1024 * 1024))
shot="$repo/store-assets/screenshots/phone/03-results.png"
if [ ! -f "$shot" ]; then
echo "error: $shot is missing — all three App campaign creatives embed it." >&2
echo " ./tools/make-store-screenshots.sh # builds it from store-assets/raw-screenshots/phone/" >&2
exit 2
fi
ad_out="$out/app-campaign"
mkdir -p "$ad_out"
render_ad() { # <svg> <width> <height> <filename>
local svg="$1" width="$2" height="$3" name="$4"
# Check the *declared* canvas, not the finished file. --export-width/height forces the output
# size, so measuring the PNG and comparing it with those two numbers would pass every time —
# including for a source edited to a different canvas, which the export flags would then stretch
# into the size the Console asked for. This is the check that catches that.
local root declared_width declared_height
root="$(tr -d '\n' < "$svg" | grep -o '<svg[^>]*>' | head -1)"
declared_width="$(printf '%s' "$root" | grep -oE 'width="[0-9]+"' | head -1 | tr -dc '0-9')"
declared_height="$(printf '%s' "$root" | grep -oE 'height="[0-9]+"' | head -1 | tr -dc '0-9')"
if [ "$declared_width" != "$width" ] || [ "$declared_height" != "$height" ]; then
echo "error: $svg declares ${declared_width}x${declared_height} but is rendered at ${width}x${height}" >&2
echo " that would stretch the composition — fix the SVG or the size in this script" >&2
exit 1
fi
# --export-area-page is explicit rather than implied, because these three bleed: the screenshot
# card is cut by the canvas edge, so the drawing bbox is taller than the page (1200x710 for the
# landscape one). Inkscape 1.x already exports the page here — checked pixel-identical with and
# without the flag, 0 differing pixels — but 0.92 defaulted to the drawing bbox, which would
# rescale this whole composition into 1200x628 and squash it.
inkscape "$svg" \
--export-type=png --export-area-page \
--export-width="$width" --export-height="$height" \
--export-filename="$ad_out/$name" >/dev/null 2>&1
# Flatten against the brand colour: an ad is shown on the placement's own background, so an
# alpha channel is how a stray transparent pixel ends up in something a customer sees.
# -strip follows from the timestamp problem: Inkscape stamps every fresh render with tIME, so
# without it a re-run of this script is pixel-identical but byte-different, and every build
# would leave three "modified" files in git. Stripping is metadata-only — measured 0 differing
# pixels with and without it.
magick "$ad_out/$name" -background '#1B5E20' -alpha remove -alpha off -strip \
PNG24:"$ad_out/$name"
# And the finished file, because an Inkscape old enough to ignore --export-width would write the
# page size here instead — which the declared-canvas check above cannot see.
local got_width got_height
got_width="$(identify -format '%w' "$ad_out/$name")"
got_height="$(identify -format '%h' "$ad_out/$name")"
if [ "$got_width" != "$width" ] || [ "$got_height" != "$height" ]; then
echo "error: $name came out ${got_width}x${got_height}, expected ${width}x${height}" >&2
echo " check the width/height and viewBox in $svg" >&2
exit 1
fi
local warn=''
if [ "$(identify -format '%B' "$ad_out/$name")" -gt "$ad_max_bytes" ]; then
warn=' ⚠️ over the 5 MB image limit — re-encode before uploading'
fi
printf ' %s ' "$ad_out/$name"
identify -format '%wx%h %[channels] %b' "$ad_out/$name"
printf '%s\n' "$warn"
}
echo "App campaign images (Google Ads), shot embedded: $shot"
render_ad "$here/store-assets/app-campaign-landscape.svg" 1200 628 landscape-1200x628.png
render_ad "$here/store-assets/app-campaign-square.svg" 1200 1200 square-1200x1200.png
render_ad "$here/store-assets/app-campaign-portrait.svg" 320 480 portrait-320x480.png
echo "Done. Play: icon-512.png + feature-graphic-1024x500.png"
echo " Ads: app-campaign/landscape-1200x628.png, square-1200x1200.png, portrait-320x480.png"
echo " ^ upload these PNGs; the tools/store-assets/*.svg are sources, and Ads rejects SVG"
echo " Screenshots: ./tools/make-store-screenshots.sh # reads store-assets/raw-screenshots/phone/"
echo " Tablets: FORM_FACTOR=tablet-7in ./tools/make-store-screenshots.sh"
echo " FORM_FACTOR=tablet-10in ./tools/make-store-screenshots.sh"
@@ -0,0 +1,59 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
width="1200" height="628" viewBox="0 0 1200 628">
<!--
App campaign image, landscape 1.91:1 (1200 x 628) — the orientation Google Ads asks for in
horizontal placements (Display, YouTube in-stream, the feed).
Same palette (#0D3D13 -> #1B5E20 -> #2E7D32) and the same icon motif as icon.svg and
feature-graphic.svg, copied verbatim, so the ad, the store listing and the launcher icon
cannot drift apart.
The screenshot is store-assets/screenshots/phone/03-results.png — the committed Play
screenshot of the *generated* demo library (17 groups, 83.5 MB reclaimable), never a real
library. It is anchored to the card's top edge (xMidYMin slice) so the summary card stays in
frame and the card bleeds off the bottom instead of ending in mid-air.
This file is a *source*, not an upload. Google Ads takes raster image assets (PNG or JPG) and
rejects SVG — the file to upload is the PNG this source renders to through the script below.
Edit this file, then: ./tools/make-store-assets.sh
-->
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="#0D3D13" />
<stop offset="0.55" stop-color="#1B5E20" />
<stop offset="1" stop-color="#2E7D32" />
</linearGradient>
<clipPath id="shot">
<rect x="760" y="150" width="400" height="560" rx="26" />
</clipPath>
</defs>
<rect x="0" y="0" width="1200" height="628" fill="url(#bg)" />
<!-- Icon motif, centred on (165, 195) at ~170 px wide. scale 4.67 = 170 / 36.4, the motif's
own bbox width; translate(-49.8, -46.85) is that bbox's centre, as in feature-graphic.svg. -->
<g transform="translate(165,195) scale(4.67) translate(-49.8,-46.85)">
<g transform="translate(30,22) scale(1.9)">
<path d="M4,5 h16 a1,1 0 0 1 1,1 v12 a1,1 0 0 1 -1,1 h-16 a1,1 0 0 1 -1,-1 v-12 a1,1 0 0 1 1,-1 z"
fill="#FFFFFF" fill-opacity="0.45" />
</g>
<g transform="translate(24,28) scale(1.9)">
<path d="M4,5 h16 a1,1 0 0 1 1,1 v12 a1,1 0 0 1 -1,1 h-16 a1,1 0 0 1 -1,-1 v-12 a1,1 0 0 1 1,-1 z"
fill="none" stroke="#FFFFFF" stroke-width="1.6" />
<path d="M7.5,9 m-1.4,0 a1.4,1.4 0 1 0 2.8,0 a1.4,1.4 0 1 0 -2.8,0" fill="#FFFFFF" />
<path d="M4,17 l4,-5 l3,3.5 l3.5,-4.5 l5.5,6 z" fill="#FFFFFF" />
</g>
</g>
<image id="shot-image" x="760" y="150" width="400" height="560" clip-path="url(#shot)"
preserveAspectRatio="xMidYMin slice"
xlink:href="../../store-assets/screenshots/phone/03-results.png" />
<text id="app-name" x="80" y="360" font-family="DejaVu Sans" font-weight="bold" font-size="62"
fill="#FFFFFF">Foto Dup Finder</text>
<text id="tagline-1" x="82" y="416" font-family="DejaVu Sans" font-size="31"
fill="#FFFFFF" fill-opacity="0.92">Find and remove duplicate photos</text>
<text id="tagline-2" x="82" y="460" font-family="DejaVu Sans" font-size="31"
fill="#FFFFFF" fill-opacity="0.92">No ads. No uploads. Fully offline.</text>
</svg>

After

Width:  |  Height:  |  Size: 3.0 KiB

@@ -0,0 +1,53 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
width="320" height="480" viewBox="0 0 320 480">
<!--
App campaign image, portrait 2:3 (320 x 480) — the orientation Google Ads asks for in vertical
placements (YouTube Shorts, in-app interstitials).
Google's size for this one is small on purpose, so the composition is different rather than a
scaled copy: identity in the top third at a size that survives a thumbnail, then the committed
demo-library screenshot below it. Text inside the screenshot is texture at this size, which is
why the creative carries its own wording.
Same palette and icon motif as app-campaign-landscape.svg / app-campaign-square.svg.
This file is a *source*, not an upload: Google Ads takes PNG/JPG, so the file to upload is
store-assets/app-campaign/portrait-320x480.png, which this source renders to.
Edit this file, then: ./tools/make-store-assets.sh
-->
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="#0D3D13" />
<stop offset="0.55" stop-color="#1B5E20" />
<stop offset="1" stop-color="#2E7D32" />
</linearGradient>
<clipPath id="shot">
<rect x="28" y="200" width="264" height="310" rx="20" />
</clipPath>
</defs>
<rect x="0" y="0" width="320" height="480" fill="url(#bg)" />
<!-- Icon motif, centred on (160, 66) at ~80 px wide (scale 2.2 = 80 / 36.4). -->
<g transform="translate(160,66) scale(2.2) translate(-49.8,-46.85)">
<g transform="translate(30,22) scale(1.9)">
<path d="M4,5 h16 a1,1 0 0 1 1,1 v12 a1,1 0 0 1 -1,1 h-16 a1,1 0 0 1 -1,-1 v-12 a1,1 0 0 1 1,-1 z"
fill="#FFFFFF" fill-opacity="0.45" />
</g>
<g transform="translate(24,28) scale(1.9)">
<path d="M4,5 h16 a1,1 0 0 1 1,1 v12 a1,1 0 0 1 -1,1 h-16 a1,1 0 0 1 -1,-1 v-12 a1,1 0 0 1 1,-1 z"
fill="none" stroke="#FFFFFF" stroke-width="1.6" />
<path d="M7.5,9 m-1.4,0 a1.4,1.4 0 1 0 2.8,0 a1.4,1.4 0 1 0 -2.8,0" fill="#FFFFFF" />
<path d="M4,17 l4,-5 l3,3.5 l3.5,-4.5 l5.5,6 z" fill="#FFFFFF" />
</g>
</g>
<image id="shot-image" x="28" y="200" width="264" height="310" clip-path="url(#shot)"
preserveAspectRatio="xMidYMin slice"
xlink:href="../../store-assets/screenshots/phone/03-results.png" />
<text id="app-name" x="160" y="142" text-anchor="middle" font-family="DejaVu Sans" font-weight="bold"
font-size="28" fill="#FFFFFF">Foto Dup Finder</text>
<text id="tagline-1" x="160" y="172" text-anchor="middle" font-family="DejaVu Sans" font-size="15"
fill="#FFFFFF" fill-opacity="0.92">Find duplicate photos</text>
</svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

@@ -0,0 +1,53 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
width="1200" height="1200" viewBox="0 0 1200 1200">
<!--
App campaign image, square 1:1 (1200 x 1200) — the orientation Google Ads asks for in feed and
interstitial placements.
Stacked version of app-campaign-landscape.svg: identity on top, the committed demo-library
screenshot bleeding off the bottom edge. Same palette, same icon motif, same source rules —
see that file for the reasoning.
This file is a *source*, not an upload: Google Ads takes PNG/JPG, so the file to upload is
store-assets/app-campaign/square-1200x1200.png, which this source renders to.
Edit this file, then: ./tools/make-store-assets.sh
-->
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="#0D3D13" />
<stop offset="0.55" stop-color="#1B5E20" />
<stop offset="1" stop-color="#2E7D32" />
</linearGradient>
<clipPath id="shot">
<rect x="380" y="560" width="440" height="660" rx="30" />
</clipPath>
</defs>
<rect x="0" y="0" width="1200" height="1200" fill="url(#bg)" />
<!-- Icon motif, centred on (600, 175) at ~200 px wide (scale 5.5 = 200 / 36.4). -->
<g transform="translate(600,175) scale(5.5) translate(-49.8,-46.85)">
<g transform="translate(30,22) scale(1.9)">
<path d="M4,5 h16 a1,1 0 0 1 1,1 v12 a1,1 0 0 1 -1,1 h-16 a1,1 0 0 1 -1,-1 v-12 a1,1 0 0 1 1,-1 z"
fill="#FFFFFF" fill-opacity="0.45" />
</g>
<g transform="translate(24,28) scale(1.9)">
<path d="M4,5 h16 a1,1 0 0 1 1,1 v12 a1,1 0 0 1 -1,1 h-16 a1,1 0 0 1 -1,-1 v-12 a1,1 0 0 1 1,-1 z"
fill="none" stroke="#FFFFFF" stroke-width="1.6" />
<path d="M7.5,9 m-1.4,0 a1.4,1.4 0 1 0 2.8,0 a1.4,1.4 0 1 0 -2.8,0" fill="#FFFFFF" />
<path d="M4,17 l4,-5 l3,3.5 l3.5,-4.5 l5.5,6 z" fill="#FFFFFF" />
</g>
</g>
<image id="shot-image" x="380" y="560" width="440" height="660" clip-path="url(#shot)"
preserveAspectRatio="xMidYMin slice"
xlink:href="../../store-assets/screenshots/phone/03-results.png" />
<text id="app-name" x="600" y="375" text-anchor="middle" font-family="DejaVu Sans" font-weight="bold"
font-size="78" fill="#FFFFFF">Foto Dup Finder</text>
<text id="tagline-1" x="600" y="435" text-anchor="middle" font-family="DejaVu Sans" font-size="36"
fill="#FFFFFF" fill-opacity="0.92">Find and remove duplicate photos</text>
<text id="tagline-2" x="600" y="483" text-anchor="middle" font-family="DejaVu Sans" font-size="36"
fill="#FFFFFF" fill-opacity="0.92">No ads. No uploads. Fully offline.</text>
</svg>

After

Width:  |  Height:  |  Size: 2.6 KiB