diff --git a/CHANGELOG.md b/CHANGELOG.md index 91bfe4a8435a..9e03fb04d06c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ release, a pull request cuts that heading to the version. The release run makes section the body of the GitHub release, and refuses a version without one. `scripts/store-copy.py` writes Play's "What's new" from the same section, under 500 characters per locale. +## Unreleased + +- The free app starts with 7 days of Pro: every editing tool and no ads. + ## 4.26.0 - Recent documents show an icon for their file type. diff --git a/app/src/ads/java/app/opendocument/droid/nonfree/AdManager.kt b/app/src/ads/java/app/opendocument/droid/nonfree/AdManager.kt index 59e0e1f058d9..5ef702d4e5a2 100644 --- a/app/src/ads/java/app/opendocument/droid/nonfree/AdManager.kt +++ b/app/src/ads/java/app/opendocument/droid/nonfree/AdManager.kt @@ -3,6 +3,7 @@ package app.opendocument.droid.nonfree import android.app.Activity import android.os.Handler import android.os.Looper +import android.os.SystemClock import android.util.TypedValue import android.view.View import android.widget.ImageView @@ -10,6 +11,7 @@ import android.widget.LinearLayout import android.widget.TextView import app.opendocument.droid.R import app.opendocument.droid.background.AppPreferences +import app.opendocument.droid.ui.SnackbarHelper import com.google.android.gms.ads.AdListener import com.google.android.gms.ads.AdRequest import com.google.android.gms.ads.AdSize @@ -30,6 +32,11 @@ class AdManager { /** Whether [initialize] ran far enough for the fields below to exist. */ private var initialized = false + /** + * Whether the ads sdk was started. Not before the first consent update: the trial asks none. + */ + private var sdkStarted = false + private lateinit var activity: Activity private lateinit var crashManager: CrashManager private lateinit var analyticsManager: AnalyticsManager @@ -55,6 +62,30 @@ class AdManager { private val retries = Handler(Looper.getMainLooper()) + /** Ends the house ad's turn, see [onDocumentOpened]. */ + private val houseTurns = Handler(Looper.getMainLooper()) + + private val houseTurn = HouseAdTurn(SystemClock::elapsedRealtime) + + /** + * The first request after the turn, for a new banner: [AdListener.onAdLoaded] shows it, and a + * failure keeps the house ad up and retries as usual. + */ + private val houseTurnEnd = Runnable { + houseTurn.end() + + if (!enabled || isActivityGone()) { + return@Runnable + } + + retries.removeCallbacksAndMessages(null) + retryDelay = FIRST_RETRY_DELAY_MS + + // the banner that was up before the turn is not shown again: a new one is asked for + requestedWidth = 0 + showAdaptiveBanner() + } + /** * How long the next retry waits: doubling from [FIRST_RETRY_DELAY_MS] up to the unit's rate. */ @@ -67,7 +98,7 @@ class AdManager { private val retry = Runnable { val adView = this.adView - if (enabled && !paused && adView != null && !isActivityGone()) { + if (enabled && !paused && !houseTurn.isRunning && adView != null && !isActivityGone()) { retryDelay = (retryDelay * 2).coerceAtMost(RETRY_DELAY_MS) scheduleRetry() @@ -92,6 +123,13 @@ class AdManager { AppPreferences.of(activity).edit().putInt(PREF_HOUSE_AD_INDEX, value).apply() } + /** Fresh documents opened with the banner up, on disk like [houseAdIndex]. */ + private var documentsOnAds: Int + get() = AppPreferences.of(activity).getInt(PREF_DOCUMENTS_ON_ADS, 0) + set(value) { + AppPreferences.of(activity).edit().putInt(PREF_DOCUMENTS_ON_ADS, value).apply() + } + fun initialize( activity: Activity, analyticsManager: AnalyticsManager, @@ -107,6 +145,15 @@ class AdManager { return } + initialized = true + } + + private fun startSdk() { + if (sdkStarted) { + return + } + sdkStarted = true + try { MobileAds.initialize(activity) } catch (e: Throwable) { @@ -119,8 +166,6 @@ class AdManager { val configuration = RequestConfiguration.Builder().setTestDeviceIds(listOf(TEST_DEVICE_ID)).build() MobileAds.setRequestConfiguration(configuration) - - initialized = true } fun setEnabled(enabled: Boolean) { @@ -141,6 +186,46 @@ class AdManager { onPurchaseRequested = listener } + /** + * Counts a fresh document opened where consent lets a banner be asked for. Every + * [HouseAdTurn.EVERY]th one starts with the house ad, and google is first asked once one + * banner's time has passed - as OpenDocument.ios does. + */ + fun onDocumentOpened() { + houseTurn.documentShown() + countDocumentIfReady() + } + + fun onDocumentClosed() { + houseTurn.documentClosed() + // Unlike iOS, the banner outlives the reader. Do not carry the fifth document's turn + // into the next document or onto the landing screen. + if (houseTurn.isRunning) { + houseTurns.removeCallbacks(houseTurnEnd) + houseTurnEnd.run() + } + } + + private fun countDocumentIfReady() { + if (!enabled || isActivityGone() || !houseTurn.takeDocument(hasConsentDecision(), paused)) { + return + } + + val opened = documentsOnAds + 1 + documentsOnAds = opened + + if (!houseTurn.documentOpened(opened)) { + return + } + + retries.removeCallbacksAndMessages(null) + + showHouseAd() + + houseTurns.removeCallbacks(houseTurnEnd) + houseTurns.postDelayed(houseTurnEnd, HouseAdTurn.LENGTH_MILLIS) + } + /** Swaps the slot between the two views already in it, or hides both while neither has run. */ private fun show(view: View?) { if (!enabled) { @@ -186,6 +271,8 @@ class AdManager { return } + startSdk() + val params = ConsentRequestParameters.Builder().setTagForUnderAgeOfConsent(false).build() val consentInformation = UserMessagingPlatform.getConsentInformation(activity) @@ -245,6 +332,7 @@ class AdManager { ) activity.runOnUiThread { + countDocumentIfReady() onConsentSettled?.invoke() if (enabled) { @@ -273,16 +361,98 @@ class AdManager { activity.runOnUiThread { showAdaptiveBanner() } } - /** Not gated on [enabled]: buying ad removal clears that, withdrawal outlives it. */ - fun isPrivacyOptionsRequired(): Boolean = - consentInformation?.privacyOptionsRequirementStatus == + /** + * Not gated on [enabled]: buying ad removal clears that, withdrawal outlives it. Before an + * update in this launch, which the trial does not ask for, a decision stored on the device + * answers. + */ + fun isPrivacyOptionsRequired(): Boolean { + val consentInformation = this.consentInformation ?: return hasStoredDecision() + + return consentInformation.privacyOptionsRequirementStatus == ConsentInformation.PrivacyOptionsRequirementStatus.REQUIRED + } + + /** A consent string the form left on the device, where the gdpr applies. Read locally. */ + private fun hasStoredDecision(): Boolean { + if (!::activity.isInitialized) { + return false + } + + val preferences = AppPreferences.of(activity) + + val tcf = + preferences.getInt(IABTCF_GDPR_APPLIES, 0) == 1 && + !preferences.getString(IABTCF_TC_STRING, null).isNullOrEmpty() + val gpp = !preferences.getString(IABGPP_STRING, null).isNullOrEmpty() + + return tcf || gpp + } /** Only from user input - the sdk preloads the form for exactly this. */ fun showPrivacyOptions() { + if (consentInformation != null) { + showPrivacyOptionsForm() + + return + } + + // no update in this launch yet: ask for one now, the tap being the reason, without the + // banner that settling the consent flow brings + val params = ConsentRequestParameters.Builder().setTagForUnderAgeOfConsent(false).build() + UserMessagingPlatform.getConsentInformation(activity) + .requestConsentInfoUpdate( + activity, + params, + { + if (isActivityGone()) { + return@requestConsentInfoUpdate + } + + if ( + UserMessagingPlatform.getConsentInformation(activity) + .privacyOptionsRequirementStatus == + ConsentInformation.PrivacyOptionsRequirementStatus.REQUIRED + ) { + showPrivacyOptionsForm() + } else { + showPrivacyOptionsUnavailable() + } + }, + { requestConsentError -> + crashManager.log("consent info update failed: " + describe(requestConsentError)) + + if (!isActivityGone()) { + showPrivacyOptionsUnavailable() + } + }, + ) + } + + /** Says so, rather than a tap that does nothing: offline, or no form to show. */ + private fun showPrivacyOptionsUnavailable() { + SnackbarHelper.show( + activity, + R.string.privacy_options_unavailable, + null, + isIndefinite = false, + isError = true, + ) + } + + private fun showPrivacyOptionsForm() { UserMessagingPlatform.showPrivacyOptionsForm(activity) { formError -> + // the answer may have changed, and what waited for the form can come now + if (!isActivityGone()) { + activity.runOnUiThread { onConsentSettled?.invoke() } + } + if (formError != null) { crashManager.log("privacy options form failed: " + describe(formError)) + + if (!isActivityGone()) { + showPrivacyOptionsUnavailable() + } } } } @@ -311,7 +481,7 @@ class AdManager { // for a banner that is on screen, so one that is torn out never gets asked for again layOutHouseAd(houseAd ?: addHouseAd().also { houseAd = it }, adSize, adWidth) - if (!hasConsentDecision()) { + if (!hasConsentDecision() || houseTurn.isRunning) { showHouseAd() return @@ -355,6 +525,11 @@ class AdManager { retryDelay = FIRST_RETRY_DELAY_MS hasAd = true + // one asked for before the turn waits for its end, which asks anew + if (houseTurn.isRunning) { + return + } + show(adView) } @@ -363,8 +538,10 @@ class AdManager { crashManager.log("ad failed to load: " + error.code + "/" + error.message) // a refresh that did not fill leaves the ad it already has up, and the sdk - // keeps refreshing it; only an empty slot needs the house ad and our own asking - if (hasAd) { + // keeps refreshing it; only an empty slot needs the house ad and our own + // asking. + // the turn's end asks anyway + if (hasAd || houseTurn.isRunning) { return } @@ -510,16 +687,23 @@ class AdManager { retries.removeCallbacksAndMessages(null) + // the turn waits for the activity, and ends no sooner than a minute on screen + houseTurns.removeCallbacksAndMessages(null) + houseTurn.pause() + adView?.pause() } fun resumeAds() { paused = false + houseTurn.resume()?.let { houseTurns.postDelayed(houseTurnEnd, it) } + adView?.resume() + countDocumentIfReady() // a slot that came back still empty gets asked for again; a filled one is the sdk's - if (enabled && !hasAd && adView != null && !isActivityGone()) { + if (enabled && !hasAd && !houseTurn.isRunning && adView != null && !isActivityGone()) { scheduleRetry() } } @@ -535,6 +719,8 @@ class AdManager { fun destroyAds() { retries.removeCallbacksAndMessages(null) + houseTurns.removeCallbacksAndMessages(null) + houseTurn.end() destroyAdView() @@ -563,6 +749,14 @@ class AdManager { const val TEST_DEVICE_ID = "46C05048B04145D0724C1ADA7FC17619" const val PREF_HOUSE_AD_INDEX = "house_ad_index" + const val PREF_DOCUMENTS_ON_ADS = "house_ad_documents" + + // what the consent form stores under the iab's tcf keys + const val IABTCF_GDPR_APPLIES = "IABTCF_gdprApplies" + const val IABTCF_TC_STRING = "IABTCF_TCString" + + // and under the iab's gpp keys, for the us states + const val IABGPP_STRING = "IABGPP_HDR_GppString" // 10s, 20s, 40s, then the 60s the unit refreshes at. Not shorter: the sdk throttles a // burst of failed requests itself. diff --git a/app/src/ads/java/app/opendocument/droid/nonfree/PlayBilling.kt b/app/src/ads/java/app/opendocument/droid/nonfree/PlayBilling.kt index e2df46cd771f..58670346c2b9 100644 --- a/app/src/ads/java/app/opendocument/droid/nonfree/PlayBilling.kt +++ b/app/src/ads/java/app/opendocument/droid/nonfree/PlayBilling.kt @@ -22,7 +22,13 @@ import com.android.billingclient.api.QueryPurchasesParams class PlayBilling( context: Context, private val crashManager: CrashManager, - private val onOwned: (entitlement: Entitlement, purchased: Boolean) -> Unit, + private val onOwned: + (entitlement: Entitlement, purchased: Boolean, passPending: Boolean) -> Unit, + /** + * Play's sheet closed without a purchase - cancelled, or failed - or play could not be asked + * what the purchase came to. + */ + private val onPurchaseEnded: () -> Unit, ) { private val mainThread = Handler(Looper.getMainLooper()) @@ -50,12 +56,17 @@ class PlayBilling( /** * Reports what the account owns through `onOwned`, and acknowledges what is not acknowledged * yet: play refunds a purchase that is not within three days. Says nothing if play did not - * answer, so a launch without a network takes nothing away. [purchased] is passed on: true - * after the purchase sheet, false for what play restores. + * answer, so a launch without a network takes nothing away - but a purchase it was asked after + * ends there. [purchased] is passed on: true after the purchase sheet, false for what play + * restores. [afterSheet] says the purchase sheet led here. */ - fun queryOwned(purchased: Boolean = false) { + fun queryOwned(purchased: Boolean = false, afterSheet: Boolean = purchased) { whenConnected { ok -> if (!ok) { + if (afterSheet) { + onPurchaseEnded() + } + return@whenConnected } @@ -63,6 +74,7 @@ class PlayBilling( val owned = HashMap>() var pending = types.size var failed = false + var passPending = false for (type in types) { val params = QueryPurchasesParams.newBuilder().setProductType(type).build() @@ -73,6 +85,14 @@ class PlayBilling( owned[type] = purchases.filter { it.purchaseState == Purchase.PurchaseState.PURCHASED } + if ( + purchases.any { + it.purchaseState == Purchase.PurchaseState.PENDING && + Entitlement.PASS_PRODUCT in it.products + } + ) { + passPending = true + } } else { crashManager.log( "billing query failed: " + type + "/" + result.responseCode @@ -82,6 +102,9 @@ class PlayBilling( } pending-- + if (pending == 0 && failed && afterSheet) { + onPurchaseEnded() + } if (pending == 0 && !failed) { owned.values.flatten().forEach(::acknowledge) @@ -95,6 +118,7 @@ class PlayBilling( }, ), purchased, + passPending, ) } } @@ -203,11 +227,15 @@ class PlayBilling( // asked again rather than read from the update: one answer, whichever way it came BillingClient.BillingResponseCode.OK -> queryOwned(purchased = true) - BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED -> queryOwned() + BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED -> queryOwned(afterSheet = true) - BillingClient.BillingResponseCode.USER_CANCELED -> {} + BillingClient.BillingResponseCode.USER_CANCELED -> onPurchaseEnded() - else -> crashManager.log("purchase failed: " + result.responseCode) + else -> { + crashManager.log("purchase failed: " + result.responseCode) + + onPurchaseEnded() + } } } diff --git a/app/src/androidTest/java/app/opendocument/droid/test/ScreenshotTests.kt b/app/src/androidTest/java/app/opendocument/droid/test/ScreenshotTests.kt index cc19277afa96..0197ee36a213 100644 --- a/app/src/androidTest/java/app/opendocument/droid/test/ScreenshotTests.kt +++ b/app/src/androidTest/java/app/opendocument/droid/test/ScreenshotTests.kt @@ -237,7 +237,7 @@ class ScreenshotTests { instrumentation.runOnMainSync { activity .findViewById(R.id.editing_tools) - .showFormatting(sheet = false, locked = true) + .showFormatting(sheet = false, locked = true, trialDays = null) } } diff --git a/app/src/main/java/app/opendocument/droid/background/BillingPreferences.kt b/app/src/main/java/app/opendocument/droid/background/BillingPreferences.kt index 9b10ef512cb8..a1091d419996 100644 --- a/app/src/main/java/app/opendocument/droid/background/BillingPreferences.kt +++ b/app/src/main/java/app/opendocument/droid/background/BillingPreferences.kt @@ -2,6 +2,7 @@ package app.opendocument.droid.background import android.content.Context import androidx.core.content.edit +import app.opendocument.droid.nonfree.ProTrial /** The last answer from play, so that a launch starts without waiting for the next one. */ class BillingPreferences(context: Context) { @@ -33,9 +34,33 @@ class BillingPreferences(context: Context) { sharedPreferences.edit { putBoolean(PASS_KEY, pass) } } + /** The pro trial: when it started, whether its end is answered, whether its intro was seen. */ + fun trial(): ProTrial.Stored = + ProTrial.Stored( + startedAt = sharedPreferences.getLong(TRIAL_STARTED_AT_KEY, -1L).takeIf { it >= 0 }, + settled = sharedPreferences.getBoolean(TRIAL_SETTLED_KEY, false), + introShown = sharedPreferences.getBoolean(TRIAL_INTRO_KEY, false), + ended = sharedPreferences.getBoolean(TRIAL_ENDED_KEY, false), + ) + + fun setTrial(trial: ProTrial.Stored) { + sharedPreferences.edit { + val startedAt = trial.startedAt + if (startedAt == null) remove(TRIAL_STARTED_AT_KEY) + else putLong(TRIAL_STARTED_AT_KEY, startedAt) + putBoolean(TRIAL_SETTLED_KEY, trial.settled) + putBoolean(TRIAL_INTRO_KEY, trial.introShown) + putBoolean(TRIAL_ENDED_KEY, trial.ended) + } + } + private companion object { const val PURCHASE_KEY = "purchaseAcknowledged" const val LIFETIME_PRO_KEY = "lifetimePro" const val PASS_KEY = "pass" + const val TRIAL_STARTED_AT_KEY = "trialStartedAt" + const val TRIAL_SETTLED_KEY = "trialSettled" + const val TRIAL_INTRO_KEY = "trialIntroShown" + const val TRIAL_ENDED_KEY = "trialEnded" } } diff --git a/app/src/main/java/app/opendocument/droid/nonfree/BillingManager.kt b/app/src/main/java/app/opendocument/droid/nonfree/BillingManager.kt index 93e8dd1003ff..95180368d2ec 100644 --- a/app/src/main/java/app/opendocument/droid/nonfree/BillingManager.kt +++ b/app/src/main/java/app/opendocument/droid/nonfree/BillingManager.kt @@ -2,6 +2,8 @@ package app.opendocument.droid.nonfree import android.app.Activity import android.content.Context +import android.os.Handler +import android.os.Looper import app.opendocument.droid.background.BillingPreferences class BillingManager { @@ -17,6 +19,23 @@ class BillingManager { /** Whether removeAds ran in this session. The ads stay away until the next launch. */ private var adsRemoved = false + private val trial = ProTrial(System::currentTimeMillis) + + /** Whether this build runs the trial at all. Off under instrumented tests. */ + private var trialOffered = true + + /** Read at launch, its phase kept for the session like an ended pass. Null without a trial. */ + private var trialState: ProTrial.State? = null + + private var onTrialChanged: (() -> Unit)? = null + + private val billingTimeout = Handler(Looper.getMainLooper()) + + /** Fires when the trial's screens may have become due or gone: play answered, or took long. */ + fun setTrialListener(listener: () -> Unit) { + onTrialChanged = listener + } + /** * Fires when play reports what the preferences did not know: a purchase, a restore, or an ended * pass. [unlocked] says whether the pro features have just been unlocked, and [purchased] @@ -37,32 +56,87 @@ class BillingManager { preferences.setPurchased(true) } + if (enabled && trialOffered) { + val state = trial.atLaunch(preferences.trial(), Features.withAds, isPro(), isAdFree()) + preferences.setTrial(state.stored) + trialState = state + + // the intro waits for play, but not for ever + billingTimeout.postDelayed( + { + updateTrial { it.billingTimedOut() } + }, + BILLING_TIMEOUT_MILLIS, + ) + } + // also without play: the last answer stands until play gives a new one - Features.unlocked = isPro() + Features.unlocked = trialState?.unlocked ?: isPro() if (!enabled) { adManager.showGoogleAds() return } - if (isAdFree()) { - removeAds(adManager) - } else { - adManager.showGoogleAds() + when { + isAdFree() -> removeAds(adManager) + // no banner and no consent form until the user picks ads on the end screen + holdsAds() -> Unit + else -> adManager.showGoogleAds() } // asked at every launch, not only until something turns up: the flags live only on this // device, and a pass ends. the ads show until play answers playBilling = - PlayBilling(context, crashManager) { entitlement, purchased -> - crashManager.log("billing answered") - - apply(entitlement, purchased) - } + PlayBilling( + context, + crashManager, + { entitlement, purchased, passPending -> + crashManager.log("billing answered") + + apply(entitlement, purchased, passPending) + }, + { endPurchase() }, + ) playBilling?.queryOwned() } - private fun apply(entitlement: Entitlement, purchased: Boolean) { + /** Whether this launch started the trial. */ + fun startedTrial(): Boolean = trialState?.startedNow == true + + /** + * Reads the trial's phase again, for a process that outlived the trial's end. Only where no + * document is open, so no tool is taken away mid-edit. + */ + fun recheckTrial() { + val state = trialState ?: return + val next = trial.recheck(state) + if (next == state) { + return + } + + if (next.phase != state.phase) { + Features.unlocked = isPro() || next.phase == ProTrial.Phase.RUNNING + } + + // The caller is opening or closing a document. It presents any due screen once that + // transition finishes, rather than from a synchronous listener here. + updateTrial(notifying = false) { next } + } + + private fun updateTrial(notifying: Boolean = true, change: (ProTrial.State) -> ProTrial.State) { + val state = trialState ?: return + val next = change(state) + + trialState = next + billingPreferences?.setTrial(next.stored) + + if (notifying) { + onTrialChanged?.invoke() + } + } + + private fun apply(entitlement: Entitlement, purchased: Boolean, passPending: Boolean) { val preferences = billingPreferences ?: return val adManager = adManager ?: return @@ -92,6 +166,10 @@ class BillingManager { if (wasAdFree != isAdFree() || wasPro != isPro()) { onEntitlementChanged?.invoke(unlocked, purchased) } + + // pro answers the end screen too, and a pass that lapses later brings today's ads back + billingTimeout.removeCallbacksAndMessages(null) + updateTrial { it.billingAnswered(isPro(), isAdFree(), passPending) } } private fun removeAds(adManager: AdManager) { @@ -99,6 +177,11 @@ class BillingManager { adManager.removeAds() + // the trial asks google for nothing, the consent update included + if (holdsAds()) { + return + } + // no banner to gate, but withdrawal has to survive the purchase, and only an // update tells us whether the sdk wants a way back out adManager.updateConsentInfo() @@ -116,7 +199,58 @@ class BillingManager { } /** Whether ads are on screen, or about to be: not after [isAdFree] was true in this session. */ - fun showsAds(): Boolean = !isAdFree() && !adsRemoved + fun showsAds(): Boolean = !isAdFree() && !adsRemoved && !holdsAds() + + /** The trial, or its end screen unanswered: no banner and no call to google. */ + private fun holdsAds(): Boolean = trialState?.adsHeld == true + + /** The trial's days left while it runs, rounded up; null otherwise or with pro. */ + fun trialDaysLeft(): Int? { + val state = trialState ?: return null + if (state.phase != ProTrial.Phase.RUNNING || isPro()) { + return null + } + + return state.stored.startedAt?.let { trial.daysLeft(it) } + } + + /** Whether the start screen is due: the trial runs, play answered, and it was never closed. */ + fun isTrialIntroDue(): Boolean = trialState?.introDue == true && !isPro() + + fun setTrialIntroShown() { + updateTrial { it.introShown() } + } + + /** Whether the start or end screen is due, or the start still waits for play. */ + fun isTrialScreenPending(): Boolean = trialState?.screenPending == true && !isPro() + + /** Whether the end screen is due: the trial is over and the user has not chosen yet. */ + fun isTrialEndDue(): Boolean = trialState?.endDue == true && !isPro() + + private fun endPurchase() { + updateTrial { it.purchaseEnded() } + } + + /** Whether the end screen offers ads: not to an old ad removal, which closes it instead. */ + fun trialEndOffersAds(): Boolean = trialState?.endShowsAdsButton ?: !isAdFree() + + /** + * The end screen's free answer: ads from now on. The consent form opens only where no answer is + * on file, and the banner follows. + */ + fun chooseAds() { + settleTrial() + + val adManager = adManager ?: return + if (!isAdFree()) { + adManager.showGoogleAds() + } + } + + /** The end screen is answered, and the app is what the entitlement says from now on. */ + fun settleTrial() { + updateTrial { it.settled() } + } /** The pro features bought in lite: the pass, or an old purchase for life. */ fun isPro(): Boolean { @@ -135,17 +269,41 @@ class BillingManager { /** See [PlayBilling.buyPass]. Without play, [onUnavailable] runs at once. */ fun buyPass(activity: Activity, onUnavailable: () -> Unit) { - playBilling?.buyPass(activity, onUnavailable) ?: onUnavailable() + val playBilling = playBilling + if (playBilling == null) { + onUnavailable() + + return + } + + updateTrial { it.purchaseStarted() } + playBilling.buyPass(activity) { + endPurchase() + + onUnavailable() + } } fun destroy() { playBilling?.end() playBilling = null + billingTimeout.removeCallbacksAndMessages(null) + onEntitlementChanged = null + onTrialChanged = null } fun setEnabled(enabled: Boolean) { this.enabled = enabled } + + fun setTrialOffered(offered: Boolean) { + trialOffered = offered + } + + private companion object { + /** How long the intro waits for play's answer on owned purchases. */ + const val BILLING_TIMEOUT_MILLIS = 3_000L + } } diff --git a/app/src/main/java/app/opendocument/droid/nonfree/HouseAdTurn.kt b/app/src/main/java/app/opendocument/droid/nonfree/HouseAdTurn.kt new file mode 100644 index 000000000000..251f29fb989e --- /dev/null +++ b/app/src/main/java/app/opendocument/droid/nonfree/HouseAdTurn.kt @@ -0,0 +1,81 @@ +package app.opendocument.droid.nonfree + +/** + * Which documents start with the house ad, and how long its turn has left. The count of documents + * is kept by AdManager, and the clock is passed in. + */ +class HouseAdTurn(private val clock: () -> Long) { + + private var documentPending = false + + fun documentShown() { + documentPending = true + } + + fun documentClosed() { + documentPending = false + } + + /** Counts the current document once, even if it rendered before consent finished. */ + fun takeDocument(bannerAllowed: Boolean, paused: Boolean): Boolean { + if (!documentPending || !counts(bannerAllowed, paused)) return false + documentPending = false + return true + } + + /** When the running turn ends, or null. */ + private var endsAt: Long? = null + + /** What is left of a turn paused with the activity, or null. */ + private var pausedLeft: Long? = null + + /** While true, the house ad has the slot and no request goes to google. */ + val isRunning: Boolean + get() = endsAt != null || pausedLeft != null + + /** Takes the [opened]th counted document; true when it starts a turn of [LENGTH_MILLIS]. */ + fun documentOpened(opened: Int): Boolean { + if (opened % EVERY != 0) { + return false + } + + endsAt = clock() + LENGTH_MILLIS + pausedLeft = null + + return true + } + + fun pause() { + val endsAt = this.endsAt ?: return + + pausedLeft = (endsAt - clock()).coerceAtLeast(0) + this.endsAt = null + } + + /** The time left of a paused turn, to wait again; null without one. */ + fun resume(): Long? { + val left = pausedLeft ?: return null + + pausedLeft = null + endsAt = clock() + left + + return left + } + + fun end() { + endsAt = null + pausedLeft = null + } + + companion object { + + /** The house ad takes the first banner of every fifth document. */ + const val EVERY = 5 + + /** One banner's time, the rate the unit refreshes at. */ + const val LENGTH_MILLIS = 60_000L + + /** A document counts where consent lets a banner be asked for, and on screen. */ + fun counts(bannerAllowed: Boolean, paused: Boolean): Boolean = bannerAllowed && !paused + } +} diff --git a/app/src/main/java/app/opendocument/droid/nonfree/ProTrial.kt b/app/src/main/java/app/opendocument/droid/nonfree/ProTrial.kt new file mode 100644 index 000000000000..65673003eff8 --- /dev/null +++ b/app/src/main/java/app/opendocument/droid/nonfree/ProTrial.kt @@ -0,0 +1,192 @@ +package app.opendocument.droid.nonfree + +import kotlin.math.ceil + +/** + * Seven days of pro for every free install, once, from the launch that starts them. Only the + * decisions: [BillingManager] stores [Stored] and asks play, and the clock is passed in. The phase + * is read at launch and kept for the session, so the trial ends at the next launch rather than + * under an open document. + */ +class ProTrial(private val clock: () -> Long) { + + enum class Phase { + /** Not started, or answered: the app is what the entitlement says. */ + NONE, + + /** Pro tools on, no ads, no consent form. */ + RUNNING, + + /** Over, and the end screen not answered yet: Pro tools locked, still no ads. */ + ENDED, + } + + /** + * What the device keeps. [startedAt] is null before the trial has started. [ended] holds once + * the trial was seen over, so a clock set back cannot give it more days. + */ + data class Stored( + val startedAt: Long?, + val settled: Boolean, + val introShown: Boolean, + val ended: Boolean = false, + ) + + /** Where the trial stands in this session. */ + data class State( + val stored: Stored, + val phase: Phase, + val holdsPro: Boolean, + val adFree: Boolean, + /** Whether play has answered, or was waited for long enough. */ + val billingAnswered: Boolean, + /** Whether this launch started the trial. */ + val startedNow: Boolean, + /** + * From the tap on subscribe until play answers on it, and while the pass is pending: the + * end screen waits, so it does not come back to someone who paid. + */ + val purchaseInFlight: Boolean = false, + ) { + + /** No banner and no call to google. */ + val adsHeld: Boolean + get() = phase != Phase.NONE + + val unlocked: Boolean + get() = holdsPro || phase == Phase.RUNNING + + /** Not before play answered: a reinstall by a buyer would see it for nothing. */ + val introDue: Boolean + get() = phase == Phase.RUNNING && !holdsPro && !stored.introShown && billingAnswered + + val endDue: Boolean + get() = phase == Phase.ENDED && !holdsPro && !purchaseInFlight + + /** The intro or the end screen is due, or the intro waits for play: no review prompt. */ + val screenPending: Boolean + get() = endDue || (phase == Phase.RUNNING && !holdsPro && !stored.introShown) + + /** An old ad removal has no ads to choose, and closes the end screen instead. */ + val endShowsAdsButton: Boolean + get() = !adFree + + /** + * Pro answers the end screen too; the phase stays for the session. A pass that play holds + * as pending keeps the purchase in flight. + */ + fun billingAnswered(holdsPro: Boolean, adFree: Boolean, passPending: Boolean): State = + copy( + stored = if (holdsPro) stored.copy(settled = true) else stored, + holdsPro = holdsPro, + adFree = adFree, + billingAnswered = true, + purchaseInFlight = passPending, + ) + + fun purchaseStarted(): State = copy(purchaseInFlight = true) + + /** Cancelled, failed, or play could not be asked whether it went through. */ + fun purchaseEnded(): State = copy(purchaseInFlight = false) + + /** Play did not answer in time. Only the intro waits for it. */ + fun billingTimedOut(): State = copy(billingAnswered = true) + + fun introShown(): State = copy(stored = stored.copy(introShown = true)) + + /** The end screen is answered: ads, or close. */ + fun settled(): State = copy(stored = stored.copy(settled = true), phase = Phase.NONE) + } + + /** + * Starts the trial at the first eligible launch. A clock set back before the start of a running + * trial moves the start to now, so it cannot run longer than seven days from the correction. An + * ended trial stays ended. + */ + fun atLaunch(stored: Stored, sellsPass: Boolean, holdsPro: Boolean, adFree: Boolean): State { + val now = clock() + + var next = if (holdsPro) stored.copy(settled = true) else stored + var startedNow = false + + val startedAt = next.startedAt + if (startedAt == null) { + if (!next.settled && isEligible(sellsPass, holdsPro)) { + next = next.copy(startedAt = now) + startedNow = true + } + } else if (now < startedAt && !next.ended) { + next = next.copy(startedAt = now) + } + + val phase = phase(next, now) + if (phase == Phase.ENDED) { + next = next.copy(ended = true) + } + + return State( + stored = next, + phase = phase, + holdsPro = holdsPro, + adFree = adFree, + billingAnswered = false, + startedNow = startedNow, + ) + } + + /** + * Reads the phase again in a running process, where no document is open: a process can live for + * days, and the trial ends at the same moment as on ios. What is not running stays so. + */ + fun recheck(state: State): State { + if (state.phase != Phase.RUNNING) { + return state + } + + val now = clock() + + var stored = state.stored + val startedAt = stored.startedAt + if (startedAt != null && now < startedAt) { + stored = stored.copy(startedAt = now) + } + + val phase = phase(stored, now) + if (phase == Phase.ENDED) { + stored = stored.copy(ended = true) + } + + return state.copy(stored = stored, phase = phase) + } + + /** The days left, rounded up: 7 at the start and 1 during the last day, and after it. */ + fun daysLeft(startedAt: Long): Int { + val left = startedAt + LENGTH_MILLIS - clock() + + return ceil(left.toDouble() / DAY_MILLIS).toInt().coerceIn(1, DAYS) + } + + private fun phase(stored: Stored, now: Long): Phase { + val startedAt = stored.startedAt + + return when { + startedAt == null || stored.settled -> Phase.NONE + stored.ended -> Phase.ENDED + now - startedAt < LENGTH_MILLIS -> Phase.RUNNING + else -> Phase.ENDED + } + } + + companion object { + + const val DAYS = 7 + const val DAY_MILLIS = 24 * 60 * 60 * 1000L + const val LENGTH_MILLIS = DAYS * DAY_MILLIS + + /** + * Who gets the trial: a build that sells the pass, to someone who does not hold pro. An old + * ad removal without pro counts as free here. Every country. + */ + fun isEligible(sellsPass: Boolean, holdsPro: Boolean): Boolean = sellsPass && !holdsPro + } +} diff --git a/app/src/main/java/app/opendocument/droid/ui/activity/DocumentFragment.kt b/app/src/main/java/app/opendocument/droid/ui/activity/DocumentFragment.kt index b52bc99d3e64..cc844ac315b7 100644 --- a/app/src/main/java/app/opendocument/droid/ui/activity/DocumentFragment.kt +++ b/app/src/main/java/app/opendocument/droid/ui/activity/DocumentFragment.kt @@ -450,6 +450,12 @@ class DocumentFragment : Fragment(), DocumentLoader.Listener { if (isEditing()) { renderWhenEditEnds = true + // the trial's strip already works, and only its chip and dots are stale + val document = state.lastDocument + if (editingTools.showsTrial && document != null) { + showEditingTools(document, true) + } + return } @@ -473,15 +479,18 @@ class DocumentFragment : Fragment(), DocumentLoader.Listener { * there is no strip over it at all - undo, redo and save are the bar's. */ private fun showEditingTools(document: LoadedDocument, editing: Boolean) { + val trialDays = (activity as? MainActivity)?.trialDaysLeft() + when { !editing || !document.editing.isEditable -> editingTools.hide() document.editing == EditingKind.DOCUMENT || document.editing == EditingKind.SHEET -> editingTools.showFormatting( sheet = document.editing == EditingKind.SHEET, locked = !Features.advancedEditing, + trialDays = trialDays, ) document.editing == EditingKind.ANNOTATION -> - editingTools.showMarking(locked = !Features.advancedEditing) + editingTools.showMarking(locked = !Features.advancedEditing, trialDays = trialDays) else -> editingTools.hide() } } @@ -565,6 +574,14 @@ class DocumentFragment : Fragment(), DocumentLoader.Listener { } override fun onLocked() { + // the trial's badge, which leads to the purchase sheet like the other counters + val mainActivity = requireActivity() as MainActivity + if (mainActivity.trialDaysLeft() != null) { + mainActivity.offerPass(null) + + return + } + // bought during this edit: the tools unlock once the page is rendered again if (Features.advancedEditing) { showUnlockedEditing() @@ -839,14 +856,20 @@ class DocumentFragment : Fragment(), DocumentLoader.Listener { R.drawable.ic_menu_book, ) - // last, so the furthest from the thumb: lite's pass and foss's sponsors. pro has paid + // last, so the furthest from the thumb: lite's pass and foss's sponsors. pro has paid. + // during the trial it counts the days left + val mainActivity = requireActivity() as MainActivity + val trialDays = mainActivity.trialDaysLeft() val support = - if (!(requireActivity() as MainActivity).offersSupport()) null + if (!mainActivity.offersSupport()) null else DocumentActions.Action( DocumentActions.ACTION_SUPPORT, R.string.menu_support, R.drawable.ic_favorite, + trialDays?.let { + resources.getQuantityString(R.plurals.trial_counter, it, it) + }, ) // the order they unfold in, most wanted first - and what a reader reaches for mid-document @@ -1014,9 +1037,9 @@ class DocumentFragment : Fragment(), DocumentLoader.Listener { state.endLoadIdling() - // only a fresh open counts - reloadUri and the webview reach here mid-task. - // a save reloads through loadUri and so still counts, which is wanted. - // the ask itself waits for the document to be closed again, where nothing is pending + // only a fresh open counts - reloadUri, the webview and the reload after a save reach here + // with none pending. the ask itself waits for the document to be closed again, where + // nothing is pending if (freshOpenPending) { freshOpenPending = false @@ -1205,20 +1228,22 @@ class DocumentFragment : Fragment(), DocumentLoader.Listener { analyticsManager.report("network_permission_offer") // strings off the activity: giveUp() already detached this fragment - AlertDialog.Builder(activity) - .setTitle(R.string.dialog_network_denied_title) - .setMessage(R.string.dialog_network_denied) - .setPositiveButton(R.string.dialog_network_denied_settings) { _, _ -> - val intent = - Intent( - Settings.ACTION_APPLICATION_DETAILS_SETTINGS, - Uri.fromParts("package", activity.packageName, null), - ) - - activity.startActivity(intent) - } - .setNegativeButton(android.R.string.cancel, null) - .show() + val dialog = + AlertDialog.Builder(activity) + .setTitle(R.string.dialog_network_denied_title) + .setMessage(R.string.dialog_network_denied) + .setPositiveButton(R.string.dialog_network_denied_settings) { _, _ -> + val intent = + Intent( + Settings.ACTION_APPLICATION_DETAILS_SETTINGS, + Uri.fromParts("package", activity.packageName, null), + ) + + activity.startActivity(intent) + } + .setNegativeButton(android.R.string.cancel, null) + .show() + (activity as? MainActivity)?.holdTrialScreens(dialog) } private fun offerContact(activity: Activity) { @@ -1231,6 +1256,7 @@ class DocumentFragment : Fragment(), DocumentLoader.Listener { val view = LayoutInflater.from(builder.context).inflate(R.layout.dialog_broken_file, null) val dialog = builder.setTitle(R.string.dialog_broken_file_title).setView(view).show() + (activity as? MainActivity)?.holdTrialScreens(dialog) view.findViewById(R.id.dialog_broken_file_contact).setOnClickListener { contactSupport(activity) @@ -1554,6 +1580,9 @@ class DocumentFragment : Fragment(), DocumentLoader.Listener { return ::state.isInitialized && state.lastRequest != null } + /** Whether a document has rendered and is on screen. */ + fun isShowingDocument(): Boolean = ::state.isInitialized && state.lastDocument != null + /** Whether the document is in edit mode. */ fun isEditing(): Boolean = ::state.isInitialized && state.lastRequest?.editable == true diff --git a/app/src/main/java/app/opendocument/droid/ui/activity/LandingFragment.kt b/app/src/main/java/app/opendocument/droid/ui/activity/LandingFragment.kt index bf5df7a498ef..cac3080da93a 100644 --- a/app/src/main/java/app/opendocument/droid/ui/activity/LandingFragment.kt +++ b/app/src/main/java/app/opendocument/droid/ui/activity/LandingFragment.kt @@ -132,12 +132,17 @@ class LandingFragment : Fragment(), LandingAdapter.Listener { // lite's pass, or foss's sponsors, where it is seen without unfolding anything. asked here // rather than carried in the state: what billing knows lives on the activity, not in // anything the ViewModel reads, and the activity refreshes this once play has answered + // the same row counts the trial's days while it runs if (mainActivity.offersSupport()) { + val trialDays = mainActivity.trialDaysLeft() items.add( LandingItem.Action( LandingItem.ACTION_SUPPORT, - R.string.menu_support, + if (trialDays != null) R.string.trial_row else R.string.menu_support, R.drawable.ic_favorite, + trialDays?.let { + resources.getQuantityString(R.plurals.trial_days_left, it, it) + }, ) ) } diff --git a/app/src/main/java/app/opendocument/droid/ui/activity/MainActivity.kt b/app/src/main/java/app/opendocument/droid/ui/activity/MainActivity.kt index 84eea3d417c1..849bbba3bf4a 100644 --- a/app/src/main/java/app/opendocument/droid/ui/activity/MainActivity.kt +++ b/app/src/main/java/app/opendocument/droid/ui/activity/MainActivity.kt @@ -25,6 +25,7 @@ import androidx.core.view.ViewCompat import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat import androidx.core.view.WindowInsetsControllerCompat +import androidx.lifecycle.Lifecycle import androidx.lifecycle.ViewModelProvider import app.opendocument.droid.R import app.opendocument.droid.background.CatchAllSetting @@ -169,6 +170,18 @@ class MainActivity : AppCompatActivity() { // fetched while an externally opened document is read: back must not wait on the network private var preparedReview: InAppReview.Prepared? = null + /** The trial's start or end screen while it is up. */ + private var trialDialog: AlertDialog? = null + + /** A dialog the trial's screens wait for, such as why a document failed to open. */ + private var heldBy: android.app.Dialog? = null + + // set by "Support us with ads", and thanked for once the consent flow has settled + private var thankForAds = false + + // the end screen comes back on every resume until answered, and is counted once per launch + private var trialEndReported = false + /** * Loads and saves the open document. Scoped to the activity, so it survives a configuration * change and [DocumentFragment] finds it already there rather than waiting for a binding. @@ -440,12 +453,30 @@ class MainActivity : AppCompatActivity() { adManager.setAdContainer(adContainer) // the landing screen is drawn long before the consent update comes back, and the privacy // options row only exists once it has - adManager.setConsentListener { landingFragment?.refresh() } + adManager.setConsentListener { + landingFragment?.refresh() + + // also after the privacy options form, which may have been over a due screen + showTrialScreenIfDue() + + if (thankForAds) { + thankForAds = false + + SnackbarHelper.show( + this, + R.string.trial_ads_thanks, + null, + isIndefinite = false, + isError = false, + ) + } + } adManager.setPurchaseListener { offerPass(null) } adManager.initialize(this, analyticsManager, crashManager) billingManager = BillingManager() billingManager.setEnabled(adsAvailable) + billingManager.setTrialOffered(!IS_TESTING) // the support row goes once play reports a purchase, and the open document is rendered // again with the editing scope the pass brings billingManager.setEntitlementListener { unlocked, purchased -> @@ -455,7 +486,21 @@ class MainActivity : AppCompatActivity() { onUnlocked(purchased) } } + // the intro waits for play, and goes again if play says pro is held + billingManager.setTrialListener { + if (billingManager.isPro()) { + trialDialog?.dismiss() + } + + landingFragment?.refresh() + + showTrialScreenIfDue() + } billingManager.initialize(this, adManager, crashManager) + + if (billingManager.startedTrial()) { + analyticsManager.report("trial_started") + } } override fun onNewIntent(intent: Intent) { @@ -491,6 +536,12 @@ class MainActivity : AppCompatActivity() { } private fun loadUri(uri: Uri, openedExternally: Boolean) { + adManager.onDocumentClosed() + // the new document is rendered with the trial's phase as it stands now + if (documentFragment?.isEditing() != true) { + recheckTrial() + } + documentOpenedExternally = openedExternally lastSaveUri = null @@ -742,6 +793,9 @@ class MainActivity : AppCompatActivity() { currentActionMode = null ttsActionMode = null editActionMode = null + + // what waited for the edit or the reading to end; posted, as the fragment hears of it too + handler.post { showTrialScreenIfDue() } } // and the framework ones, which is what selecting text in the page raises @@ -772,6 +826,147 @@ class MainActivity : AppCompatActivity() { else -> true } + /** Reads the trial's phase again, never under an open document; the counters follow. */ + private fun recheckTrial() { + if (!::billingManager.isInitialized) { + return + } + + billingManager.recheckTrial() + landingFragment?.refresh() + } + + /** Keeps the trial's screens back while [dialog] is up, and checks for them once it closes. */ + fun holdTrialScreens(dialog: android.app.Dialog) { + heldBy = dialog + + dialog.setOnDismissListener { + if (heldBy === dialog) { + heldBy = null + } + + showTrialScreenIfDue() + } + } + + /** The pro trial's days left while it runs, rounded up; null otherwise. */ + fun trialDaysLeft(): Int? = + if (::billingManager.isInitialized) billingManager.trialDaysLeft() else null + + /** + * The trial's screens: the start once, and the end until one of its answers is picked - also + * after "Pay once" or a purchase that did not go through, when the user comes back. Over a + * document only once it has rendered, and never in the edit mode. + */ + private fun showTrialScreenIfDue() { + if ( + trialDialog != null || + heldBy?.isShowing == true || + isFinishing || + isDestroyed || + !::billingManager.isInitialized || + !lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED) + ) { + return + } + + val documentFragment = this.documentFragment + if ( + loadOnStart != null || + ttsActionMode != null || + (documentFragment != null && + (!documentFragment.isShowingDocument() || documentFragment.isEditing())) + ) { + return + } + + when { + billingManager.isTrialIntroDue() -> showTrialIntro() + billingManager.isTrialEndDue() -> showTrialEnd() + } + } + + private fun showTrialIntro() { + val message = + listOf( + R.string.trial_start_body, + R.string.trial_start_after, + R.string.trial_privacy, + ) + .joinToString("\n\n") { getString(it) } + + trialDialog = + AlertDialog.Builder(this) + .setTitle(R.string.trial_start_title) + .setMessage(message) + .setPositiveButton(R.string.trial_got_it, null) + // back and a tap outside close it too + .setOnDismissListener { + trialDialog = null + + billingManager.setTrialIntroShown() + } + .show() + } + + /** + * The purchase sheet once the trial is over, with "Support us with ads" in place of "Not now". + * It is not cancelable, and returns until an answer is picked. An old ad removal has no ads to + * choose, and closes it instead. + */ + private fun showTrialEnd() { + if (!trialEndReported) { + trialEndReported = true + + analyticsManager.report("trial_end_shown") + } + + val offersAds = billingManager.trialEndOffersAds() + + val view = layoutInflater.inflate(R.layout.dialog_pass, null) + val lead = view.findViewById(R.id.pass_lead) + lead.setText(R.string.trial_end_body) + lead.visibility = View.VISIBLE + view.findViewById(R.id.pass_why).visibility = View.GONE + view.findViewById(R.id.pass_privacy).visibility = View.VISIBLE + + val builder = + AlertDialog.Builder(this) + .setTitle(R.string.trial_end_title) + .setView(view) + .setCancelable(false) + .setOnDismissListener { trialDialog = null } + if (!offersAds) { + builder.setNegativeButton(R.string.trial_end_close) { _, _ -> + analyticsManager.report("trial_end_closed") + + billingManager.settleTrial() + landingFragment?.refresh() + } + } + + val dialog = builder.show() + trialDialog = dialog + + bindPassButtons(view, dialog, null) + + if (offersAds) { + val adsButton = view.findViewById(R.id.pass_ads) + adsButton.visibility = View.VISIBLE + view.findViewById(R.id.pass_ads_note).visibility = View.VISIBLE + + adsButton.setOnClickListener { + analyticsManager.report("trial_chose_ads") + + thankForAds = true + billingManager.chooseAds() + + dialog.dismiss() + landingFragment?.refresh() + } + } + } + /** The pass in lite, the sponsors anywhere else. */ fun offerSupport() { if (Features.withAds) { @@ -795,16 +990,27 @@ class MainActivity : AppCompatActivity() { } /** The pro app's listing: the way to pay once, and the edition without the ads sdk. */ - fun openProListing() { + /** Whether the listing opened: a device can have nothing that takes the link. */ + fun openProListing(): Boolean { analyticsManager.report(AnalyticsConstants.EVENT_ADD_TO_CART) // the play listing id is the applicationId, not the renamed java package - startActivity( - Intent( - Intent.ACTION_VIEW, - Uri.parse("https://play.google.com/store/apps/details?id=at.tomtasche.reader.pro"), + return try { + startActivity( + Intent( + Intent.ACTION_VIEW, + Uri.parse( + "https://play.google.com/store/apps/details?id=at.tomtasche.reader.pro" + ), + ) ) - ) + + true + } catch (e: ActivityNotFoundException) { + crashManager.log(e) + + false + } } /** @@ -821,21 +1027,46 @@ class MainActivity : AppCompatActivity() { val view = layoutInflater.inflate(R.layout.dialog_pass, null) val featureView = view.findViewById(R.id.pass_feature) - val buyButton = view.findViewById