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
This commit is contained in:
2026-10-20 09:28:29 +02:00
parent 3afa7d777d
commit 22091dd808
36 changed files with 3268 additions and 295 deletions
+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 = 3
versionName = "1.0.2"
versionCode = 4
versionName = "1.1.0"
// AdMob reads its application id from the manifest, so it has to be a placeholder:
// the value differs between a developer machine, CI and a release build.
manifestPlaceholders["admobAppId"] = adMobAppId
buildConfigField("String", "ADMOB_BANNER_UNIT_ID", "\"$adMobBannerUnitId\"")
buildConfigField("long", "LEGACY_PRO_CUTOFF_EPOCH_MS", "${legacyProCutoffEpochMs}L")
vectorDrawables {
useSupportLibrary = true
@@ -93,6 +145,8 @@ android {
buildFeatures {
compose = true
// AdMob unit id + legacy-Pro cutoff are injected here.
buildConfig = true
}
testOptions {
@@ -186,6 +240,13 @@ dependencies {
implementation(libs.kotlinx.coroutines.android)
implementation(libs.coil.compose)
// Free tier: AdMob banner + UMP consent. Pro tier: one-time Play Billing product.
// The ads SDK merges INTERNET, ACCESS_NETWORK_STATE, AD_ID and the Privacy Sandbox
// permissions into the release manifest; billing-ktx merges com.android.vending.BILLING.
implementation(libs.play.services.ads)
implementation(libs.user.messaging.platform)
implementation(libs.billing.ktx)
debugImplementation(libs.androidx.compose.ui.tooling)
testImplementation(libs.junit)
+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)
}
}
@@ -12,11 +12,23 @@ 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?) {
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(
@@ -28,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
+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))
}
}