- 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
21 KiB
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; agent-specific rules live in../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; the diagrams below focus
on the flows that are hard to read from a static graph.
2. Layered architecture
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 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
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:
BoundedCallgives every provider call a deadline, so one wedged file cannot freeze the scan.withTimeoutOrNullaround 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
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
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
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.cutoffEpochMsto the instant of the first freemium release; - every install older than that instant is treated as a paid install and gets Pro;
KEY_ORIGIN_RESOLVEDpersists the decision so a later Play query cannot revoke it;- a cutoff of
0disables 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
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.createDeleteRequestorcreateTrashRequest. The app never requestsMANAGE_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.
BannerAdSlotowns theAdViewlifecycle 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:
- Update the affected node/edge in
codemap.mmd. - Update the matching diagram, file index and change-impact row here.
- Update
../AGENTS.mdif an architectural rule or command changed. - Update
README.md,PRIVACY.md,CHANGELOG.md,docs/ROADMAP.md,docs/MONETIZATION.md,docs/STORE_LISTING.mdanddocs/PLAY_RELEASE_CHECKLIST.mdwhen the change affects users, permissions, monetisation or release steps. - Verify the Mermaid syntax in a Markdown preview before committing.
- 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.