diff --git a/.gitignore b/.gitignore index 430eb6a..4dc7cd1 100644 --- a/.gitignore +++ b/.gitignore @@ -27,3 +27,4 @@ platforms/**/bundle/ **/Config.xcconfig platforms/ios/**/*.xcuserstate platforms/ios/**/xcuserdata/ +/docs/reviews/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 06a4510..6a24337 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Change Log +## Unreleased + +* Ad-free pass redemption is discontinued; previously earned time remains valid until expiry. The `system.redeemReward` wrapper and native action have been removed. Plugins using that action must stop offering redemption. Internal pass-offer helpers and the `isWatchingRewardedAd` export were also removed. + ## v1.13.5 * fix(terminal): stop proot "can't sanitize binding" fd warnings by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2878 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index dc61ab2..106db87 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -247,12 +247,24 @@ implementation. Version, build number and display name are synced from services work without a distribution certificate. The target includes `platforms/ios/ads`, Google Mobile Ads/UMP and advertising -metadata. Debug builds use Google's iOS test units. Release builds require -`ACODE_IOS_ADMOB_APP_ID`, `ACODE_IOS_ADMOB_BANNER_ID`, -`ACODE_IOS_ADMOB_INTERSTITIAL_ID` and `ACODE_IOS_ADMOB_REWARDED_ID`. -See [iOS advertising](docs/ios-advertising.md) for consent testing, source provenance -and validation limits. Run the normal script before building `runner` in Xcode; -it prepares `.ios-build/App-Info.plist` and the matching web bundle. +metadata. `ads.json` supplies ad-unit IDs through the web build configuration; +`dev/scripts/iosAds.js` separately writes the app ID and advertising metadata into +`.ios-build/App-Info.plist`. Run the normal script before building `runner` in Xcode +to prepare both the plist and web bundle. The adapted AdMob Plus code retains its +MIT notice in `platforms/ios/ads/AdMobPlus-LICENSE.txt`. + +The app gathers UMP consent, then native startup waits for ATT to settle before +starting Mobile Ads; consent is checked again before startup and ad requests. +ATT waits are bounded to 30 seconds. A timeout fails startup without granting +authorization; retry/foreground checks read the OS status, and cancellation never +starts a second prompt while the original OS request is outstanding. +On physical Release builds, a verified StoreKit sandbox/Xcode environment selects +Google demo units. A failed, unverified or timed-out lookup keeps the configured +units; the lookup deadline is three seconds. Verified environments are cached for +the process; failed/unverified lookups retry after a 30-second cooldown, and +concurrent lookups share one request. Debug/simulator selection comes from +the build configuration and SDK test-device behavior. Simulator tests do not +establish TestFlight/App Review environment selection or production ad fill. The icon picker uses UIKit alternate icons and the existing reward/Pro gates. `runner.icon` and the fifteen alternate app-icon sets use Acode's existing @@ -264,6 +276,10 @@ iPhone and iPad. It uses the local StoreKit Pro fixture to unlock the picker. Native tests cover packaged icons and the bridge; shared tests cover reward and purchase gates. +Calling `Bridge.setup()` again intentionally invalidates callbacks from the old +navigation and resets its services before rebuilding them for the supplied WebView. +Normal page navigation calls `reset()` and reuses the same WebView and services. + The `System` file utilities retain Android's result shapes, newline semantics and nonrecursive deletion while restricting paths to the sandbox or granted Files folders. Reward-pass state uses Keychain. Android file-edit intents and launcher diff --git a/ads.json b/ads.json index 5fca1f2..63aeb1b 100644 --- a/ads.json +++ b/ads.json @@ -5,8 +5,6 @@ "banner": "ca-app-pub-5911839694379275/9157899592", "interstitial": "ca-app-pub-5911839694379275/9570937608", "rewarded": "ca-app-pub-5911839694379275/1633667633", - "academyRewarded": "ca-app-pub-5911839694379275/3893763807", - "academyInterstitial": "ca-app-pub-5911839694379275/7819275372", "appOpen": "ca-app-pub-5911839694379275/4600740197" }, "test": { @@ -14,8 +12,6 @@ "banner": "ca-app-pub-3940256099942544/6300978111", "interstitial": "ca-app-pub-3940256099942544/1033173712", "rewarded": "ca-app-pub-3940256099942544/5224354917", - "academyRewarded": "ca-app-pub-3940256099942544/5224354917", - "academyInterstitial": "ca-app-pub-3940256099942544/1033173712", "appOpen": "ca-app-pub-3940256099942544/9257395921" } }, @@ -25,8 +21,6 @@ "banner": "ca-app-pub-5911839694379275/7672969208", "interstitial": "ca-app-pub-5911839694379275/8054492011", "rewarded": "ca-app-pub-5911839694379275/4550361278", - "academyRewarded": "ca-app-pub-5911839694379275/4716873072", - "academyInterstitial": "ca-app-pub-5911839694379275/5428328674", "appOpen": "ca-app-pub-5911839694379275/4115247005" }, "test": { @@ -34,8 +28,6 @@ "banner": "ca-app-pub-3940256099942544/2435281174", "interstitial": "ca-app-pub-3940256099942544/4411468910", "rewarded": "ca-app-pub-3940256099942544/1712485313", - "academyRewarded": "ca-app-pub-3940256099942544/1712485313", - "academyInterstitial": "ca-app-pub-3940256099942544/4411468910", "appOpen": "ca-app-pub-3940256099942544/5575463023" } } diff --git a/dev/config.js b/dev/config.js index 41fb71f..d9593f8 100755 --- a/dev/config.js +++ b/dev/config.js @@ -15,8 +15,6 @@ function getAdConfig(platform, mode) { "banner", "interstitial", "rewarded", - "academyRewarded", - "academyInterstitial", "appOpen", ]) { const id = config[name]; diff --git a/docs/ios-advertising.md b/docs/ios-advertising.md deleted file mode 100644 index ad7f092..0000000 --- a/docs/ios-advertising.md +++ /dev/null @@ -1,128 +0,0 @@ -# iOS advertising - -iOS has one free app, built with the `runner` target and scheme using the bundle -ID from `package.json.appleAppId`. It links Google Mobile Ads 13.10.0 and User -Messaging Platform 3.1.0 through Swift Package Manager. The iOS native and web -builds always include the free implementation, regardless of the Android edition -in `package.json.androidPackageId`. - -`platforms/ios/ads` adapts the original AdMob Plus iOS format implementations and -native-ad XIB from [admob-plus](https://github.com/admob-plus/admob-plus) at commit -`16e5768bda7244e8d35334a62caa5dbcadd70c9a` (the `cordova` and `cordova-native` -packages). Its MIT notice is retained in `AdMobPlus-LICENSE.txt`. The WebView ad -registration follows the upstream `cordova-webview-ad` implementation; its bridge -methods retain Acode's Android adapter contract. Native classes are regular Xcode -sources; there is no plugin installation, native code generation or copying hook. - -The port replaces the command/callback transport and global plugin registry with -the existing iOS bridge. It retains banner, interstitial, rewarded, rewarded -interstitial, app-open and native formats, server-side reward options, request -configuration, event names and IDs. Paid impression events use the same payload -as Android. Banner layout reserves space in the editor's existing wrapper and -accounts for safe areas and the keyboard without reparenting the WebView. -The shared request builder supplies the presenting window's `UIWindowScene`, as -recommended by Google's [iPad window guide](https://developers.google.com/admob/ios/multiscene), -so the SDK receives the app window's sizing context for every ad format. - -Pending loads are invalidated on replacement, destroy and WebView reload. Native -views, delegates and paid-event handlers are released. Fullscreen presentation is -limited to one ad in a foreground app; reward values are captured before -presentation so dismissal cannot lose the reward callback. The SDK integration -page opens in a separate sheet with no app native bridge. - -The existing JavaScript consent coordinator uses UMP's current-session state. -Native initialization, loads and presentation require `canRequestAds`; no stored -boolean substitutes for UMP. Consent forms are loaded separately from presentation -so a form loaded for an old WebView cannot appear after reload. Privacy options -remain accessible through the shared settings entry. Consent reset and geography -overrides are limited to debug builds. ATT is requested only by an explicit API -call or an IDFA message configured in UMP. - -Reward passes retain Android's rules: Quick grants one hour; Focus grants four, -five or six hours, with three redemptions per local calendar day and at most ten -hours remaining. Native state lives in the existing `ads` Keychain namespace. -Tests cover midnight resets, stacking and clipping, expiry notification delivery, -persisted state and malformed-state recovery. The shared rewarded-ad gate accepts -iOS; it still enforces the existing Android SDK minimum on Android. - -## Configuration - -Debug builds use Google's published [iOS test ad units](https://developers.google.com/admob/ios/test-ads) -and sample app ID. Set `ACODE_IOS_ADMOB_APP_ID` to a configured iOS app ID to test -that app's consent messages; debug ad units remain Google's test units. - -Release builds require all four environment variables: - -- `ACODE_IOS_ADMOB_APP_ID` -- `ACODE_IOS_ADMOB_BANNER_ID` -- `ACODE_IOS_ADMOB_INTERSTITIAL_ID` -- `ACODE_IOS_ADMOB_REWARDED_ID` - -The release script rejects missing, malformed and Google demo IDs. Use iOS IDs; -Android ad-unit IDs are not a substitute. No production IDs are committed. -`dev/scripts/iosAds.js` creates `.ios-build/App-Info.plist` from the shared app -metadata and adds the SDK keys. `dev/ios/skadnetwork.json` is the -50-entry list from Google's [setup guide](https://developers.google.com/admob/ios/quick-start), -retrieved on 2026-09-23. Refresh it when updating the SDK. Run the normal build -script before building `runner` directly in Xcode so its metadata and web -bundle match the build mode. - -The deprecated anchored banner size helpers and legacy child-directed/under-age -request fields are retained to preserve the existing public API's dimensions and -separate option semantics. Switching to the newer large banners or combined age -policy would be a behavior change. - -## Validation boundaries - -Automated simulator checks use actual SDK classes with network loads replaced only in the -banner layout fixture. They cover advertising inclusion, the app identity, API dispatch, consent gating, -load invalidation, callback isolation, paid-impression format/currency payloads, -stacking/hiding/destroying banners, native -XIB loading and fullscreen ownership. Shared tests cover iOS ID selection, -unchanged Android behavior, initialization retries and release configuration. -A scene regression failed for all six native formats before the shared request -builder supplied the presenting scene; all six AdMob bridge tests pass with it. - -A sample UMP form was observed in the simulator. The regression test bootstrap -suppresses automatic consent gathering so unrelated tests do not depend on network -dialogs; direct bridge calls still test the native consent gate. This fixture is -only in the test bundle and does not modify normal app launches or stored Pro status. -A normal free-edition launch on iOS 18.6 also displayed the system ATT prompt. -Choosing Ask App Not to Track left an incoming Files document editable and savable. - -A normal free-app launch on the iPad iOS 18.6 simulator also loaded Google's -adaptive banner and rewarded test creatives, visibly labelled Test mode. The -Settings banner stayed inside Acode's Split View area, hid when the software -keyboard opened, returned after dismissal and adapted to portrait rotation. -The Quick pass flow showed Reward granted in the SDK creative; dismissing it -changed the app from no active pass and 0/3 redemptions to one hour remaining and -1/3 redemptions. Returning to Settings suppressed its previously visible banner. -This used the normal app UI and published Google test units, without consent or -ad-load mocks. Further banner checks must account for any active rewarded pass. - -A temporary manual bridge harness also loaded Google's interstitial test unit on -iOS 18.6. On the iPad in Split View, closing the SDK's Test mode screen delivered -`load`, `show`, `impression` and `dismiss` in order. The active editor document, -unsaved state, WebView frame and stored reward pass were unchanged; the native -fullscreen owner and loaded ad were released. Native consent gathering and ad -loading were real. The harness called the public ad API directly, so this does -not establish normal app interstitial eligibility during an ad-free pass. - -The iPad's landscape Split View creative area was intermittently black, both -before and after the scene correction. Subsequent portrait and landscape runs -rendered the full test image and passed manual dismissal with editor content, -layout and reward state preserved. In the final landscape run, the SDK's -`canPresent` preflight accepted the window and its ad WebView matched the app's -991-by-1032-point window. This does not establish the cause of the intermittent -black creative. Google's window guide still documents portrait-only support for -Split View ads; physical-device validation remains necessary. - -The same test unit rendered the full Google test image on the iPhone simulator. -Its manual dismissal check timed out because the desktop UI tool could not -reliably target the close control; it is not a passing iPhone dismissal test. -The temporary presentation and rendering harnesses were removed from the suite. - -These checks do not prove production ad delivery or revenue, account-configured -consent forms, mediation adapters or physical-device presentation. Production -AdMob configuration, broader consent/ATT variants and physical-device ad layout -during keyboard changes, rotation and fullscreen remain unverified. diff --git a/docs/ios-port.md b/docs/ios-port.md index 9d326fc..851c8b3 100644 --- a/docs/ios-port.md +++ b/docs/ios-port.md @@ -105,9 +105,7 @@ translation checks. Later focused native checks are recorded below. StoreKit coverage uses local simulated transactions; it does not verify production products or the purchase backend. Advertising checks verify the free bridge, consent gating, load cancellation, banner layout and paid-impression payloads; -the paid app excludes the SDK classes, resources and metadata. See -[iOS advertising](ios-advertising.md) for source provenance, configuration and -remaining live/device checks. +the paid app excludes the SDK classes, resources and metadata. The simulator suite currently exercises editor startup, safe-area layout, reading, editing and saving files, watching coordinated writes, worker loading, incoming @@ -407,8 +405,8 @@ and cache clearing are supported; clearing the WebView cache keeps app storage. All sixteen existing app icons are packaged for iPhone and iPad, including Acode's default artwork. UIKit changes the launcher icon in place. The shared picker retains reward/Pro requirements and persistence, and omits Android's app-exit -warning on iOS. Reward passes retain the one-hour Quick offer, random four-to-six -hour Focus offer, three-per-day limit and ten-hour cap, with native Keychain state. +warning on iOS. New ad-free passes are discontinued. Existing earned time remains +active until its stored expiry, with native Keychain state preserved. Native tests verify packaged icon metadata and actual DOM hit targets after startup. A paid-edition UI test changes and restores the icon through Settings, acknowledging Apple's confirmation. An iOS-only centering rule keeps WebKit's @@ -584,9 +582,9 @@ reproduced the missing scene for all six native formats, and all six AdMob bridg tests pass with the correction. Live portrait and landscape Split View checks displayed the full interstitial test image and passed dismissal, though other landscape runs had an unexplained black creative. The iPhone rendered the full -test image, but its dismissal check timed out after desktop UI targeting failures. See -[iOS advertising](ios-advertising.md) for the distinction between these test-ad -checks and production delivery, consent variants and physical-device validation. +test image, but its dismissal check timed out after desktop UI targeting failures. +These test-ad checks do not establish production delivery, consent variants or +physical-device behavior. ## Remaining native work diff --git a/package.json b/package.json index 22b2072..e482adf 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "acode-app", "displayName": "Acode", "version": "1.13.6", - "versionCode": 1022, + "versionCode": 1023, "androidPackageId": "com.foxdebug.acode", "appleAppId": "app.acode", "description": "Powerful code editor and terminal for IOS and Android", diff --git a/platforms/android/app/src/free/java/app/acode/ads/AdMob.kt b/platforms/android/app/src/free/java/app/acode/ads/AdMob.kt index 8ff5b62..03553e2 100644 --- a/platforms/android/app/src/free/java/app/acode/ads/AdMob.kt +++ b/platforms/android/app/src/free/java/app/acode/ads/AdMob.kt @@ -49,6 +49,7 @@ class AdMob : Service() { Actions.AD_IS_LOADED to ::executeAdIsLoaded, Actions.AD_LOAD to ::executeAdLoad, Actions.AD_SHOW to ::executeAdShow, + Actions.AD_RECOVER_PRESENTATION to ::executeAdRecoverPresentation, Actions.AD_HIDE to ::executeAdHide, Actions.PRIVACY_GATHER_CONSENT to privacy::gatherConsent, Actions.PRIVACY_GET_STATE to privacy::getState, @@ -177,6 +178,11 @@ class AdMob : Service() { } } + private fun executeAdRecoverPresentation(ctx: ExecuteContext) { + val id = ctx.optId() ?: return ctx.reject("id is required") + activity.runOnUiThread { ctx.resolve(recoverAdPresentation(activity, id)) } + } + private fun executeAdHide(ctx: ExecuteContext) { host!!.activity.runOnUiThread { ctx.optAdOrReject()?.hide(ctx) diff --git a/platforms/android/app/src/free/java/app/acode/ads/AdRecovery.kt b/platforms/android/app/src/free/java/app/acode/ads/AdRecovery.kt new file mode 100644 index 0000000..16f2d75 --- /dev/null +++ b/platforms/android/app/src/free/java/app/acode/ads/AdRecovery.kt @@ -0,0 +1,18 @@ +package app.acode.ads + +import android.app.Activity +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleOwner +import app.acode.ads.ads.Rewarded + +internal fun recoverAdPresentation(activity: Activity, id: String): Boolean { + val lifecycle = (activity as? LifecycleOwner)?.lifecycle ?: return false + if (!lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED) || + !activity.hasWindowFocus() || activity.isFinishing || activity.isDestroyed + ) return false + // AdActivity (or an external ad destination) must no longer own the foreground. + val ad = ads[id] ?: return true + if (ad !is Rewarded) return false + ad.onDestroy() + return true +} diff --git a/platforms/android/app/src/free/java/app/acode/ads/Generated.kt b/platforms/android/app/src/free/java/app/acode/ads/Generated.kt index f815589..e8b6143 100644 --- a/platforms/android/app/src/free/java/app/acode/ads/Generated.kt +++ b/platforms/android/app/src/free/java/app/acode/ads/Generated.kt @@ -1,4 +1,4 @@ -// THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +// AdMob Plus protocol constants, maintained locally for Acode bridge extensions. package app.acode.ads object Actions { @@ -8,6 +8,7 @@ object Actions { const val AD_IS_LOADED = "adIsLoaded" const val AD_LOAD = "adLoad" const val AD_SHOW = "adShow" + const val AD_RECOVER_PRESENTATION = "adRecoverPresentation" const val BANNER_CONFIG = "bannerConfig" const val CONFIGURE = "configure" const val PRIVACY_GATHER_CONSENT = "privacyGatherConsent" diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/system/RewardPassManager.java b/platforms/android/app/src/main/java/com/foxdebug/acode/system/RewardPassManager.java index bbd4b1a..fc45f4d 100644 --- a/platforms/android/app/src/main/java/com/foxdebug/acode/system/RewardPassManager.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/system/RewardPassManager.java @@ -6,7 +6,6 @@ import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; -import java.util.Random; import org.json.JSONException; import org.json.JSONObject; @@ -19,62 +18,25 @@ public class RewardPassManager { private static final int MAX_REDEMPTIONS_PER_DAY = 3; private final EncryptedPreferenceManager adsPrefManager; - private final Random random = new Random(); public RewardPassManager(Context context) { this.adsPrefManager = new EncryptedPreferenceManager(context, ADS_PREFS_FILENAME); } public String getRewardStatus() throws JSONException { - JSONObject state = syncRewardState(loadRewardState()); + String previous = adsPrefManager.getString(KEY_REWARD_STATE, ""); + JSONObject state = syncRewardState(loadRewardState(previous)); JSONObject status = buildRewardStatus(state); if (status.optBoolean("hasPendingExpiryNotice")) { state.put("expiryNoticePendingUntil", 0L); } - saveRewardState(state); + if (!RewardPassStorage.isUnchanged(previous, state)) saveRewardState(state); return status.toString(); } - public String redeemReward(String offerId) throws JSONException { - JSONObject state = syncRewardState(loadRewardState()); - int redemptionsToday = state.optInt("redemptionsToday", 0); - long now = java.lang.System.currentTimeMillis(); - long adFreeUntil = state.optLong("adFreeUntil", 0L); - long remainingMs = Math.max(0L, adFreeUntil - now); - - if (redemptionsToday >= MAX_REDEMPTIONS_PER_DAY) { - throw new JSONException( - "Daily limit reached. You can redeem up to " + MAX_REDEMPTIONS_PER_DAY + " rewards per day." - ); - } - - if (remainingMs >= MAX_ACTIVE_PASS_MS) { - throw new JSONException("You already have the maximum 10 hours of ad-free time active."); - } - - long grantedDurationMs = resolveRewardDuration(offerId); - long baseTime = Math.max(now, adFreeUntil); - long newAdFreeUntil = Math.min(baseTime + grantedDurationMs, now + MAX_ACTIVE_PASS_MS); - long appliedDurationMs = Math.max(0L, newAdFreeUntil - baseTime); - - state.put("adFreeUntil", newAdFreeUntil); - state.put("lastExpiredRewardUntil", 0L); - state.put("expiryNoticePendingUntil", 0L); - state.put("redemptionDay", getTodayKey()); - state.put("redemptionsToday", redemptionsToday + 1); - saveRewardState(state); - - JSONObject status = buildRewardStatus(state); - status.put("grantedDurationMs", grantedDurationMs); - status.put("appliedDurationMs", appliedDurationMs); - status.put("offerId", offerId); - return status.toString(); - } - - private JSONObject loadRewardState() { - String raw = adsPrefManager.getString(KEY_REWARD_STATE, ""); + private JSONObject loadRewardState(String raw) { if (raw == null || raw.isEmpty()) { return defaultRewardState(); } @@ -156,33 +118,11 @@ private JSONObject buildRewardStatus(JSONObject state) throws JSONException { status.put("hasPendingExpiryNotice", state.optLong("expiryNoticePendingUntil", 0L) > 0L); status.put("expiryNoticePendingUntil", state.optLong("expiryNoticePendingUntil", 0L)); - boolean canRedeem = remainingRedemptions > 0 && remainingMs < MAX_ACTIVE_PASS_MS; - status.put("canRedeem", canRedeem); - status.put("redeemDisabledReason", getRedeemDisabledReason(remainingRedemptions, remainingMs)); + status.put("canRedeem", false); + status.put("redeemDisabledReason", "Ad-free passes are no longer available."); return status; } - private String getRedeemDisabledReason(int remainingRedemptions, long remainingMs) { - if (remainingRedemptions <= 0) { - return "Daily limit reached. You can redeem up to " + MAX_REDEMPTIONS_PER_DAY + " rewards per day."; - } - if (remainingMs >= MAX_ACTIVE_PASS_MS) { - return "You already have the maximum 10 hours of ad-free time active."; - } - return ""; - } - - private long resolveRewardDuration(String offerId) throws JSONException { - if ("quick".equals(offerId)) { - return ONE_HOUR_MS; - } - if ("focus".equals(offerId)) { - int selectedHours = 4 + random.nextInt(3); - return selectedHours * ONE_HOUR_MS; - } - throw new JSONException("Unknown reward offer."); - } - private String getTodayKey() { return new SimpleDateFormat("yyyy-MM-dd", Locale.US).format(new Date()); } diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/system/RewardPassStorage.kt b/platforms/android/app/src/main/java/com/foxdebug/acode/system/RewardPassStorage.kt new file mode 100644 index 0000000..01d7050 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/system/RewardPassStorage.kt @@ -0,0 +1,22 @@ +package com.foxdebug.acode.system + +import org.json.JSONException +import org.json.JSONObject + +internal object RewardPassStorage { + @JvmStatic + fun isUnchanged(raw: String?, state: JSONObject): Boolean { + if (raw.isNullOrEmpty()) return false + return try { + val previous = JSONObject(raw) + previous.length() == state.length() && state.keys().asSequence().all { key -> + val old = previous.opt(key) + val new = state.get(key) + if (old is Number && new is Number) old.toString() == new.toString() + else old == new + } + } catch (error: JSONException) { + false + } + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/system/System.java b/platforms/android/app/src/main/java/com/foxdebug/acode/system/System.java index 06cf847..4eec1bd 100644 --- a/platforms/android/app/src/main/java/com/foxdebug/acode/system/System.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/system/System.java @@ -289,11 +289,6 @@ public void run() { case "getRewardStatus": callbackContext.success(rewardPassManager.getRewardStatus()); return true; - case "redeemReward": - callbackContext.success( - rewardPassManager.redeemReward(args.getString(0)) - ); - return true; case "getParentPath": callbackContext.success(getParentPath(args.getString(0))); return true; diff --git a/platforms/android/app/src/test/java/com/foxdebug/acode/system/RewardPassManagerTest.kt b/platforms/android/app/src/test/java/com/foxdebug/acode/system/RewardPassManagerTest.kt new file mode 100644 index 0000000..963b77c --- /dev/null +++ b/platforms/android/app/src/test/java/com/foxdebug/acode/system/RewardPassManagerTest.kt @@ -0,0 +1,60 @@ +package com.foxdebug.acode.system + +import com.foxdebug.acode.auth.EncryptedPreferenceManager +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(manifest = Config.NONE, sdk = [28]) +class RewardPassManagerTest { + @Test + fun unchangedStatusPreservesJsonFormattingAndKeyOrder() { + val context = RuntimeEnvironment.getApplication() + val store = EncryptedPreferenceManager(context, "ads") + val today = java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.US).format(java.util.Date()) + val raw = """{ "redemptionsToday": 2, "redemptionDay": "$today", + "expiryNoticePendingUntil": 0, "lastExpiredRewardUntil": 0, "adFreeUntil": 0 }""" + try { + store.setString("reward_state", raw) + RewardPassManager(context).getRewardStatus() + assertEquals(raw, store.getString("reward_state", "")) + assertFalse(RewardPassStorage.isUnchanged("invalid", JSONObject())) + assertFalse(RewardPassStorage.isUnchanged("{}", JSONObject().put("adFreeUntil", 0L))) + } finally { + store.clear() + } + } + + @Test + fun existingTimeSurvivesAndExpiryIsReportedOnceWithoutNewRedemptions() { + val context = RuntimeEnvironment.getApplication() + val store = EncryptedPreferenceManager(context, "ads") + try { + val expiry = java.lang.System.currentTimeMillis() + 3_600_000 + store.setString("reward_state", JSONObject().put("adFreeUntil", expiry).toString()) + val active = JSONObject(RewardPassManager(context).getRewardStatus()) + assertTrue(active.getBoolean("isActive")) + assertFalse(active.getBoolean("canRedeem")) + assertEquals(expiry, active.getLong("adFreeUntil")) + + val pastExpiry = java.lang.System.currentTimeMillis() - 1 + store.setString("reward_state", JSONObject().put("adFreeUntil", pastExpiry).toString()) + val rewards = RewardPassManager(context) + val expired = JSONObject(rewards.getRewardStatus()) + assertFalse(expired.getBoolean("isActive")) + assertFalse(expired.getBoolean("canRedeem")) + assertTrue(expired.getBoolean("hasPendingExpiryNotice")) + assertEquals(pastExpiry, expired.getLong("expiryNoticePendingUntil")) + assertFalse(JSONObject(rewards.getRewardStatus()).getBoolean("hasPendingExpiryNotice")) + } finally { + store.clear() + } + } +} diff --git a/platforms/android/app/src/testFree/java/app/acode/ads/AdRecoveryTest.kt b/platforms/android/app/src/testFree/java/app/acode/ads/AdRecoveryTest.kt new file mode 100644 index 0000000..2320542 --- /dev/null +++ b/platforms/android/app/src/testFree/java/app/acode/ads/AdRecoveryTest.kt @@ -0,0 +1,38 @@ +package app.acode.ads + +import androidx.activity.ComponentActivity +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(manifest = Config.NONE, sdk = [28]) +class AdRecoveryTest { + @Test + fun missingAdIsRecoverableOnlyWhenTheHostHasResumedAndRegainedFocus() { + val controller = Robolectric.buildActivity(RecoveryActivity::class.java).setup() + val activity = controller.get() + try { + assertFalse(recoverAdPresentation(activity, "removed-ad")) + activity.focused = true + assertTrue(recoverAdPresentation(activity, "removed-ad")) + controller.pause() + assertFalse(recoverAdPresentation(activity, "removed-ad")) + controller.resume() + assertTrue(recoverAdPresentation(activity, "removed-ad")) + activity.finish() + assertFalse(recoverAdPresentation(activity, "removed-ad")) + } finally { + controller.pause().stop().destroy() + } + } + + class RecoveryActivity : ComponentActivity() { + var focused = false + override fun hasWindowFocus(): Boolean = focused + } +} diff --git a/platforms/ios/Alpine/build.sh b/platforms/ios/Alpine/build.sh index e026434..8183e0d 100755 --- a/platforms/ios/Alpine/build.sh +++ b/platforms/ios/Alpine/build.sh @@ -20,7 +20,7 @@ if [[ "${ARCHS:-arm64}" != arm64 ]]; then exit 1 fi -crossfile="$build_dir/cross.ini" +crossfile="$build_dir.cross.ini" cat > "$crossfile.tmp" < AMBAdEnvironment { + #if DEBUG || targetEnvironment(simulator) + // Debug and simulator installs have no App Store app transaction. + return AMBAdEnvironment(verifiedEnvironment: nil) + #else + return await cache.current { + if case .verified(let transaction) = try await AppTransaction.shared { + return transaction.environment + } + return nil + } + #endif + } + + @MainActor + static func resolve(timeout: Duration = .seconds(3), + lookup: @escaping () async throws -> AppStore.Environment?) async -> AMBAdEnvironment { + // A task group would still wait for a StoreKit operation that ignores cancellation. + await withCheckedContinuation { continuation in + var pending: CheckedContinuation? = continuation + var deadline: Task? + let request = Task { @MainActor in + let environment = try? await lookup() + guard let completion = pending else { return } + pending = nil + deadline?.cancel() + completion.resume(returning: AMBAdEnvironment(verifiedEnvironment: environment)) + } + deadline = Task { @MainActor in + do { try await Task.sleep(for: timeout) } + catch { return } + guard let completion = pending else { return } + pending = nil + request.cancel() + completion.resume(returning: AMBAdEnvironment(verifiedEnvironment: nil)) + } + } + } + + func unitID(for format: String, configured: String) -> String { + guard verifiedEnvironment == .sandbox || verifiedEnvironment == .xcode else { return configured } + // Google's demo units are used only in Apple's verified testing environments. + let suffix: String + switch format { + case "appOpen": suffix = "5575463023" + case "banner": suffix = "2435281174" + case "interstitial": suffix = "4411468910" + case "rewarded": suffix = "1712485313" + case "rewardedInterstitial": suffix = "6978759866" + case "native": suffix = "3986624511" + default: return configured + } + return "ca-app-pub-3940256099942544/" + suffix + } +} + +@MainActor +final class AMBAdEnvironmentCache { + private var verified: AMBAdEnvironment? + private var pending: Task? + private var retryAfter: ContinuousClock.Instant? + private let now: () -> ContinuousClock.Instant + + init(now: @escaping () -> ContinuousClock.Instant = { .now }) { self.now = now } + + func current(lookup: @escaping () async throws -> AppStore.Environment?) async -> AMBAdEnvironment { + if let verified { return verified } + if let pending { return await pending.value } + if let retryAfter, now() < retryAfter { return AMBAdEnvironment(verifiedEnvironment: nil) } + let request = Task { await AMBAdEnvironment.resolve(lookup: lookup) } + pending = request + let result = await request.value + pending = nil + if result.verifiedEnvironment != nil { verified = result } + else { retryAfter = now().advanced(by: .seconds(30)) } + return result + } +} diff --git a/platforms/ios/ads/AMBContext.swift b/platforms/ios/ads/AMBContext.swift index c55e291..0bd73d5 100644 --- a/platforms/ios/ads/AMBContext.swift +++ b/platforms/ios/ads/AMBContext.swift @@ -94,6 +94,7 @@ final class AMBContext: AMBCoreContext { let maxHeight = adSizeDict["maxHeight"] as? CGFloat { return inlineAdaptiveBanner(width: width, maxHeight: maxHeight) } else { + // Keep the compact anchored size; the newer large helpers increase editor insets. switch adSizeDict["orientation"] as? String { case "portrait": return portraitAnchoredAdaptiveBanner(width: width) diff --git a/platforms/ios/ads/AMBCore.swift b/platforms/ios/ads/AMBCore.swift index 67809f2..4b36acf 100644 --- a/platforms/ios/ads/AMBCore.swift +++ b/platforms/ios/ads/AMBCore.swift @@ -122,6 +122,7 @@ extension AMBCoreContext { reject(error.localizedDescription) } + @MainActor func configure() { if let muted = optAppMuted() { MobileAds.shared.isApplicationMuted = muted @@ -134,12 +135,7 @@ extension AMBCoreContext { if let maxAdContentRating = optGADMaxAdContentRating() { requestConfiguration.maxAdContentRating = maxAdContentRating } - if let tag = optChildDirectedTreatmentTag() { - requestConfiguration.tagForChildDirectedTreatment = NSNumber(value: tag) - } - if let tag = optUnderAgeOfConsentTag() { - requestConfiguration.tagForUnderAgeOfConsent = NSNumber(value: tag) - } + plugin?.configureAgeTreatment(childDirected: optChildDirectedTreatmentTag(), underAgeOfConsent: optUnderAgeOfConsentTag()) if let testDevices = optTestDeviceIds() { requestConfiguration.testDeviceIdentifiers = testDevices } diff --git a/platforms/ios/ads/AMBFullScreen.swift b/platforms/ios/ads/AMBFullScreen.swift index 1178aec..e3f86e9 100644 --- a/platforms/ios/ads/AMBFullScreen.swift +++ b/platforms/ios/ads/AMBFullScreen.swift @@ -18,6 +18,14 @@ class AMBFullScreen: AMBAdBase, FullScreenContentDelegate { return controller } + @MainActor + func recoverPresentation() -> Bool { + guard isActive, plugin?.canRecoverPresentation == true else { return false } + // The JS dismissal event may have been lost even when the SDK cleared presenting. + didFinishPresentation() + return true + } + func clear() {} override func destroy() { diff --git a/platforms/ios/ads/AMBPlugin.swift b/platforms/ios/ads/AMBPlugin.swift index e2a9860..aa93db6 100644 --- a/platforms/ios/ads/AMBPlugin.swift +++ b/platforms/ios/ads/AMBPlugin.swift @@ -11,6 +11,10 @@ final class AMBPlugin: BaseService { private var events: [[String: Any]] = [] private var starting: [AMBContext] = [] private var started = false + private var childDirected = false + private var underAgeOfConsent = false + @MainActor private lazy var tracking = AMBTrackingAuthorization() + private(set) var adEnvironment = AMBAdEnvironment(verifiedEnvironment: nil) private weak var registeredWebView: WKWebView? lazy var banners = AMBBannerLayout(plugin: self) lazy var privacy = AMBPrivacy(plugin: self) @@ -31,9 +35,34 @@ final class AMBPlugin: BaseService { readyCallback = nil events.removeAll() generation = UUID() + tracking.cancel() } } + @MainActor + func configureAgeTreatment(childDirected: Bool?, underAgeOfConsent: Bool?) { + guard childDirected != nil || underAgeOfConsent != nil else { return } + if let childDirected { self.childDirected = childDirected } + if let underAgeOfConsent { self.underAgeOfConsent = underAgeOfConsent } + MobileAds.shared.requestConfiguration.ageRestrictedTreatment = self.childDirected || self.underAgeOfConsent ? .child : .unspecified + } + + @MainActor + var canRecoverPresentation: Bool { + guard UIApplication.shared.applicationState == .active, + let controller = viewController, + controller.view.window?.windowScene?.activationState == .foregroundActive, + controller.presentedViewController == nil, + controller.transitionCoordinator == nil else { return false } + return true + } + + @MainActor + func recoverPresentation(_ id: String) -> Bool { + guard let ad = ads[id] else { return canRecoverPresentation } + return (ad as? AMBFullScreen)?.recoverPresentation() ?? false + } + func clearAds() { for ad in ads.values { ad.destroy() } ads.removeAll() @@ -47,6 +76,7 @@ final class AMBPlugin: BaseService { else if events.count < 100 { events.append(payload) } } + @MainActor private func execute(_ action: String, _ ctx: AMBContext) { switch action { case "ready": @@ -68,8 +98,11 @@ final class AMBPlugin: BaseService { MobileAds.shared.applicationVolume = volume ctx.resolve() case "requestTrackingAuthorization": - ATTrackingManager.requestTrackingAuthorization { status in - DispatchQueue.main.async { ctx.resolve(status.rawValue) } + tracking.authorize { result in + switch result { + case .success(let status): ctx.resolve(status.rawValue) + case .failure(let error): ctx.reject(error) + } } case "privacyGetState": ctx.resolve(privacy.state) case "privacyGatherConsent": privacy.gather(ctx) @@ -84,10 +117,14 @@ final class AMBPlugin: BaseService { if let ad = ctx.optAdOrError() { ctx.resolve(ad.isLoaded()) } case "adLoad", "adShow": guard privacy.canRequestAds else { ctx.reject("Gather ad consent before requesting ads"); return } + guard started else { ctx.reject("Initialize ads before requesting ads"); return } guard let ad = ctx.optAdOrError() else { return } if action == "adLoad" { ad.load(ctx) } else if ad is AMBBanner || ad.isLoaded() { ad.show(ctx) } else { ctx.resolve(false) } + case "adRecoverPresentation": + guard let id = ctx.optId() else { ctx.reject("id is required"); return } + ctx.resolve(recoverPresentation(id)) case "adHide": ctx.optAdOrError()?.hide(ctx) case "bannerConfig": banners.configure(ctx) case "webviewGoto": @@ -106,24 +143,51 @@ final class AMBPlugin: BaseService { } } + @MainActor private func start(_ ctx: AMBContext) { guard privacy.canRequestAds else { ctx.reject("Gather ad consent before requesting ads"); return } if started { ctx.resolve(["version": string(for: MobileAds.shared.versionNumber)]); return } starting.append(ctx) guard starting.count == 1 else { return } let token = generation - MobileAds.shared.start { [weak self] _ in - DispatchQueue.main.async { - guard let self, self.generation == token else { return } - self.started = true - if let webView = self.webView, self.registeredWebView !== webView { - MobileAds.shared.register(webView) - self.registeredWebView = webView - } + tracking.authorize { [weak self] result in + guard let self, self.generation == token else { return } + if case .failure(let error) = result { let pending = self.starting self.starting.removeAll() - for request in pending { request.resolve(["version": string(for: MobileAds.shared.versionNumber)]) } + pending.forEach { $0.reject(error) } + return } + Task { @MainActor [weak self] in + let environment = await AMBAdEnvironment.current() + guard let self, self.generation == token else { return } + guard self.privacy.canRequestAds else { + let pending = self.starting + self.starting.removeAll() + pending.forEach { $0.reject("Gather ad consent before requesting ads") } + return + } + self.adEnvironment = environment + self.startSDK(token) + } + } + } + + @MainActor + private func startSDK(_ token: UUID) { + let didStart: @MainActor @Sendable () -> Void = { [weak self] in + guard let self, self.generation == token else { return } + self.started = true + if let webView = self.webView, self.registeredWebView !== webView { + MobileAds.shared.register(webView) + self.registeredWebView = webView + } + let pending = self.starting + self.starting.removeAll() + for request in pending { request.resolve(["version": string(for: MobileAds.shared.versionNumber)]) } + } + MobileAds.shared.start { _ in + DispatchQueue.main.async(execute: didStart) } } diff --git a/platforms/ios/ads/AMBPrivacy.swift b/platforms/ios/ads/AMBPrivacy.swift index 1dccda2..96b24dc 100644 --- a/platforms/ios/ads/AMBPrivacy.swift +++ b/platforms/ios/ads/AMBPrivacy.swift @@ -5,9 +5,12 @@ final class AMBPrivacy { private weak var plugin: AMBPlugin? private var busy = false private var presenting = false - private let information = ConsentInformation.shared + private let information: ConsentInformation - init(plugin: AMBPlugin) { self.plugin = plugin } + init(plugin: AMBPlugin, information: ConsentInformation = .shared) { + self.plugin = plugin + self.information = information + } var canRequestAds: Bool { information.canRequestAds } var state: [String: Any] { diff --git a/platforms/ios/ads/AMBTrackingAuthorization.swift b/platforms/ios/ads/AMBTrackingAuthorization.swift new file mode 100644 index 0000000..b590589 --- /dev/null +++ b/platforms/ios/ads/AMBTrackingAuthorization.swift @@ -0,0 +1,94 @@ +import AppTrackingTransparency +import UIKit + +@MainActor +final class AMBTrackingAuthorization { + typealias Completion = (Result) -> Void + private let status: @MainActor () -> ATTrackingManager.AuthorizationStatus + private let isActive: @MainActor () -> Bool + private let request: (@escaping @Sendable (ATTrackingManager.AuthorizationStatus) -> Void) -> Void + private let notifications: NotificationCenter + private var observer: NSObjectProtocol? + private var pending: [Completion] = [] + private var requestID: UUID? + private var deadline: Task? + private let timeout: Duration + + init(status: @escaping @MainActor () -> ATTrackingManager.AuthorizationStatus = { ATTrackingManager.trackingAuthorizationStatus }, + isActive: @escaping @MainActor () -> Bool = { UIApplication.shared.applicationState == .active }, + notifications: NotificationCenter = .default, + timeout: Duration = .seconds(30), + request: @escaping (@escaping @Sendable (ATTrackingManager.AuthorizationStatus) -> Void) -> Void = ATTrackingManager.requestTrackingAuthorization) { + self.status = status + self.isActive = isActive + self.notifications = notifications + self.timeout = timeout + self.request = request + observer = notifications.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main) { [weak self] _ in + DispatchQueue.main.async { self?.requestWhenActive() } + } + } + + deinit { + deadline?.cancel() + if let observer { notifications.removeObserver(observer) } + } + + func authorize(_ completion: @escaping Completion) { + pending.append(completion) + if deadline == nil { + deadline = Task { [weak self, timeout] in + do { try await Task.sleep(for: timeout) } + catch { return } + guard !Task.isCancelled, let self, !self.pending.isEmpty else { return } + if !self.finishIfDecided() { + self.finish(.failure(NSError(domain: "AcodeAds", code: 3, + userInfo: [NSLocalizedDescriptionKey: "Tracking authorization is still pending. Please try again."]))) + } + } + } + requestWhenActive() + } + + func cancel() { + finish(.failure(NSError(domain: "AcodeAds", code: 1, + userInfo: [NSLocalizedDescriptionKey: "Tracking authorization was cancelled"]))) + } + + private func requestWhenActive() { + guard !pending.isEmpty, !finishIfDecided(), requestID == nil, isActive() else { return } + let id = UUID() + requestID = id + request { [weak self] status in + DispatchQueue.main.async { + guard let self, self.requestID == id else { return } + self.requestID = nil + if self.finishIfDecided() { return } + if status != .notDetermined { self.finish(.success(status)) } + else if self.isActive() { + self.finish(.failure(NSError(domain: "AcodeAds", code: 2, + userInfo: [NSLocalizedDescriptionKey: "Tracking authorization could not be presented. Please try again."]))) + } + // An inactive app cannot display ATT. Retry on didBecomeActive. + } + } + } + + private func finishIfDecided() -> Bool { + let current = status() + guard current != .notDetermined else { return false } + requestID = nil + finish(.success(current)) + return true + } + + private func finish(_ result: Result) { + deadline?.cancel() + deadline = nil + // Cancellation/timeout settles callers, not the OS request. Its ID remains + // until a callback or a determined OS status proves it is safe to retire. + let callbacks = pending + pending.removeAll() + callbacks.forEach { $0(result) } + } +} diff --git a/platforms/ios/runner.xcodeproj/project.pbxproj b/platforms/ios/runner.xcodeproj/project.pbxproj index 92fd058..4c35357 100644 --- a/platforms/ios/runner.xcodeproj/project.pbxproj +++ b/platforms/ios/runner.xcodeproj/project.pbxproj @@ -375,7 +375,7 @@ CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; - CURRENT_PROJECT_VERSION = 1022; + CURRENT_PROJECT_VERSION = 1023; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; @@ -443,7 +443,7 @@ CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; - CURRENT_PROJECT_VERSION = 1022; + CURRENT_PROJECT_VERSION = 1023; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; diff --git a/platforms/ios/runner/Bridge.swift b/platforms/ios/runner/Bridge.swift index 9e40f97..8d71084 100644 --- a/platforms/ios/runner/Bridge.swift +++ b/platforms/ios/runner/Bridge.swift @@ -6,8 +6,11 @@ final class Bridge: NSObject, WKScriptMessageHandler { private var services: [String: ServiceProtocol] = [:] private var serviceQueues: [String: DispatchQueue] = [:] private var navigationID = UUID() + private(set) lazy var shareService = ShareService(bridge: self) func setup(webView: WKWebView, viewController: WebViewController) { + if !services.isEmpty { reset() } + _ = shareService self.webView = webView self.viewController = viewController services = [ @@ -82,6 +85,7 @@ final class Bridge: NSObject, WKScriptMessageHandler { func reset() { navigationID = UUID() + shareService.reset() for (name, service) in services { serviceQueues[name]?.async { service.reset() } } } } diff --git a/platforms/ios/runner/lib/NativeService.swift b/platforms/ios/runner/lib/NativeService.swift index fad31dd..252f768 100644 --- a/platforms/ios/runner/lib/NativeService.swift +++ b/platforms/ios/runner/lib/NativeService.swift @@ -50,13 +50,13 @@ final class NativeService: BaseService { // MARK: - shareFile / shareText private func shareFile(args: [Any], callback: Callback) { - guard let bridge else { callback.error("Native bridge unavailable"); return } - ShareService(bridge: bridge).exec(action: "shareFile", args: args, callback: callback) + guard let share = bridge?.shareService else { callback.error("Native bridge unavailable"); return } + share.exec(action: "shareFile", args: args, callback: callback) } private func shareText(args: [Any], callback: Callback) { - guard let bridge else { callback.error("Native bridge unavailable"); return } - ShareService(bridge: bridge).exec(action: "shareText", args: args, callback: callback) + guard let share = bridge?.shareService else { callback.error("Native bridge unavailable"); return } + share.exec(action: "shareText", args: args, callback: callback) } // MARK: - getAppInfo diff --git a/platforms/ios/runner/lib/PlatformServices.swift b/platforms/ios/runner/lib/PlatformServices.swift index 8d56452..b702197 100644 --- a/platforms/ios/runner/lib/PlatformServices.swift +++ b/platforms/ios/runner/lib/PlatformServices.swift @@ -9,13 +9,15 @@ final class BuildInfoService: BaseService { let name = info["CFBundleDisplayName"] as? String ?? "Acode" #if DEBUG let debug = true + let buildType = "debug" #else let debug = false + let buildType = "release" #endif let flavor = "free" callback.success(["packageName": id, "basePackageName": id, "displayName": name, "name": name, "version": info["CFBundleShortVersionString"] as? String ?? "", "versionCode": Int(info["CFBundleVersion"] as? String ?? "0") ?? 0, - "debug": debug, "buildType": debug ? "debug" : "release", "flavor": flavor]) + "debug": debug, "buildType": buildType, "flavor": flavor]) } } @@ -34,9 +36,9 @@ final class ClipboardService: BaseService { final class AppService: BaseService { override func exec(action: String, args: [Any], callback: Callback) { - DispatchQueue.main.async { [weak self] in + DispatchQueue.main.async { [self] in switch action { - case "backHistory": self?.webView?.goBack(); callback.success() + case "backHistory": self.webView?.goBack(); callback.success() case "clearCache", "clear-cache": WKWebsiteDataStore.default().removeData(ofTypes: [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache], modifiedSince: .distantPast) { callback.success(action == "clear-cache" ? "Cache cleared" : nil) diff --git a/platforms/ios/runner/lib/RewardPassManager.swift b/platforms/ios/runner/lib/RewardPassManager.swift index 0345965..583ca77 100644 --- a/platforms/ios/runner/lib/RewardPassManager.swift +++ b/platforms/ios/runner/lib/RewardPassManager.swift @@ -1,62 +1,34 @@ import Foundation -// Port of Android's System/RewardPassManager; the public state and reward rules stay identical. +// Preserves earned passes from before new redemptions were discontinued. final class RewardPassManager { private static let hour: Int64 = 60 * 60 * 1000 private static let maximumDuration = 10 * hour private static let maximumRedemptions = 3 private let store: SecretStore private let now: () -> Date - private let focusHours: () -> Int - init(store: SecretStore = SecretStore(namespace: "ads"), now: @escaping () -> Date = Date.init, - focusHours: @escaping () -> Int = { Int.random(in: 4...6) }) { + init(store: SecretStore = SecretStore(namespace: "ads"), now: @escaping () -> Date = Date.init) { self.store = store self.now = now - self.focusHours = focusHours } func getRewardStatus() throws -> String { let date = now() - var state = try synchronizedState(date) + let raw = try store.get("reward_state") + let values = (try? JSONSerialization.jsonObject(with: Data(raw.utf8))) as? [String: Any] ?? [:] + var state = synchronizedState(values, date: date) let status = status(state, date: date) state.expiryNoticePendingUntil = 0 - try save(state) + try save(state, previous: values) return try json(status) } - func redeemReward(_ offerID: String) throws -> String { - let date = now() - let time = milliseconds(date) - var state = try synchronizedState(date) - let reason = disabledReason(state, time: time) - guard reason.isEmpty else { throw SecretFailure(reason) } - let duration: Int64 - switch offerID { - case "quick": duration = Self.hour - case "focus": duration = Int64(focusHours()) * Self.hour - default: throw SecretFailure("Unknown reward offer.") - } - let baseTime = max(time, state.adFreeUntil) - state.adFreeUntil = min(baseTime + duration, time + Self.maximumDuration) - state.lastExpiredRewardUntil = 0 - state.expiryNoticePendingUntil = 0 - state.redemptionDay = day(date) - state.redemptionsToday += 1 - try save(state) - var result = status(state, date: date) - result["grantedDurationMs"] = duration - result["appliedDurationMs"] = max(0, state.adFreeUntil - baseTime) - result["offerId"] = offerID - return try json(result) - } - - private func synchronizedState(_ date: Date) throws -> RewardPassState { - let raw = try store.get("reward_state") - let values = (try? JSONSerialization.jsonObject(with: Data(raw.utf8))) as? [String: Any] ?? [:] - var state = RewardPassState(values, today: day(date)) - if state.redemptionDay != day(date) { - state.redemptionDay = day(date) + private func synchronizedState(_ values: [String: Any], date: Date) -> RewardPassState { + let today = day(date) + var state = RewardPassState(values, today: today) + if state.redemptionDay != today { + state.redemptionDay = today state.redemptionsToday = 0 } if state.adFreeUntil > 0, state.adFreeUntil <= milliseconds(date) { @@ -69,7 +41,6 @@ final class RewardPassManager { private func status(_ state: RewardPassState, date: Date) -> [String: Any] { let time = milliseconds(date) - let reason = disabledReason(state, time: time) return ["adFreeUntil": state.adFreeUntil, "lastExpiredRewardUntil": state.lastExpiredRewardUntil, "isActive": state.adFreeUntil > time, "remainingMs": max(0, state.adFreeUntil - time), "redemptionsToday": state.redemptionsToday, @@ -77,25 +48,18 @@ final class RewardPassManager { "maxRedemptionsPerDay": Self.maximumRedemptions, "maxActivePassMs": Self.maximumDuration, "hasPendingExpiryNotice": state.expiryNoticePendingUntil > 0, "expiryNoticePendingUntil": state.expiryNoticePendingUntil, - "canRedeem": reason.isEmpty, "redeemDisabledReason": reason] + "canRedeem": false, "redeemDisabledReason": "Ad-free passes are no longer available."] } - private func disabledReason(_ state: RewardPassState, time: Int64) -> String { - if state.redemptionsToday >= Self.maximumRedemptions { - return "Daily limit reached. You can redeem up to 3 rewards per day." - } - if state.adFreeUntil - time >= Self.maximumDuration { - return "You already have the maximum 10 hours of ad-free time active." - } - return "" - } - - private func save(_ state: RewardPassState) throws { - try store.set("reward_state", value: json([ + private func save(_ state: RewardPassState, previous: [String: Any]) throws { + let values: [String: Any] = [ "adFreeUntil": state.adFreeUntil, "lastExpiredRewardUntil": state.lastExpiredRewardUntil, "expiryNoticePendingUntil": state.expiryNoticePendingUntil, "redemptionDay": state.redemptionDay, "redemptionsToday": state.redemptionsToday, - ])) + ] + if !NSDictionary(dictionary: values).isEqual(to: previous) { + try store.set("reward_state", value: json(values)) + } } private func json(_ value: [String: Any]) throws -> String { @@ -105,12 +69,10 @@ final class RewardPassManager { private func milliseconds(_ date: Date) -> Int64 { Int64(date.timeIntervalSince1970 * 1000) } private func day(_ date: Date) -> String { - let formatter = DateFormatter() - formatter.locale = Locale(identifier: "en_US_POSIX") - formatter.calendar = Calendar(identifier: .gregorian) - formatter.timeZone = .current - formatter.dateFormat = "yyyy-MM-dd" - return formatter.string(from: date) + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = .current + return String(format: "%04d-%02d-%02d", calendar.component(.year, from: date), + calendar.component(.month, from: date), calendar.component(.day, from: date)) } } diff --git a/platforms/ios/runner/lib/SystemService.swift b/platforms/ios/runner/lib/SystemService.swift index 3e29dff..aadf9a7 100644 --- a/platforms/ios/runner/lib/SystemService.swift +++ b/platforms/ios/runner/lib/SystemService.swift @@ -9,13 +9,11 @@ final class SystemService: BaseService { private let rewards = RewardPassManager() private lazy var browser = SafariService(bridge: bridge!) private lazy var preview = BrowserService(bridge: bridge!) - private lazy var share = ShareService(bridge: bridge!) override func reset() { streams.reset() browser.reset() preview.reset() - share.reset() DispatchQueue.main.async { [weak self] in IncomingLinks.shared.reset() self?.viewController?.fullscreen.setActive(false) @@ -36,7 +34,6 @@ final class SystemService: BaseService { callback.success(text) case "getInstaller": callback.success("appstore") case "getRewardStatus": callback.success(try rewards.getRewardStatus()) - case "redeemReward": callback.success(try rewards.redeemReward(args[safe: 0] as? String ?? "")) case "get-android-version": callback.success(0) case "get-configuration": DispatchQueue.main.async { [weak self] in callback.success(self?.viewController?.systemConfiguration ?? [:]) } @@ -50,12 +47,15 @@ final class SystemService: BaseService { #else callback.success("x86_64") #endif - case "shareText": share.exec(action: action, args: args, callback: callback) + case "shareText": + guard let share = bridge?.shareService else { callback.error("Native bridge unavailable"); return } + share.exec(action: action, args: args, callback: callback) case "file-action": let intent = args[safe: 2] as? String ?? "android.intent.action.VIEW" guard ["android.intent.action.VIEW", "android.intent.action.SEND"].contains(intent) else { callback.error(["code": "UNSUPPORTED_ACTION", "message": "File intent \(intent) is unavailable on iOS"]); return } + guard let share = bridge?.shareService else { callback.error("Native bridge unavailable"); return } share.exec(action: "shareFile", args: args, callback: callback) case "open-in-browser": browser.exec(action: "external", args: args, callback: callback) case "in-app-browser": preview.exec(action: action, args: args, callback: callback) diff --git a/platforms/ios/runner/lib/network/AppAPIHandler.swift b/platforms/ios/runner/lib/network/AppAPIHandler.swift index 64850cf..fa3dd39 100644 --- a/platforms/ios/runner/lib/network/AppAPIHandler.swift +++ b/platforms/ios/runner/lib/network/AppAPIHandler.swift @@ -24,7 +24,7 @@ final class AppAPIHandler { Self.storeCookies(from: response, credentials: credentials) try Self.applyCookies(to: &next, credentials: credentials, auth: auth) } - transport.onResponse = { response in + transport.onResponse = { [weak self] response in Self.storeCookies(from: response, credentials: credentials) if redirects == "error", (300..<400).contains(response.statusCode) { throw URLError(.redirectToNonExistentLocation) } var headers: [String: String] = [:] @@ -37,8 +37,8 @@ final class AppAPIHandler { let result = HTTPURLResponse(url: source, statusCode: response.statusCode, httpVersion: "HTTP/1.1", headerFields: headers)! DispatchQueue.main.async { [weak self] in if self?.requests[id] != nil { task.didReceive(result) } } } - transport.onData = { data in DispatchQueue.main.async { [weak self] in if self?.requests[id] != nil { task.didReceive(data) } } } - transport.onComplete = { error in + transport.onData = { [weak self] data in DispatchQueue.main.async { [weak self] in if self?.requests[id] != nil { task.didReceive(data) } } } + transport.onComplete = { [weak self] error in DispatchQueue.main.async { [weak self] in guard self?.requests.removeValue(forKey: id) != nil else { return } if let error { task.didFailWithError(error) } diff --git a/platforms/ios/runner/lib/network/HTTPStreamService.swift b/platforms/ios/runner/lib/network/HTTPStreamService.swift index 241bac2..cb0548c 100644 --- a/platforms/ios/runner/lib/network/HTTPStreamService.swift +++ b/platforms/ios/runner/lib/network/HTTPStreamService.swift @@ -12,7 +12,7 @@ final class HTTPStreamService { } func exec(action: String, args: [Any], callback: Callback) { - queue.async { + queue.async { [self] in let id = args[safe: 0] as? String ?? "" do { switch action { diff --git a/platforms/ios/runner/lib/network/NativeHTTPService.swift b/platforms/ios/runner/lib/network/NativeHTTPService.swift index 83df688..7429374 100644 --- a/platforms/ios/runner/lib/network/NativeHTTPService.swift +++ b/platforms/ios/runner/lib/network/NativeHTTPService.swift @@ -14,7 +14,7 @@ final class NativeHTTPService: BaseService { } override func exec(action: String, args: [Any], callback: Callback) { - queue.async { + queue.async { [self] in do { switch action { case "setServerTrustMode": diff --git a/platforms/ios/runner/lib/network/WebSocketService.swift b/platforms/ios/runner/lib/network/WebSocketService.swift index 9d6a7bb..cce70e6 100644 --- a/platforms/ios/runner/lib/network/WebSocketService.swift +++ b/platforms/ios/runner/lib/network/WebSocketService.swift @@ -12,7 +12,7 @@ final class WebSocketService: BaseService { } override func exec(action: String, args: [Any], callback: Callback) { - queue.async { + queue.async { [self] in do { if action == "connect" { let id = UUID().uuidString diff --git a/platforms/ios/runner/lib/preview/PluginWebViewService.swift b/platforms/ios/runner/lib/preview/PluginWebViewService.swift index 570d059..a0de642 100644 --- a/platforms/ios/runner/lib/preview/PluginWebViewService.swift +++ b/platforms/ios/runner/lib/preview/PluginWebViewService.swift @@ -13,7 +13,7 @@ final class PluginWebViewService: BaseService { } override func exec(action: String, args: [Any], callback: Callback) { - DispatchQueue.main.async { + DispatchQueue.main.async { [self] in if action == "setMessageCallback" { self.messageCallback?.release(); self.messageCallback = callback; return } diff --git a/platforms/ios/runner/lib/preview/ServerService.swift b/platforms/ios/runner/lib/preview/ServerService.swift index fc5eb97..92775e3 100644 --- a/platforms/ios/runner/lib/preview/ServerService.swift +++ b/platforms/ios/runner/lib/preview/ServerService.swift @@ -29,7 +29,7 @@ final class ServerService: BaseService { } override func exec(action: String, args: [Any], callback: Callback) { - queue.async { + queue.async { [self] in guard let port = args[safe: 0] as? Int, (1...65535).contains(port) else { callback.error("Invalid server port"); return } do { switch action { diff --git a/platforms/ios/runner/lib/security/AuthenticatorService.swift b/platforms/ios/runner/lib/security/AuthenticatorService.swift index f804868..ce6c509 100644 --- a/platforms/ios/runner/lib/security/AuthenticatorService.swift +++ b/platforms/ios/runner/lib/security/AuthenticatorService.swift @@ -6,7 +6,7 @@ final class AuthenticatorService: BaseService { required init(bridge: Bridge) { super.init(bridge: bridge) - DispatchQueue.main.async { + DispatchQueue.main.async { [self] in self.coordinator = SignInCoordinator(bridge: bridge) IncomingLinks.shared.authenticationHandler = { [weak self] in self?.coordinator.receive($0) } } diff --git a/platforms/ios/runner/lib/ssh/SFTPConnections.swift b/platforms/ios/runner/lib/ssh/SFTPConnections.swift index d06fbae..82fb6ab 100644 --- a/platforms/ios/runner/lib/ssh/SFTPConnections.swift +++ b/platforms/ios/runner/lib/ssh/SFTPConnections.swift @@ -16,17 +16,17 @@ extension SFTPService { let currentGeneration = generation attempts[requestID] = attempt let timeout = shell ? 10 : min(30, max(1, (args[safe: 2] as? Double ?? 10000) / 1000)) - DispatchQueue.global(qos: .userInitiated).async { + DispatchQueue.global(qos: .userInitiated).async { [self] in do { let connection = try SSHConnection(cancellation: attempt.cancellation) - try connection.connect(profile, timeout: timeout) { key, algorithm in - try self.profiles.verify(endpoint: profile.endpoint, key: key, algorithm: algorithm) { fingerprint in + try connection.connect(profile, timeout: timeout) { [self] key, algorithm in + try self.profiles.verify(endpoint: profile.endpoint, key: key, algorithm: algorithm) { [self] fingerprint in try SSHPrompts.confirm(title: "Unknown SSH host", message: "This is the first connection to \(profile.endpoint).\n\nKey type: \(algorithm)\nFingerprint: \(fingerprint)\n\nVerify this fingerprint before trusting the host.", button: "Trust and connect", presenter: { [weak self] in self?.viewController }, cancellation: attempt.cancellation) } } if shell { let terminal = try SSHShell(connection: connection, columns: SSHShell.dimension(args[safe: 1], default: 80), rows: SSHShell.dimension(args[safe: 2], default: 24), callback: callback) - self.control.async { + self.control.async { [self, terminal] in self.attempts.removeValue(forKey: requestID) guard (try? attempt.cancellation.check()) != nil else { terminal.close(); return } terminal.onClose = { [weak self, weak terminal] in diff --git a/platforms/ios/runner/lib/ssh/SFTPService.swift b/platforms/ios/runner/lib/ssh/SFTPService.swift index 3eedbe7..690268a 100644 --- a/platforms/ios/runner/lib/ssh/SFTPService.swift +++ b/platforms/ios/runner/lib/ssh/SFTPService.swift @@ -80,7 +80,7 @@ final class SFTPService: BaseService { let attempt = SSHAttempt(callback: callback, shell: true) let requestID = UUID().uuidString attempts[requestID] = attempt - DispatchQueue.global(qos: .userInitiated).async { + DispatchQueue.global(qos: .userInitiated).async { [self] in defer { self.control.async { self.attempts.removeValue(forKey: requestID) } } do { guard try SSHPrompts.confirm(title: "Delete saved SSH credentials?", message: "Remove the encrypted SFTP/SSH profile for \(profile.username)@\(profile.hostname)?", button: "Delete", destructive: true, presenter: { [weak self] in self?.viewController }, cancellation: attempt.cancellation) else { diff --git a/platforms/ios/runner/lib/ssh/SSHShell.swift b/platforms/ios/runner/lib/ssh/SSHShell.swift index 9dfb1bf..66a71bd 100644 --- a/platforms/ios/runner/lib/ssh/SSHShell.swift +++ b/platforms/ios/runner/lib/ssh/SSHShell.swift @@ -20,7 +20,7 @@ final class SSHShell { } func start() { - queue.async { + queue.async { [self] in self.callback.success(["type": "ready", "sessionId": self.id], keep: true) let timer = DispatchSource.makeTimerSource(queue: self.queue) timer.schedule(deadline: .now(), repeating: .milliseconds(20)) diff --git a/platforms/ios/runner/lib/terminal/TerminalServer.swift b/platforms/ios/runner/lib/terminal/TerminalServer.swift index 85843ac..4be77b1 100644 --- a/platforms/ios/runner/lib/terminal/TerminalServer.swift +++ b/platforms/ios/runner/lib/terminal/TerminalServer.swift @@ -104,7 +104,7 @@ final class TerminalServer { runtime.queue.async { [self] in do { let session = try runtime.startTerminal(shell, rows: size.rows, cols: size.cols, queue: queue) - queue.async { [self] in + queue.async { [self, session] in sessions[session.pid] = session session.onFinish = { [weak self, weak session] in if let session { self?.sessions.removeValue(forKey: session.pid) } @@ -133,7 +133,7 @@ final class TerminalServer { let run = { [self] in do { let session = try runtime.startTerminal(script, rows: 24, cols: 80, queue: queue, scrollbackLimit: Self.captureLimit) - queue.async { [self] in + queue.async { [self, session] in session.onExit = { [weak session] _ in answer(200, String(decoding: session?.capturedOutput ?? Data(), as: UTF8.self), nil) } diff --git a/platforms/ios/runnerTests/AdsBridgeTests.swift b/platforms/ios/runnerTests/AdsBridgeTests.swift index 97e7791..10bc21c 100644 --- a/platforms/ios/runnerTests/AdsBridgeTests.swift +++ b/platforms/ios/runnerTests/AdsBridgeTests.swift @@ -123,6 +123,34 @@ final class AdsBridgeTests: BridgeTestCase { XCTAssertTrue(second.preparePresentation(context(plugin, id: second.id)) === controller) } + func testPresentationRecoveryNeverDismissesAVisibleController() async throws { + let (controller, plugin) = try await host() + let ad = try XCTUnwrap(AMBFullScreen(context(plugin, id: "recovery"))) + plugin.ads[ad.id] = ad + defer { plugin.ads.removeValue(forKey: ad.id)?.destroy() } + XCTAssertNotNil(ad.preparePresentation(context(plugin, id: ad.id))) + let visible = UIViewController() + await withCheckedContinuation { continuation in + controller.present(visible, animated: false) { continuation.resume() } + } + XCTAssertFalse(ad.recoverPresentation()) + XCTAssertFalse(plugin.recoverPresentation("already-removed")) + XCTAssertTrue(ad.isPresenting) + XCTAssertTrue(controller.presentedViewController === visible) + await withCheckedContinuation { continuation in + visible.dismiss(animated: false) { continuation.resume() } + } + XCTAssertTrue(ad.recoverPresentation()) + XCTAssertFalse(ad.isPresenting) + XCTAssertNil(plugin.presentedAd) + // Recovery also handles the case where only the JS event was lost. + XCTAssertTrue(ad.recoverPresentation()) + ad.destroy() + XCTAssertFalse(ad.recoverPresentation()) + plugin.ads.removeValue(forKey: ad.id) + XCTAssertTrue(plugin.recoverPresentation(ad.id)) + } + func testPaidImpressionPayloadPreservesFormatsAndCurrencyMicros() async throws { let (controller, plugin) = try await host() let webView = controller.webView! diff --git a/platforms/ios/runnerTests/AdsRequestTests.swift b/platforms/ios/runnerTests/AdsRequestTests.swift new file mode 100644 index 0000000..df6291e --- /dev/null +++ b/platforms/ios/runnerTests/AdsRequestTests.swift @@ -0,0 +1,93 @@ +import GoogleMobileAds +import UserMessagingPlatform +import WebKit +import XCTest +@testable import runner + +@MainActor +final class AdsRequestTests: XCTestCase { + func testAgeTreatmentPreservesRestrictionsAcrossPartialConfigurationUpdates() { + let bridge = Bridge() + let plugin = AMBPlugin(bridge: bridge) + let configuration = MobileAds.shared.requestConfiguration + let original = configuration.ageRestrictedTreatment + defer { configuration.ageRestrictedTreatment = original } + configure(["tagForChildDirectedTreatment": false, "tagForUnderAgeOfConsent": false]) + XCTAssertEqual(configuration.ageRestrictedTreatment, .unspecified) + configure(["tagForUnderAgeOfConsent": true]) + XCTAssertEqual(configuration.ageRestrictedTreatment, .child) + configure(["tagForChildDirectedTreatment": false]) + XCTAssertEqual(configuration.ageRestrictedTreatment, .child) + configure(["tagForChildDirectedTreatment": true, "tagForUnderAgeOfConsent": false]) + XCTAssertEqual(configuration.ageRestrictedTreatment, .child) + configure([:]) + XCTAssertEqual(configuration.ageRestrictedTreatment, .child) + configure(["tagForChildDirectedTreatment": false]) + XCTAssertEqual(configuration.ageRestrictedTreatment, .unspecified) + + func configure(_ options: [String: Any]) { + AMBContext(plugin, [options], Callback(id: 0, webView: nil)).configure() + } + } + + func testLoadAndShowRequireStartupEvenWithConsent() async throws { + let bridge = Bridge() + let plugin = AMBPlugin(bridge: bridge) + let information = RequestConsentFixture() + plugin.privacy = AMBPrivacy(plugin: plugin, information: information) + let receiver = RequestReplyReceiver(loaded: expectation(description: "Callback page loaded")) + let configuration = WKWebViewConfiguration() + configuration.userContentController.add(receiver, name: "reply") + let replies = WKWebView(frame: .zero, configuration: configuration) + replies.navigationDelegate = receiver + defer { configuration.userContentController.removeScriptMessageHandler(forName: "reply") } + replies.loadHTMLString("", baseURL: nil) + await fulfillment(of: [receiver.loaded], timeout: 5) + let ctx = AMBContext(plugin, [["id": "gate", "adUnitId": "fixture"]], Callback(id: 0, webView: nil)) + let ad = try XCTUnwrap(RequestAdFixture(ctx)) + plugin.ads[ad.id] = ad + for allowed in [false, true] { + information.allowed = allowed + for action in ["adLoad", "adShow"] { + let response = expectation(description: "\(action) rejected before startup") + receiver.onReply = { payload in + XCTAssertEqual(payload["status"] as? Int, 9) + XCTAssertEqual(payload["error"] as? String, allowed + ? "Initialize ads before requesting ads" : "Gather ad consent before requesting ads") + response.fulfill() + } + plugin.exec(action: action, args: [["id": ad.id]], callback: Callback(id: 1, webView: replies)) + await fulfillment(of: [response], timeout: 5) + } + } + XCTAssertEqual(ad.requests, 0) + XCTAssertFalse(ad.recoverPresentation()) + } +} + +private final class RequestConsentFixture: ConsentInformation { + var allowed = false + override var canRequestAds: Bool { allowed } +} + +private final class RequestAdFixture: AMBFullScreen { + var requests = 0 + override func isLoaded() -> Bool { true } + override func load(_ ctx: AMBContext) { requests += 1; ctx.resolve() } + override func show(_ ctx: AMBContext) { requests += 1; ctx.resolve(true) } +} + +@MainActor +private final class RequestReplyReceiver: NSObject, WKNavigationDelegate, WKScriptMessageHandler { + let loaded: XCTestExpectation + var onReply: ([String: Any]) -> Void = { _ in } + + init(loaded: XCTestExpectation) { self.loaded = loaded } + + func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { loaded.fulfill() } + + func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) { + guard let payload = message.body as? [String: Any] else { XCTFail("Invalid callback payload"); return } + onReply(payload) + } +} diff --git a/platforms/ios/runnerTests/AdsStartupTests.swift b/platforms/ios/runnerTests/AdsStartupTests.swift new file mode 100644 index 0000000..5b248a6 --- /dev/null +++ b/platforms/ios/runnerTests/AdsStartupTests.swift @@ -0,0 +1,90 @@ +import StoreKit +import XCTest +@testable import runner + +@MainActor +final class AdsStartupTests: XCTestCase { + func testEnvironmentCacheCoalescesRequestsAndRetainsVerifiedResult() async { + let cache = AMBAdEnvironmentCache() + var complete: CheckedContinuation? + let started = expectation(description: "StoreKit lookup started") + let first = Task { @MainActor in + await cache.current { + await withCheckedContinuation { complete = $0; started.fulfill() } + } + } + await fulfillment(of: [started], timeout: 1) + let joined = expectation(description: "Second lookup joined") + let second = Task { @MainActor in + joined.fulfill() + return await cache.current { XCTFail("Concurrent lookup must be coalesced"); return .production } + } + await fulfillment(of: [joined], timeout: 1) + complete?.resume(returning: .sandbox) + let firstResult = await first.value + let secondResult = await second.value + XCTAssertEqual(firstResult.verifiedEnvironment, .sandbox) + XCTAssertEqual(secondResult.verifiedEnvironment, .sandbox) + let cached = await cache.current { XCTFail("Verified result must be reused"); return nil } + XCTAssertEqual(cached.verifiedEnvironment, .sandbox) + } + + func testEnvironmentCacheRetriesFailuresAndUnverifiedResultsAfterCooldown() async { + var instant = ContinuousClock.now + let cache = AMBAdEnvironmentCache(now: { instant }) + let failed = await cache.current { throw URLError(.notConnectedToInternet) } + XCTAssertNil(failed.verifiedEnvironment) + let cooled = await cache.current { XCTFail("Retry must be throttled"); return .sandbox } + XCTAssertNil(cooled.verifiedEnvironment) + instant = instant.advanced(by: .seconds(30)) + let unverified = await cache.current { nil } + XCTAssertNil(unverified.verifiedEnvironment) + instant = instant.advanced(by: .seconds(30)) + let recovered = await cache.current { .sandbox } + XCTAssertEqual(recovered.verifiedEnvironment, .sandbox) + } + + func testOnlyVerifiedTestingEnvironmentsReplaceConfiguredUnits() { + let formats = ["banner", "interstitial", "rewarded", "rewardedInterstitial", "appOpen", "native"] + for environment: AppStore.Environment? in [nil, .production, .sandbox, .xcode] { + let policy = AMBAdEnvironment(verifiedEnvironment: environment) + for format in formats { + let unit = policy.unitID(for: format, configured: "production-unit") + if environment == .sandbox || environment == .xcode { + XCTAssertTrue(unit.hasPrefix("ca-app-pub-3940256099942544/"), format) + } else { XCTAssertEqual(unit, "production-unit", format) } + } + XCTAssertEqual(policy.unitID(for: "webView", configured: "original"), "original") + } + XCTAssertEqual(AMBAdEnvironment(verifiedEnvironment: .sandbox).unitID(for: "rewarded", configured: "production"), + "ca-app-pub-3940256099942544/1712485313") + } + + func testEnvironmentLookupPreservesSuccessAndFallsBackOnFailure() async { + let verified = await AMBAdEnvironment.resolve { .sandbox } + XCTAssertEqual(verified.verifiedEnvironment, .sandbox) + let failed = await AMBAdEnvironment.resolve { throw URLError(.notConnectedToInternet) } + XCTAssertNil(failed.verifiedEnvironment) + } + + func testEnvironmentDeadlineDoesNotWaitForCancellationAndIgnoresLateResult() async { + var completeLookup: CheckedContinuation? + let started = expectation(description: "Lookup started") + let completed = expectation(description: "Deadline releases startup") + let request = Task { @MainActor in + let result = await AMBAdEnvironment.resolve(timeout: .milliseconds(25)) { + await withCheckedContinuation { + completeLookup = $0 + started.fulfill() + } + } + XCTAssertNil(result.verifiedEnvironment) + completed.fulfill() + return result + } + await fulfillment(of: [started, completed], timeout: 2) + completeLookup?.resume(returning: .sandbox) + let result = await request.value + XCTAssertEqual(result.unitID(for: "rewarded", configured: "production"), "production") + } +} diff --git a/platforms/ios/runnerTests/RewardPassTests.swift b/platforms/ios/runnerTests/RewardPassTests.swift index 28d1a0f..ebaa3f0 100644 --- a/platforms/ios/runnerTests/RewardPassTests.swift +++ b/platforms/ios/runnerTests/RewardPassTests.swift @@ -3,81 +3,61 @@ import XCTest final class RewardPassTests: XCTestCase { private let store = SecretStore(namespace: "ios-test.rewards." + UUID().uuidString) - private let hour: Int64 = 3_600_000 override func tearDownWithError() throws { try store.clear() } - func testQuickPassPersistsAndDailyLimitResetsAtLocalMidnight() throws { - var date = Calendar.current.startOfDay(for: Date()).addingTimeInterval(23 * 3600 + 1800) + func testExistingPassPersistsAndExpiryNoticeIsConsumedOnce() throws { + var date = Date() + let expiry = Int64(date.timeIntervalSince1970 * 1000) + 3_600_000 + try store.set("reward_state", value: "{\"adFreeUntil\":\(expiry),\"redemptionsToday\":2}") let rewards = RewardPassManager(store: store, now: { date }) - let initial = try status(rewards.getRewardStatus()) - XCTAssertEqual(initial["remainingRedemptions"] as? Int, 3) - XCTAssertEqual(initial["isActive"] as? Bool, false) - XCTAssertThrowsError(try rewards.redeemReward("invalid")) { XCTAssertEqual($0.localizedDescription, "Unknown reward offer.") } - let first = try status(rewards.redeemReward("quick")) - XCTAssertEqual(first["grantedDurationMs"] as? Int64, hour) - XCTAssertEqual(first["appliedDurationMs"] as? Int64, hour) - XCTAssertEqual(first["offerId"] as? String, "quick") - XCTAssertEqual(first["isActive"] as? Bool, true) + let active = try status(rewards.getRewardStatus()) + XCTAssertEqual(active["isActive"] as? Bool, true) + XCTAssertEqual(active["remainingMs"] as? Int64, 3_600_000) + XCTAssertEqual(active["canRedeem"] as? Bool, false) + XCTAssertEqual(active["hasPendingExpiryNotice"] as? Bool, false) let reopened = RewardPassManager(store: store, now: { date }) - let persisted = try status(reopened.getRewardStatus()) - XCTAssertEqual(first["adFreeUntil"] as? Int64, persisted["adFreeUntil"] as? Int64) - _ = try rewards.redeemReward("quick") - let third = try status(rewards.redeemReward("quick")) - XCTAssertEqual(third["remainingMs"] as? Int64, 3 * hour) - XCTAssertEqual(third["remainingRedemptions"] as? Int, 0) - XCTAssertEqual(third["canRedeem"] as? Bool, false) - XCTAssertThrowsError(try rewards.redeemReward("quick")) { - XCTAssertEqual($0.localizedDescription, "Daily limit reached. You can redeem up to 3 rewards per day.") - } - date = date.addingTimeInterval(1800) - let nextDay = try status(reopened.getRewardStatus()) - XCTAssertEqual(nextDay["remainingRedemptions"] as? Int, 3) - XCTAssertEqual(nextDay["remainingMs"] as? Int64, 9_000_000) - XCTAssertEqual(nextDay["canRedeem"] as? Bool, true) - } - - func testFocusOfferRangeAndTenHourCap() throws { - let date = Date() - for hours in 4...6 { - try store.clear() - let rewards = RewardPassManager(store: store, now: { date }, focusHours: { hours }) - let first = try status(rewards.redeemReward("focus")) - XCTAssertEqual(first["grantedDurationMs"] as? Int64, Int64(hours) * hour) - } - let rewards = RewardPassManager(store: store, now: { date }, focusHours: { 6 }) - let capped = try status(rewards.redeemReward("focus")) - XCTAssertEqual(capped["grantedDurationMs"] as? Int64, 6 * hour) - XCTAssertEqual(capped["appliedDurationMs"] as? Int64, 4 * hour) - XCTAssertEqual(capped["remainingMs"] as? Int64, 10 * hour) - XCTAssertEqual(capped["remainingRedemptions"] as? Int, 1) - XCTAssertEqual(capped["canRedeem"] as? Bool, false) - XCTAssertThrowsError(try rewards.redeemReward("quick")) { - XCTAssertEqual($0.localizedDescription, "You already have the maximum 10 hours of ad-free time active.") - } - } + XCTAssertEqual(try status(reopened.getRewardStatus())["adFreeUntil"] as? Int64, expiry) - func testExpiryNoticeIsConsumedOnceAndMalformedStateRecovers() throws { - var date = Date() - let rewards = RewardPassManager(store: store, now: { date }) - try store.set("reward_state", value: "malformed") - let grant = try status(rewards.redeemReward("quick")) date = date.addingTimeInterval(3600) - let expired = try status(rewards.getRewardStatus()) + let expired = try status(reopened.getRewardStatus()) XCTAssertEqual(expired["isActive"] as? Bool, false) XCTAssertEqual(expired["adFreeUntil"] as? Int64, 0) XCTAssertEqual(expired["remainingMs"] as? Int64, 0) XCTAssertEqual(expired["hasPendingExpiryNotice"] as? Bool, true) - XCTAssertEqual(expired["expiryNoticePendingUntil"] as? Int64, grant["adFreeUntil"] as? Int64) - let reopened = RewardPassManager(store: store, now: { date }) - let consumed = try status(reopened.getRewardStatus()) + XCTAssertEqual(expired["expiryNoticePendingUntil"] as? Int64, expiry) + let consumed = try status(rewards.getRewardStatus()) XCTAssertEqual(consumed["hasPendingExpiryNotice"] as? Bool, false) - XCTAssertEqual(consumed["lastExpiredRewardUntil"] as? Int64, grant["adFreeUntil"] as? Int64) - let renewed = try status(reopened.redeemReward("quick")) - XCTAssertEqual(renewed["lastExpiredRewardUntil"] as? Int64, 0) - XCTAssertEqual(renewed["expiryNoticePendingUntil"] as? Int64, 0) - try store.set("reward_state", value: "{\"redemptionsToday\":2}") - XCTAssertEqual(try status(rewards.getRewardStatus())["remainingRedemptions"] as? Int, 1) + XCTAssertEqual(consumed["lastExpiredRewardUntil"] as? Int64, expiry) + } + + func testMissingOrMalformedStateCannotGrantTime() throws { + let rewards = RewardPassManager(store: store) + for raw in ["", "malformed", "{\"redemptionsToday\":2}"] { + try store.set("reward_state", value: raw) + let empty = try status(rewards.getRewardStatus()) + XCTAssertEqual(empty["isActive"] as? Bool, false) + XCTAssertEqual(empty["canRedeem"] as? Bool, false) + XCTAssertEqual(empty["hasPendingExpiryNotice"] as? Bool, false) + } + } + + func testUnchangedStatusDoesNotRewriteStorageAndDayRolloverIsPersisted() throws { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = .current + var date = try XCTUnwrap(calendar.date(from: DateComponents(year: 2026, month: 11, day: 15, hour: 12))) + let raw = """ + { "adFreeUntil": 0, "lastExpiredRewardUntil": 0, "expiryNoticePendingUntil": 0, + "redemptionDay": "2026-11-15", "redemptionsToday": 2 } + """ + try store.set("reward_state", value: raw) + let rewards = RewardPassManager(store: store, now: { date }) + _ = try rewards.getRewardStatus() + XCTAssertEqual(try store.get("reward_state"), raw, "An unchanged read must not rewrite even the JSON formatting") + date = try XCTUnwrap(calendar.date(byAdding: .day, value: 1, to: date)) + XCTAssertEqual(try status(rewards.getRewardStatus())["redemptionsToday"] as? Int, 0) + let saved = try status(store.get("reward_state")) + XCTAssertEqual(saved["redemptionDay"] as? String, "2026-11-16") } private func status(_ value: String) throws -> [String: Any] { @@ -87,16 +67,17 @@ final class RewardPassTests: XCTestCase { @MainActor final class RewardBridgeTests: BridgeTestCase { - func testPublicStatusAPIAndUnknownOfferRejection() async throws { + func testStatusRemainsAvailableButRedemptionIsUnsupported() async throws { let webView = try await appWebView() let result = try await webView.callAsyncJavaScript(""" const raw=await new Promise((resolve,reject)=>system.getRewardStatus(resolve,reject)); if(typeof raw!=='string')throw Error('Changed reward response type'); const status=JSON.parse(raw); - if(status.maxRedemptionsPerDay!==3||status.maxActivePassMs!==36000000)throw Error('Changed reward limits'); + if(status.canRedeem!==false)throw Error('New passes must remain disabled'); if(typeof status.hasPendingExpiryNotice!=='boolean')throw Error('Missing expiry policy'); - try{await new Promise((resolve,reject)=>system.redeemReward('invalid',resolve,reject));return false;} - catch(error){return typeof error==='string'&&!error.includes('unavailable on iOS');} + if(typeof system.redeemReward!=='undefined')throw Error('Retired wrapper still exposed'); + try{await new Promise((resolve,reject)=>Bridge.exec(resolve,reject,'System','redeemReward',['quick']));return false;} + catch(error){return error?.code==='UNSUPPORTED_ACTION';} """, arguments: [:], in: nil, contentWorld: .page) as? Bool XCTAssertEqual(result, true) } diff --git a/platforms/ios/runnerTests/ShareTests.swift b/platforms/ios/runnerTests/ShareTests.swift index 2c3917d..3a0a116 100644 --- a/platforms/ios/runnerTests/ShareTests.swift +++ b/platforms/ios/runnerTests/ShareTests.swift @@ -5,6 +5,35 @@ import WebKit @MainActor final class ShareTests: BridgeTestCase { func testFileExportsAreIsolatedAndRemovedAfterCancellationOrReload() async throws { + try await verifyFileSharing(service: "System") + } + + func testNativeFileExportsSurviveUntilDismissalAndAreRemovedOnReload() async throws { + try await verifyFileSharing(service: "Native") + } + + func testRepeatedBridgeSetupRetainsShareOwnerAndCleansPresentedExport() async throws { + try await verifyFileSharing(service: "Native", repeatSetup: true) + } + + func testNativeTextSharingPresentsAndCompletes() async throws { + let webView = try await appWebView() + var responder: UIResponder? = webView + while responder != nil, !(responder is WebViewController) { responder = responder?.next } + let host = try XCTUnwrap(responder as? WebViewController) + _ = try await webView.evaluateJavaScript(""" + window.shareResult={state:'pending'}; + Bridge.exec(()=>window.shareResult={state:'success'},error=>window.shareResult={state:'error',error}, + 'Native','shareText',['Share fixture']); + """) + let presented = try await sheet(host) + presented.completionWithItemsHandler?(nil, false, nil, nil) + await dismiss(presented) + let response = try await result(webView) + XCTAssertEqual(response["state"] as? String, "success") + } + + private func verifyFileSharing(service: String, repeatSetup: Bool = false) async throws { let webView = try await appWebView() var responder: UIResponder? = webView while responder != nil, !(responder is WebViewController) { responder = responder?.next } @@ -15,7 +44,7 @@ final class ShareTests: BridgeTestCase { try bytes.write(to: source) defer { try? files.manager.removeItem(at: source) } let original = try exports() - try await begin(webView, path: source.absoluteString) + try await begin(webView, service: service, path: source.absoluteString) let first = try await sheet(host) let exported = try XCTUnwrap(try exports().subtracting(original).first) let copy = exported.appendingPathComponent("shared # 日本語.bin") @@ -23,7 +52,7 @@ final class ShareTests: BridgeTestCase { try Data([1, 2, 3]).write(to: source) XCTAssertEqual(try Data(contentsOf: copy), bytes) - try await begin(webView, path: source.absoluteString, key: "busyShare") + try await begin(webView, service: service == "Native" ? "System" : "Native", path: source.absoluteString, key: "busyShare") let busy = try await result(webView, key: "busyShare") XCTAssertEqual(busy["error"] as? String, "A share sheet cannot be presented right now") XCTAssertEqual(try exports().subtracting(original), [exported]) @@ -33,8 +62,13 @@ final class ShareTests: BridgeTestCase { XCTAssertEqual(cancelled["state"] as? String, "success") XCTAssertEqual(try exports(), original) - try await begin(webView, path: source.absoluteString) + try await begin(webView, service: service, path: source.absoluteString) let pending = try await sheet(host) + if repeatSetup { + let owner = host.bridge.shareService + host.bridge.setup(webView: webView, viewController: host) + XCTAssertTrue(host.bridge.shareService === owner) + } webView.reload() for _ in 0..<100 { if host.presentedViewController == nil { break } @@ -49,12 +83,12 @@ final class ShareTests: BridgeTestCase { _ = try await editorWebView() } - private func begin(_ webView: WKWebView, path: String, key: String = "shareResult") async throws { + private func begin(_ webView: WKWebView, service: String, path: String, key: String = "shareResult") async throws { _ = try await webView.callAsyncJavaScript(""" window[key]={state:'pending'}; Bridge.exec(()=>window[key]={state:'success'},error=>window[key]={state:'error',error}, - 'System','file-action',[path,'shared # 日本語.bin','android.intent.action.SEND']); - """, arguments: ["path": path, "key": key], in: nil, contentWorld: .page) + service,service==='Native'?'shareFile':'file-action',[path,'shared # 日本語.bin','android.intent.action.SEND']); + """, arguments: ["service": service, "path": path, "key": key], in: nil, contentWorld: .page) } private func exports() throws -> Set { diff --git a/platforms/ios/runnerTests/TrackingAuthorizationTests.swift b/platforms/ios/runnerTests/TrackingAuthorizationTests.swift new file mode 100644 index 0000000..30b7797 --- /dev/null +++ b/platforms/ios/runnerTests/TrackingAuthorizationTests.swift @@ -0,0 +1,193 @@ +import AppTrackingTransparency +import UIKit +import XCTest +@testable import runner + +@MainActor +final class TrackingAuthorizationTests: XCTestCase { + private var appActive = false + + func testTrackingWaitsForActiveAppAndCoalescesRequests() async { + appActive = false + var calls = 0 + var callback: ((ATTrackingManager.AuthorizationStatus) -> Void)? + let notifications = NotificationCenter() + let requested = expectation(description: "ATT requested in foreground") + let tracking = AMBTrackingAuthorization(status: { .notDetermined }, isActive: { self.appActive }, + notifications: notifications, request: { calls += 1; callback = $0; requested.fulfill() }) + let finished = expectation(description: "Both callers receive the decision") + finished.expectedFulfillmentCount = 2 + for _ in 0..<2 { + tracking.authorize { result in + XCTAssertEqual(try? result.get(), .denied) + finished.fulfill() + } + } + XCTAssertEqual(calls, 0) + appActive = true + notifications.post(name: UIApplication.didBecomeActiveNotification, object: nil) + await fulfillment(of: [requested], timeout: 2) + XCTAssertEqual(calls, 1) + callback?(.denied) + await fulfillment(of: [finished], timeout: 2) + } + + func testExistingTrackingDecisionsDoNotPromptAgain() { + for status: ATTrackingManager.AuthorizationStatus in [.denied, .restricted, .authorized] { + let tracking = AMBTrackingAuthorization(status: { status }, isActive: { false }, request: { _ in + XCTFail("A decided permission must not prompt again") + }) + var result: ATTrackingManager.AuthorizationStatus? + tracking.authorize { result = try? $0.get() } + XCTAssertEqual(result, status) + } + } + + func testUndeterminedResultCannotStartAdsAndAllowsRetry() async { + var calls = 0 + let tracking = AMBTrackingAuthorization(status: { .notDetermined }, isActive: { true }, request: { + calls += 1 + $0(calls == 1 ? .notDetermined : .authorized) + }) + let failed = expectation(description: "No ad startup without ATT decision") + tracking.authorize { result in + if case .success = result { XCTFail("Unresolved ATT must not initialize ads") } + failed.fulfill() + } + await fulfillment(of: [failed], timeout: 2) + let retried = expectation(description: "Retry succeeds") + tracking.authorize { result in + XCTAssertEqual(try? result.get(), .authorized) + retried.fulfill() + } + await fulfillment(of: [retried], timeout: 2) + XCTAssertEqual(calls, 2) + } + + func testResetCancelsCallerWithoutStartingAnOverlappingTrackingRequest() async { + var requests = 0 + var reply: (@Sendable (ATTrackingManager.AuthorizationStatus) -> Void)? + let tracking = AMBTrackingAuthorization(status: { .notDetermined }, isActive: { true }, request: { + requests += 1 + reply = $0 + }) + var cancelled = false + tracking.authorize { result in + if case .failure = result { cancelled = true } + } + tracking.cancel() + XCTAssertTrue(cancelled) + let completed = expectation(description: "New caller receives the outstanding OS decision") + tracking.authorize { result in + XCTAssertEqual(try? result.get(), .denied) + completed.fulfill() + } + XCTAssertEqual(requests, 1) + reply?(.denied) + await fulfillment(of: [completed], timeout: 2) + } + + func testDeadlineFailsWaitersWithoutOverlappingOSRequestAndLateReplyCanRecover() async { + var calls = 0 + var reply: (@Sendable (ATTrackingManager.AuthorizationStatus) -> Void)? + let tracking = AMBTrackingAuthorization(status: { .notDetermined }, isActive: { true }, + timeout: .milliseconds(25), request: { calls += 1; reply = $0 }) + let timedOut = expectation(description: "Both callers time out without a decision") + timedOut.expectedFulfillmentCount = 2 + for _ in 0..<2 { + tracking.authorize { result in + if case .success = result { XCTFail("Timeout is not authorization") } + timedOut.fulfill() + } + } + await fulfillment(of: [timedOut], timeout: 2) + let recovered = expectation(description: "Retry uses the outstanding OS request") + tracking.authorize { result in + XCTAssertEqual(try? result.get(), .denied) + recovered.fulfill() + } + XCTAssertEqual(calls, 1) + reply?(.denied) + await fulfillment(of: [recovered], timeout: 2) + } + + func testDeadlineReadsDeterminedOSStatusWhenReplyIsLost() async { + var current = ATTrackingManager.AuthorizationStatus.notDetermined + var calls = 0 + let tracking = AMBTrackingAuthorization(status: { current }, isActive: { true }, + timeout: .milliseconds(25), request: { _ in calls += 1 }) + let completed = expectation(description: "Deadline uses OS status, not a fabricated decision") + tracking.authorize { result in + XCTAssertEqual(try? result.get(), .restricted) + completed.fulfill() + } + current = .restricted + await fulfillment(of: [completed], timeout: 2) + XCTAssertEqual(calls, 1) + } + + func testForegroundRechecksOSStatusEvenWithAnOutstandingRequest() async { + var current = ATTrackingManager.AuthorizationStatus.notDetermined + let notifications = NotificationCenter() + let tracking = AMBTrackingAuthorization(status: { current }, isActive: { true }, + notifications: notifications, request: { _ in }) + let completed = expectation(description: "Foreground sees the lost callback's decision") + tracking.authorize { result in + XCTAssertEqual(try? result.get(), .denied) + completed.fulfill() + } + current = .denied + notifications.post(name: UIApplication.didBecomeActiveNotification, object: nil) + await fulfillment(of: [completed], timeout: 2) + } + + func testInactiveWaitIsBoundedAndCanRetryWhenActive() async { + appActive = false + var calls = 0 + let tracking = AMBTrackingAuthorization(status: { .notDetermined }, isActive: { self.appActive }, + timeout: .milliseconds(25), request: { calls += 1; $0(.denied) }) + let timedOut = expectation(description: "Inactive wait times out") + tracking.authorize { result in + if case .success = result { XCTFail("Inactive timeout must not start ads") } + timedOut.fulfill() + } + await fulfillment(of: [timedOut], timeout: 2) + XCTAssertEqual(calls, 0) + appActive = true + let completed = expectation(description: "Active retry succeeds") + tracking.authorize { result in + XCTAssertEqual(try? result.get(), .denied) + completed.fulfill() + } + await fulfillment(of: [completed], timeout: 2) + XCTAssertEqual(calls, 1) + } + + func testCancelledRequestCanRecoverFromOSStatusAndStaleReplyCannotSettleNewRequest() async { + var current = ATTrackingManager.AuthorizationStatus.notDetermined + var replies: [@Sendable (ATTrackingManager.AuthorizationStatus) -> Void] = [] + let tracking = AMBTrackingAuthorization(status: { current }, isActive: { true }, request: { replies.append($0) }) + var cancelled = false + tracking.authorize { result in + if case .failure = result { cancelled = true } + } + tracking.cancel() + XCTAssertTrue(cancelled) + current = .denied + var recovered: ATTrackingManager.AuthorizationStatus? + tracking.authorize { recovered = try? $0.get() } + XCTAssertEqual(recovered, .denied) + XCTAssertEqual(replies.count, 1) + + current = .notDetermined + let completed = expectation(description: "Only the new OS request settles the new caller") + tracking.authorize { result in + XCTAssertEqual(try? result.get(), .restricted) + completed.fulfill() + } + XCTAssertEqual(replies.count, 2) + replies[0](.authorized) + replies[1](.restricted) + await fulfillment(of: [completed], timeout: 2) + } +} diff --git a/rspack.config.js b/rspack.config.js index ddac534..b1d8102 100644 --- a/rspack.config.js +++ b/rspack.config.js @@ -227,8 +227,6 @@ module.exports = (env, options) => { ADMOB_BANNER_ID: JSON.stringify(ads.banner), ADMOB_INTERSTITIAL_ID: JSON.stringify(ads.interstitial), ADMOB_REWARDED_ID: JSON.stringify(ads.rewarded), - ADMOB_ACADEMY_REWARDED_ID: JSON.stringify(ads.academyRewarded), - ADMOB_ACADEMY_INTERSTITIAL_ID: JSON.stringify(ads.academyInterstitial), ADMOB_APP_OPEN_ID: JSON.stringify(ads.appOpen), __FDROID__: JSON.stringify(process.env.ACODE_FDROID === 'true'), __DEV_MODE__: JSON.stringify(isDev), diff --git a/src/lang/ar-ye.json b/src/lang/ar-ye.json index bf8f2ac..e096d76 100644 --- a/src/lang/ar-ye.json +++ b/src/lang/ar-ye.json @@ -519,7 +519,6 @@ "save file before home shortcut": "احفظ الملف قبل إضافته إلى الشاشة الرئيسية.", "terminal_required_message_for_lsp": "الطرفية غير مثبتة. يرجى تثبيت الطرفية أولاً لاستخدام خوادم LSP.", "shift click selection": "تحديد عبر Shift + نقر/ضغط", - "earn ad-free time": "اكسب وقتاً خالياً من الإعلانات", "indent guides": "خطوط توجيه المسافات البادئة", "language servers": "خوادم اللغة", "lint gutter": "إظهار هامش التدقيق", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "إزالة الحزم أو الملفات الثنائية المثبتة لهذا الخادم.", "settings-info-lsp-update-server": "تحديث خادم اللغة هذا إذا كان مسار التحديث متاحاً.", "settings-info-lsp-view-init-options": "عرض خيارات التهيئة الفعلية بصيغة JSON.", - "settings-info-main-ad-rewards": "مشاهدة الإعلانات لفتح وصول مؤقت خالٍ من الإعلانات.", "settings-info-main-app-settings": "اللغة، سلوك التطبيق، وأدوات الوصول السريع.", "settings-info-main-backup-restore": "تصدير الإعدادات إلى نسخة احتياطية أو استعادتها لاحقاً.", "settings-info-main-changelog": "عرض آخر التحديثات وملاحظات الإصدار.", diff --git a/src/lang/az-az.json b/src/lang/az-az.json index 6d982f7..ec8c583 100644 --- a/src/lang/az-az.json +++ b/src/lang/az-az.json @@ -549,7 +549,6 @@ "save file before home shortcut": "Faylı əsas ekrana əlavə etməzdən əvvəl yadda saxla.", "terminal_required_message_for_lsp": "Terminal quraşdırılmayıb. LSP serverlərindən istifadə etmək üçün əvvəlcə terminalı quraşdır.", "shift click selection": "Yuxarı registr düyməsi + toxunuş/klik ilə seçim", - "earn ad-free time": "Reklamsız istifadə vaxtı qazan", "indent guides": "Girinti bələdçiləri", "language servers": "Dil serverləri", "lint gutter": "Kod yoxlamasının kənar zolağını göstər", @@ -745,7 +744,6 @@ "settings-info-lsp-uninstall-server": "Bu server üçün quraşdırılmış paketləri və ya icra fayllarını çıxar.", "settings-info-lsp-update-server": "Yeniləmə imkanı varsa, bu dil serverini yenilə.", "settings-info-lsp-view-init-options": "Qüvvədə olan ilkin sazlama seçimlərinə JSON kimi bax.", - "settings-info-main-ad-rewards": "Müvəqqəti reklamsız istifadə imkanı əldə etmək üçün reklamlara bax.", "settings-info-main-app-settings": "Dil, tətbiqin davranışı və sürətli giriş alətləri.", "settings-info-main-backup-restore": "Parametrləri ehtiyat nüsxəyə ixrac et və ya sonradan bərpa et.", "settings-info-main-changelog": "Son yeniləmələrə və buraxılış qeydlərinə bax.", diff --git a/src/lang/be-by.json b/src/lang/be-by.json index 11c19f4..0ae240c 100644 --- a/src/lang/be-by.json +++ b/src/lang/be-by.json @@ -519,7 +519,6 @@ "save file before home shortcut": "Save the file before adding it to the home screen.", "terminal_required_message_for_lsp": "Terminal not installed. Please install Terminal first to use LSP servers.", "shift click selection": "Shift + tap/click selection", - "earn ad-free time": "Earn ad-free time", "indent guides": "Indent guides", "language servers": "Language servers", "lint gutter": "Show lint gutter", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "Remove installed packages or binaries for this server.", "settings-info-lsp-update-server": "Update this language server if an update flow is available.", "settings-info-lsp-view-init-options": "View the effective initialization options as JSON.", - "settings-info-main-ad-rewards": "Watch ads to unlock temporary ad-free access.", "settings-info-main-app-settings": "Language, app behavior, and quick access tools.", "settings-info-main-backup-restore": "Export settings to a backup or restore them later.", "settings-info-main-changelog": "See recent updates and release notes.", diff --git a/src/lang/bn-bd.json b/src/lang/bn-bd.json index 9af4cf9..4a995ce 100644 --- a/src/lang/bn-bd.json +++ b/src/lang/bn-bd.json @@ -519,7 +519,6 @@ "save file before home shortcut": "Save the file before adding it to the home screen.", "terminal_required_message_for_lsp": "Terminal not installed. Please install Terminal first to use LSP servers.", "shift click selection": "Shift + tap/click selection", - "earn ad-free time": "Earn ad-free time", "indent guides": "Indent guides", "language servers": "Language servers", "lint gutter": "Show lint gutter", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "Remove installed packages or binaries for this server.", "settings-info-lsp-update-server": "Update this language server if an update flow is available.", "settings-info-lsp-view-init-options": "View the effective initialization options as JSON.", - "settings-info-main-ad-rewards": "Watch ads to unlock temporary ad-free access.", "settings-info-main-app-settings": "Language, app behavior, and quick access tools.", "settings-info-main-backup-restore": "Export settings to a backup or restore them later.", "settings-info-main-changelog": "See recent updates and release notes.", diff --git a/src/lang/cs-cz.json b/src/lang/cs-cz.json index 5f737f4..ed900a8 100644 --- a/src/lang/cs-cz.json +++ b/src/lang/cs-cz.json @@ -519,7 +519,6 @@ "save file before home shortcut": "Save the file before adding it to the home screen.", "terminal_required_message_for_lsp": "Terminal not installed. Please install Terminal first to use LSP servers.", "shift click selection": "Shift + tap/click selection", - "earn ad-free time": "Earn ad-free time", "indent guides": "Indent guides", "language servers": "Language servers", "lint gutter": "Show lint gutter", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "Remove installed packages or binaries for this server.", "settings-info-lsp-update-server": "Update this language server if an update flow is available.", "settings-info-lsp-view-init-options": "View the effective initialization options as JSON.", - "settings-info-main-ad-rewards": "Watch ads to unlock temporary ad-free access.", "settings-info-main-app-settings": "Language, app behavior, and quick access tools.", "settings-info-main-backup-restore": "Export settings to a backup or restore them later.", "settings-info-main-changelog": "See recent updates and release notes.", diff --git a/src/lang/de-de.json b/src/lang/de-de.json index c6650d0..c702a7c 100644 --- a/src/lang/de-de.json +++ b/src/lang/de-de.json @@ -519,7 +519,6 @@ "save file before home shortcut": "Save the file before adding it to the home screen.", "terminal_required_message_for_lsp": "Terminal not installed. Please install Terminal first to use LSP servers.", "shift click selection": "Shift + tap/click selection", - "earn ad-free time": "Earn ad-free time", "indent guides": "Indent guides", "language servers": "Language servers", "lint gutter": "Show lint gutter", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "Remove installed packages or binaries for this server.", "settings-info-lsp-update-server": "Update this language server if an update flow is available.", "settings-info-lsp-view-init-options": "View the effective initialization options as JSON.", - "settings-info-main-ad-rewards": "Watch ads to unlock temporary ad-free access.", "settings-info-main-app-settings": "Language, app behavior, and quick access tools.", "settings-info-main-backup-restore": "Export settings to a backup or restore them later.", "settings-info-main-changelog": "See recent updates and release notes.", diff --git a/src/lang/en-us.json b/src/lang/en-us.json index 5d6ef39..07984d8 100644 --- a/src/lang/en-us.json +++ b/src/lang/en-us.json @@ -552,7 +552,6 @@ "save file before home shortcut": "Save the file before adding it to the home screen.", "terminal_required_message_for_lsp": "Terminal not installed. Please install Terminal first to use LSP servers.", "shift click selection": "Shift + tap/click selection", - "earn ad-free time": "Earn ad-free time", "indent guides": "Indent guides", "language servers": "Language Servers", "lint gutter": "Show lint gutter", @@ -748,7 +747,6 @@ "settings-info-lsp-uninstall-server": "Remove installed packages or binaries for this server.", "settings-info-lsp-update-server": "Update this language server if an update flow is available.", "settings-info-lsp-view-init-options": "View the effective initialization options as JSON.", - "settings-info-main-ad-rewards": "Watch ads to unlock temporary ad-free access.", "settings-info-main-app-settings": "Language, app behavior, and quick access tools.", "settings-info-main-backup-restore": "Export settings to a backup or restore them later.", "settings-info-main-changelog": "See recent updates and release notes.", diff --git a/src/lang/es-sv.json b/src/lang/es-sv.json index b9f709d..6bdbf29 100644 --- a/src/lang/es-sv.json +++ b/src/lang/es-sv.json @@ -519,7 +519,6 @@ "save file before home shortcut": "Guarda el archivo antes de agregarlo a la pantalla de inicio.", "terminal_required_message_for_lsp": "La terminal no está instalada. Instale la terminal primero para poder usar los servidores LSP.", "shift click selection": "Shift + pulsar/clic para seleccionar", - "earn ad-free time": "Gana tiempo sin anuncios", "indent guides": "Guías de Indentación", "language servers": "Servidores de Lenguaje", "lint gutter": "Mostrar lint gutter", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "Remover los paquetes o binarios instalados para este servidor.", "settings-info-lsp-update-server": "Actualiza este servidor si algún flujo de actualización está disponible.", "settings-info-lsp-view-init-options": "Mira las opciones de inicialización aplicadas en formato JSON.", - "settings-info-main-ad-rewards": "Mira anuncios para desactivar los anuncios en la aplicación de forma temporal.", "settings-info-main-app-settings": "Lenguaje, comportamiento de la aplicación y acceso a herramientas rápidas.", "settings-info-main-backup-restore": "Exporta tu configuración a un respaldo o restaurala más tarde.", "settings-info-main-changelog": "Mira las actualizaciones recientes y las notas release de la aplicación", diff --git a/src/lang/fr-fr.json b/src/lang/fr-fr.json index 316c866..0e65a15 100644 --- a/src/lang/fr-fr.json +++ b/src/lang/fr-fr.json @@ -519,7 +519,6 @@ "save file before home shortcut": "Save the file before adding it to the home screen.", "terminal_required_message_for_lsp": "Terminal not installed. Please install Terminal first to use LSP servers.", "shift click selection": "Shift + tap/click selection", - "earn ad-free time": "Earn ad-free time", "indent guides": "Indent guides", "language servers": "Language servers", "lint gutter": "Show lint gutter", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "Remove installed packages or binaries for this server.", "settings-info-lsp-update-server": "Update this language server if an update flow is available.", "settings-info-lsp-view-init-options": "View the effective initialization options as JSON.", - "settings-info-main-ad-rewards": "Watch ads to unlock temporary ad-free access.", "settings-info-main-app-settings": "Language, app behavior, and quick access tools.", "settings-info-main-backup-restore": "Export settings to a backup or restore them later.", "settings-info-main-changelog": "See recent updates and release notes.", diff --git a/src/lang/he-il.json b/src/lang/he-il.json index e043a94..635b715 100644 --- a/src/lang/he-il.json +++ b/src/lang/he-il.json @@ -519,7 +519,6 @@ "save file before home shortcut": "Save the file before adding it to the home screen.", "terminal_required_message_for_lsp": "Terminal not installed. Please install Terminal first to use LSP servers.", "shift click selection": "Shift + tap/click selection", - "earn ad-free time": "Earn ad-free time", "indent guides": "Indent guides", "language servers": "Language servers", "lint gutter": "Show lint gutter", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "Remove installed packages or binaries for this server.", "settings-info-lsp-update-server": "Update this language server if an update flow is available.", "settings-info-lsp-view-init-options": "View the effective initialization options as JSON.", - "settings-info-main-ad-rewards": "Watch ads to unlock temporary ad-free access.", "settings-info-main-app-settings": "Language, app behavior, and quick access tools.", "settings-info-main-backup-restore": "Export settings to a backup or restore them later.", "settings-info-main-changelog": "See recent updates and release notes.", diff --git a/src/lang/hi-in.json b/src/lang/hi-in.json index 105d36a..d3fdb6f 100644 --- a/src/lang/hi-in.json +++ b/src/lang/hi-in.json @@ -519,7 +519,6 @@ "save file before home shortcut": "फ़ाइल को होम स्क्रीन पर जोड़ने से पहले उसे सेव करें।", "terminal_required_message_for_lsp": "टर्मिनल इंस्टॉल नहीं है। LSP सर्वर उपयोग करने के लिए पहले टर्मिनल इंस्टॉल करें।", "shift click selection": "शिफ्ट + टैप/क्लिक सिलेक्शन", - "earn ad-free time": "ऐड-फ्री समय प्राप्त करें", "indent guides": "इंडेंट गाइड्स", "language servers": "लैंग्वेज सर्वर्स", "lint gutter": "लिंट गटर दिखाएँ", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "Remove installed packages or binaries for this server.", "settings-info-lsp-update-server": "Update this language server if an update flow is available.", "settings-info-lsp-view-init-options": "View the effective initialization options as JSON.", - "settings-info-main-ad-rewards": "Watch ads to unlock temporary ad-free access.", "settings-info-main-app-settings": "Language, app behavior, and quick access tools.", "settings-info-main-backup-restore": "Export settings to a backup or restore them later.", "settings-info-main-changelog": "See recent updates and release notes.", diff --git a/src/lang/hu-hu.json b/src/lang/hu-hu.json index bef09f2..2d692d1 100644 --- a/src/lang/hu-hu.json +++ b/src/lang/hu-hu.json @@ -519,7 +519,6 @@ "save file before home shortcut": "A kezdőképernyőhöz való hozzáadás előtt mentse el a fájlt.", "terminal_required_message_for_lsp": "A Terminál nincs telepítve. Először telepítse a Terminált, hogy használni tudja az LSP-kiszolgálókat.", "shift click selection": "Shift + koppintás/kattintás a kiválasztáshoz", - "earn ad-free time": "Reklámmentesség szerzése egy kis időre", "indent guides": "Behúzási segédvonalak", "language servers": "Nyelvi kiszolgálók", "lint gutter": "Szintaxisellenőrzési margó megjelenítése", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "A kiszolgálóhoz tartozó telepített csomagok vagy binárisok eltávolítása.", "settings-info-lsp-update-server": "Ezen nyelvi kiszolgáló frissítése, ha elérhető frissítési folyamat.", "settings-info-lsp-view-init-options": "Érvényes előkészítési beállítások megtekintése JSON-formátumban.", - "settings-info-main-ad-rewards": "Reklámok megtekintése az ideiglenes reklámmentes hozzáférés feloldásához.", "settings-info-main-app-settings": "Nyelv, alkalmazás viselkedése és gyorselérési eszközök.", "settings-info-main-backup-restore": "Beállítások exportálása biztonsági mentésbe vagy azok későbbi visszaállítása.", "settings-info-main-changelog": "Legutóbbi frissítések és kiadási megjegyzések megtekintése.", diff --git a/src/lang/id-id.json b/src/lang/id-id.json index 8dea45a..943720e 100644 --- a/src/lang/id-id.json +++ b/src/lang/id-id.json @@ -519,7 +519,6 @@ "save file before home shortcut": "Simpan berkas sebelum menambahkannya ke layar beranda.", "terminal_required_message_for_lsp": "Terminal belum terpasang. Mohon pasang Terminal terlebih dahulu untuk menggunakan server LSP.", "shift click selection": "Pemilihan Shift + tekan/klik", - "earn ad-free time": "Ambil waktu bebas iklan", "indent guides": "Panduan indentasi", "language servers": "Server bahasa", "lint gutter": "Tampilkan gutter lint", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "Hapus paket terpasang atau biner dari server ini.", "settings-info-lsp-update-server": "Perbarui server bahasa ini jika jalur pembaruan tersedia.", "settings-info-lsp-view-init-options": "Lihat opsi inisialisasi efektif sebagai JSON.", - "settings-info-main-ad-rewards": "Tonton iklan untuk membuka akses bebas iklan sementara.", "settings-info-main-app-settings": "Bahasa, perilaku aplikasi, dan alat akses cepat.", "settings-info-main-backup-restore": "Ekspor pengaturan ke cadangan atau pulihkan nanti.", "settings-info-main-changelog": "Lihat pembaruan saat ini dan catatan rilis.", diff --git a/src/lang/index.d.ts b/src/lang/index.d.ts index 5a41da0..a29135f 100644 --- a/src/lang/index.d.ts +++ b/src/lang/index.d.ts @@ -555,7 +555,6 @@ declare type LangStrings = { "save file before home shortcut": string; terminal_required_message_for_lsp: string; "shift click selection": string; - "earn ad-free time": string; "indent guides": string; "language servers": string; "lint gutter": string; @@ -751,7 +750,6 @@ declare type LangStrings = { "settings-info-lsp-uninstall-server": string; "settings-info-lsp-update-server": string; "settings-info-lsp-view-init-options": string; - "settings-info-main-ad-rewards": string; "settings-info-main-app-settings": string; "settings-info-main-backup-restore": string; "settings-info-main-changelog": string; diff --git a/src/lang/ir-fa.json b/src/lang/ir-fa.json index ed089a7..0699fe4 100644 --- a/src/lang/ir-fa.json +++ b/src/lang/ir-fa.json @@ -519,7 +519,6 @@ "save file before home shortcut": "Save the file before adding it to the home screen.", "terminal_required_message_for_lsp": "Terminal not installed. Please install Terminal first to use LSP servers.", "shift click selection": "Shift + tap/click selection", - "earn ad-free time": "Earn ad-free time", "indent guides": "Indent guides", "language servers": "Language servers", "lint gutter": "Show lint gutter", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "Remove installed packages or binaries for this server.", "settings-info-lsp-update-server": "Update this language server if an update flow is available.", "settings-info-lsp-view-init-options": "View the effective initialization options as JSON.", - "settings-info-main-ad-rewards": "Watch ads to unlock temporary ad-free access.", "settings-info-main-app-settings": "Language, app behavior, and quick access tools.", "settings-info-main-backup-restore": "Export settings to a backup or restore them later.", "settings-info-main-changelog": "See recent updates and release notes.", diff --git a/src/lang/it-it.json b/src/lang/it-it.json index 5ea821d..9ea8567 100644 --- a/src/lang/it-it.json +++ b/src/lang/it-it.json @@ -519,7 +519,6 @@ "save file before home shortcut": "Save the file before adding it to the home screen.", "terminal_required_message_for_lsp": "Terminal not installed. Please install Terminal first to use LSP servers.", "shift click selection": "Shift + tap/click selection", - "earn ad-free time": "Earn ad-free time", "indent guides": "Indent guides", "language servers": "Language servers", "lint gutter": "Show lint gutter", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "Remove installed packages or binaries for this server.", "settings-info-lsp-update-server": "Update this language server if an update flow is available.", "settings-info-lsp-view-init-options": "View the effective initialization options as JSON.", - "settings-info-main-ad-rewards": "Watch ads to unlock temporary ad-free access.", "settings-info-main-app-settings": "Language, app behavior, and quick access tools.", "settings-info-main-backup-restore": "Export settings to a backup or restore them later.", "settings-info-main-changelog": "See recent updates and release notes.", diff --git a/src/lang/ja-jp.json b/src/lang/ja-jp.json index 12b7ea5..8f3f2c1 100644 --- a/src/lang/ja-jp.json +++ b/src/lang/ja-jp.json @@ -519,7 +519,6 @@ "save file before home shortcut": "Save the file before adding it to the home screen.", "terminal_required_message_for_lsp": "Terminal not installed. Please install Terminal first to use LSP servers.", "shift click selection": "Shift + tap/click selection", - "earn ad-free time": "Earn ad-free time", "indent guides": "Indent guides", "language servers": "Language servers", "lint gutter": "Show lint gutter", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "Remove installed packages or binaries for this server.", "settings-info-lsp-update-server": "Update this language server if an update flow is available.", "settings-info-lsp-view-init-options": "View the effective initialization options as JSON.", - "settings-info-main-ad-rewards": "Watch ads to unlock temporary ad-free access.", "settings-info-main-app-settings": "Language, app behavior, and quick access tools.", "settings-info-main-backup-restore": "Export settings to a backup or restore them later.", "settings-info-main-changelog": "See recent updates and release notes.", diff --git a/src/lang/ko-kr.json b/src/lang/ko-kr.json index b9e3d36..5ef86fb 100644 --- a/src/lang/ko-kr.json +++ b/src/lang/ko-kr.json @@ -519,7 +519,6 @@ "save file before home shortcut": "Save the file before adding it to the home screen.", "terminal_required_message_for_lsp": "Terminal not installed. Please install Terminal first to use LSP servers.", "shift click selection": "Shift + tap/click selection", - "earn ad-free time": "Earn ad-free time", "indent guides": "Indent guides", "language servers": "Language servers", "lint gutter": "Show lint gutter", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "Remove installed packages or binaries for this server.", "settings-info-lsp-update-server": "Update this language server if an update flow is available.", "settings-info-lsp-view-init-options": "View the effective initialization options as JSON.", - "settings-info-main-ad-rewards": "Watch ads to unlock temporary ad-free access.", "settings-info-main-app-settings": "Language, app behavior, and quick access tools.", "settings-info-main-backup-restore": "Export settings to a backup or restore them later.", "settings-info-main-changelog": "See recent updates and release notes.", diff --git a/src/lang/ln-ln.json b/src/lang/ln-ln.json index f344ba0..8f565c1 100644 --- a/src/lang/ln-ln.json +++ b/src/lang/ln-ln.json @@ -514,7 +514,6 @@ "save file before home shortcut": "Bomba fichier liboso ya kobakisa yango na écran d'accueil.", "terminal_required_message_for_lsp": "Terminal ezali installed te. Install terminal liboso mpo na kosalela ba serveurs LSP.", "shift click selection": "Poná na Shift + click", - "earn ad-free time": "Zwa ntango kozanga bapub", "indent guides": "Ba guide ya kokɔtisa molɔngɔ", "language servers": "Ba serveurs ya monoko", "lint gutter": "Lakisa ba erreurs ya lint", @@ -684,7 +683,6 @@ "settings-info-lsp-uninstall-server": "Longola ba paquets to ba fichiers exécutables oyo ebombami mpo na serveur oyo.", "settings-info-lsp-update-server": "Kobongisa serveur oyo ya monoko soki lolenge ya kobongisa ezali.", "settings-info-lsp-view-init-options": "Tala ba options ya kobanda oyo ezali kosala lokola JSON.", - "settings-info-main-ad-rewards": "Tala ba publicité mpo na kozwa accès sans publicité mpo na mwa tango.", "settings-info-main-app-settings": "Monoko, ndenge application esalaka mpe ba outils ya accès rapide.", "settings-info-main-backup-restore": "Bimisa ba paramɛtrɛ na backup to zongisa yango sima.", "settings-info-main-changelog": "Tala ba mbongwana ya sika mpe ba notes ya version.", diff --git a/src/lang/ml-in.json b/src/lang/ml-in.json index 6e12d8b..6f967cf 100644 --- a/src/lang/ml-in.json +++ b/src/lang/ml-in.json @@ -519,7 +519,6 @@ "save file before home shortcut": "Save the file before adding it to the home screen.", "terminal_required_message_for_lsp": "Terminal not installed. Please install Terminal first to use LSP servers.", "shift click selection": "Shift + tap/click selection", - "earn ad-free time": "Earn ad-free time", "indent guides": "Indent guides", "language servers": "Language servers", "lint gutter": "Show lint gutter", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "Remove installed packages or binaries for this server.", "settings-info-lsp-update-server": "Update this language server if an update flow is available.", "settings-info-lsp-view-init-options": "View the effective initialization options as JSON.", - "settings-info-main-ad-rewards": "Watch ads to unlock temporary ad-free access.", "settings-info-main-app-settings": "Language, app behavior, and quick access tools.", "settings-info-main-backup-restore": "Export settings to a backup or restore them later.", "settings-info-main-changelog": "See recent updates and release notes.", diff --git a/src/lang/mm-unicode.json b/src/lang/mm-unicode.json index fa13060..1b87a91 100644 --- a/src/lang/mm-unicode.json +++ b/src/lang/mm-unicode.json @@ -519,7 +519,6 @@ "save file before home shortcut": "Save the file before adding it to the home screen.", "terminal_required_message_for_lsp": "Terminal not installed. Please install Terminal first to use LSP servers.", "shift click selection": "Shift + tap/click selection", - "earn ad-free time": "Earn ad-free time", "indent guides": "Indent guides", "language servers": "Language servers", "lint gutter": "Show lint gutter", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "Remove installed packages or binaries for this server.", "settings-info-lsp-update-server": "Update this language server if an update flow is available.", "settings-info-lsp-view-init-options": "View the effective initialization options as JSON.", - "settings-info-main-ad-rewards": "Watch ads to unlock temporary ad-free access.", "settings-info-main-app-settings": "Language, app behavior, and quick access tools.", "settings-info-main-backup-restore": "Export settings to a backup or restore them later.", "settings-info-main-changelog": "See recent updates and release notes.", diff --git a/src/lang/mm-zawgyi.json b/src/lang/mm-zawgyi.json index 9313949..0eda851 100644 --- a/src/lang/mm-zawgyi.json +++ b/src/lang/mm-zawgyi.json @@ -519,7 +519,6 @@ "save file before home shortcut": "Save the file before adding it to the home screen.", "terminal_required_message_for_lsp": "Terminal not installed. Please install Terminal first to use LSP servers.", "shift click selection": "Shift + tap/click selection", - "earn ad-free time": "Earn ad-free time", "indent guides": "Indent guides", "language servers": "Language servers", "lint gutter": "Show lint gutter", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "Remove installed packages or binaries for this server.", "settings-info-lsp-update-server": "Update this language server if an update flow is available.", "settings-info-lsp-view-init-options": "View the effective initialization options as JSON.", - "settings-info-main-ad-rewards": "Watch ads to unlock temporary ad-free access.", "settings-info-main-app-settings": "Language, app behavior, and quick access tools.", "settings-info-main-backup-restore": "Export settings to a backup or restore them later.", "settings-info-main-changelog": "See recent updates and release notes.", diff --git a/src/lang/pl-pl.json b/src/lang/pl-pl.json index f364139..cdf07a4 100644 --- a/src/lang/pl-pl.json +++ b/src/lang/pl-pl.json @@ -519,7 +519,6 @@ "save file before home shortcut": "Save the file before adding it to the home screen.", "terminal_required_message_for_lsp": "Terminal not installed. Please install Terminal first to use LSP servers.", "shift click selection": "Shift + tap/click selection", - "earn ad-free time": "Earn ad-free time", "indent guides": "Indent guides", "language servers": "Language servers", "lint gutter": "Show lint gutter", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "Remove installed packages or binaries for this server.", "settings-info-lsp-update-server": "Update this language server if an update flow is available.", "settings-info-lsp-view-init-options": "View the effective initialization options as JSON.", - "settings-info-main-ad-rewards": "Watch ads to unlock temporary ad-free access.", "settings-info-main-app-settings": "Language, app behavior, and quick access tools.", "settings-info-main-backup-restore": "Export settings to a backup or restore them later.", "settings-info-main-changelog": "See recent updates and release notes.", diff --git a/src/lang/pt-br.json b/src/lang/pt-br.json index 2e6ef31..d8f771b 100644 --- a/src/lang/pt-br.json +++ b/src/lang/pt-br.json @@ -519,7 +519,6 @@ "save file before home shortcut": "Save the file before adding it to the home screen.", "terminal_required_message_for_lsp": "Terminal not installed. Please install Terminal first to use LSP servers.", "shift click selection": "Shift + tap/click selection", - "earn ad-free time": "Earn ad-free time", "indent guides": "Indent guides", "language servers": "Language servers", "lint gutter": "Show lint gutter", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "Remove installed packages or binaries for this server.", "settings-info-lsp-update-server": "Update this language server if an update flow is available.", "settings-info-lsp-view-init-options": "View the effective initialization options as JSON.", - "settings-info-main-ad-rewards": "Watch ads to unlock temporary ad-free access.", "settings-info-main-app-settings": "Language, app behavior, and quick access tools.", "settings-info-main-backup-restore": "Export settings to a backup or restore them later.", "settings-info-main-changelog": "See recent updates and release notes.", diff --git a/src/lang/pu-in.json b/src/lang/pu-in.json index de1f679..8f7d334 100644 --- a/src/lang/pu-in.json +++ b/src/lang/pu-in.json @@ -519,7 +519,6 @@ "save file before home shortcut": "Save the file before adding it to the home screen.", "terminal_required_message_for_lsp": "Terminal not installed. Please install Terminal first to use LSP servers.", "shift click selection": "Shift + tap/click selection", - "earn ad-free time": "Earn ad-free time", "indent guides": "Indent guides", "language servers": "Language servers", "lint gutter": "Show lint gutter", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "Remove installed packages or binaries for this server.", "settings-info-lsp-update-server": "Update this language server if an update flow is available.", "settings-info-lsp-view-init-options": "View the effective initialization options as JSON.", - "settings-info-main-ad-rewards": "Watch ads to unlock temporary ad-free access.", "settings-info-main-app-settings": "Language, app behavior, and quick access tools.", "settings-info-main-backup-restore": "Export settings to a backup or restore them later.", "settings-info-main-changelog": "See recent updates and release notes.", diff --git a/src/lang/ru-ru.json b/src/lang/ru-ru.json index 4d38706..e781f65 100644 --- a/src/lang/ru-ru.json +++ b/src/lang/ru-ru.json @@ -519,7 +519,6 @@ "save file before home shortcut": "Save the file before adding it to the home screen.", "terminal_required_message_for_lsp": "Terminal not installed. Please install Terminal first to use LSP servers.", "shift click selection": "Shift + tap/click selection", - "earn ad-free time": "Earn ad-free time", "indent guides": "Indent guides", "language servers": "Language servers", "lint gutter": "Show lint gutter", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "Remove installed packages or binaries for this server.", "settings-info-lsp-update-server": "Update this language server if an update flow is available.", "settings-info-lsp-view-init-options": "View the effective initialization options as JSON.", - "settings-info-main-ad-rewards": "Watch ads to unlock temporary ad-free access.", "settings-info-main-app-settings": "Language, app behavior, and quick access tools.", "settings-info-main-backup-restore": "Export settings to a backup or restore them later.", "settings-info-main-changelog": "See recent updates and release notes.", diff --git a/src/lang/tl-ph.json b/src/lang/tl-ph.json index e372890..0540198 100644 --- a/src/lang/tl-ph.json +++ b/src/lang/tl-ph.json @@ -519,7 +519,6 @@ "save file before home shortcut": "Save the file before adding it to the home screen.", "terminal_required_message_for_lsp": "Terminal not installed. Please install Terminal first to use LSP servers.", "shift click selection": "Shift + tap/click selection", - "earn ad-free time": "Earn ad-free time", "indent guides": "Indent guides", "language servers": "Language servers", "lint gutter": "Show lint gutter", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "Remove installed packages or binaries for this server.", "settings-info-lsp-update-server": "Update this language server if an update flow is available.", "settings-info-lsp-view-init-options": "View the effective initialization options as JSON.", - "settings-info-main-ad-rewards": "Watch ads to unlock temporary ad-free access.", "settings-info-main-app-settings": "Language, app behavior, and quick access tools.", "settings-info-main-backup-restore": "Export settings to a backup or restore them later.", "settings-info-main-changelog": "See recent updates and release notes.", diff --git a/src/lang/tr-tr.json b/src/lang/tr-tr.json index 0562d00..614f2f9 100644 --- a/src/lang/tr-tr.json +++ b/src/lang/tr-tr.json @@ -519,7 +519,6 @@ "save file before home shortcut": "Save the file before adding it to the home screen.", "terminal_required_message_for_lsp": "Terminal not installed. Please install Terminal first to use LSP servers.", "shift click selection": "Shift + tap/click selection", - "earn ad-free time": "Earn ad-free time", "indent guides": "Indent guides", "language servers": "Language servers", "lint gutter": "Show lint gutter", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "Remove installed packages or binaries for this server.", "settings-info-lsp-update-server": "Update this language server if an update flow is available.", "settings-info-lsp-view-init-options": "View the effective initialization options as JSON.", - "settings-info-main-ad-rewards": "Watch ads to unlock temporary ad-free access.", "settings-info-main-app-settings": "Language, app behavior, and quick access tools.", "settings-info-main-backup-restore": "Export settings to a backup or restore them later.", "settings-info-main-changelog": "See recent updates and release notes.", diff --git a/src/lang/uk-ua.json b/src/lang/uk-ua.json index 5a49d94..2b1194a 100644 --- a/src/lang/uk-ua.json +++ b/src/lang/uk-ua.json @@ -519,7 +519,6 @@ "save file before home shortcut": "Збережіть файл, перш ніж додавати його на головний екран.", "terminal_required_message_for_lsp": "Термінал не встановлено. Будь ласка, спочатку встановіть Термінал, щоб використовувати сервери LSP.", "shift click selection": "Shift + tap/click selection", - "earn ad-free time": "Earn ad-free time", "indent guides": "Indent guides", "language servers": "Language servers", "lint gutter": "Show lint gutter", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "Remove installed packages or binaries for this server.", "settings-info-lsp-update-server": "Update this language server if an update flow is available.", "settings-info-lsp-view-init-options": "View the effective initialization options as JSON.", - "settings-info-main-ad-rewards": "Watch ads to unlock temporary ad-free access.", "settings-info-main-app-settings": "Language, app behavior, and quick access tools.", "settings-info-main-backup-restore": "Export settings to a backup or restore them later.", "settings-info-main-changelog": "See recent updates and release notes.", diff --git a/src/lang/uz-uz.json b/src/lang/uz-uz.json index 2cdd2d3..4d30375 100644 --- a/src/lang/uz-uz.json +++ b/src/lang/uz-uz.json @@ -519,7 +519,6 @@ "save file before home shortcut": "Save the file before adding it to the home screen.", "terminal_required_message_for_lsp": "Terminal not installed. Please install Terminal first to use LSP servers.", "shift click selection": "Shift + tap/click selection", - "earn ad-free time": "Earn ad-free time", "indent guides": "Indent guides", "language servers": "Language servers", "lint gutter": "Show lint gutter", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "Remove installed packages or binaries for this server.", "settings-info-lsp-update-server": "Update this language server if an update flow is available.", "settings-info-lsp-view-init-options": "View the effective initialization options as JSON.", - "settings-info-main-ad-rewards": "Watch ads to unlock temporary ad-free access.", "settings-info-main-app-settings": "Language, app behavior, and quick access tools.", "settings-info-main-backup-restore": "Export settings to a backup or restore them later.", "settings-info-main-changelog": "See recent updates and release notes.", diff --git a/src/lang/vi-vn.json b/src/lang/vi-vn.json index 0894968..2abdf06 100644 --- a/src/lang/vi-vn.json +++ b/src/lang/vi-vn.json @@ -519,7 +519,6 @@ "save file before home shortcut": "Save the file before adding it to the home screen.", "terminal_required_message_for_lsp": "Terminal not installed. Please install Terminal first to use LSP servers.", "shift click selection": "Shift + tap/click selection", - "earn ad-free time": "Earn ad-free time", "indent guides": "Indent guides", "language servers": "Language servers", "lint gutter": "Show lint gutter", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "Remove installed packages or binaries for this server.", "settings-info-lsp-update-server": "Update this language server if an update flow is available.", "settings-info-lsp-view-init-options": "View the effective initialization options as JSON.", - "settings-info-main-ad-rewards": "Watch ads to unlock temporary ad-free access.", "settings-info-main-app-settings": "Language, app behavior, and quick access tools.", "settings-info-main-backup-restore": "Export settings to a backup or restore them later.", "settings-info-main-changelog": "See recent updates and release notes.", diff --git a/src/lang/zh-cn.json b/src/lang/zh-cn.json index 5e10cf0..f4840a5 100644 --- a/src/lang/zh-cn.json +++ b/src/lang/zh-cn.json @@ -519,7 +519,6 @@ "save file before home shortcut": "请先保存文件,再添加到主屏幕。", "terminal_required_message_for_lsp": "未安装终端。请先安装终端以使用 LSP 服务器。", "shift click selection": "Shift + 点击选择", - "earn ad-free time": "获取免广告时间", "indent guides": "缩进指示线", "language servers": "语言服务器", "lint gutter": "显示 Lint 标记栏", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "移除此服务器的已安装包或二进制文件。", "settings-info-lsp-update-server": "如果可用,更新此语言服务器。", "settings-info-lsp-view-init-options": "以 JSON 查看有效的初始化选项。", - "settings-info-main-ad-rewards": "观看广告以解锁临时免广告。", "settings-info-main-app-settings": "语言、应用行为和快捷工具。", "settings-info-main-backup-restore": "导出或恢复设置备份。", "settings-info-main-changelog": "查看最近更新和发布说明。", diff --git a/src/lang/zh-hant.json b/src/lang/zh-hant.json index 584d3cc..3deda30 100644 --- a/src/lang/zh-hant.json +++ b/src/lang/zh-hant.json @@ -519,7 +519,6 @@ "save file before home shortcut": "請先保存文件,再添加到主屏幕。", "terminal_required_message_for_lsp": "未安裝終端。請先安裝終端以使用 LSP 服務器。", "shift click selection": "Shift + 點擊選擇", - "earn ad-free time": "獲取免廣告時間", "indent guides": "縮進指示線", "language servers": "語言服務器", "lint gutter": "顯示 Lint 標記欄", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "移除此服務器的已安裝包或二進制文件。", "settings-info-lsp-update-server": "如果可用,更新此語言服務器。", "settings-info-lsp-view-init-options": "以 JSON 查看有效的初始化選項。", - "settings-info-main-ad-rewards": "觀看廣告以解鎖臨時免廣告。", "settings-info-main-app-settings": "語言、應用行為和快捷工具。", "settings-info-main-backup-restore": "導出或恢復設置備份。", "settings-info-main-changelog": "查看最近更新和發布說明。", diff --git a/src/lang/zh-tw.json b/src/lang/zh-tw.json index 15179b8..dcae509 100644 --- a/src/lang/zh-tw.json +++ b/src/lang/zh-tw.json @@ -519,7 +519,6 @@ "save file before home shortcut": "Save the file before adding it to the home screen.", "terminal_required_message_for_lsp": "Terminal not installed. Please install Terminal first to use LSP servers.", "shift click selection": "Shift + tap/click selection", - "earn ad-free time": "Earn ad-free time", "indent guides": "Indent guides", "language servers": "Language servers", "lint gutter": "Show lint gutter", @@ -689,7 +688,6 @@ "settings-info-lsp-uninstall-server": "Remove installed packages or binaries for this server.", "settings-info-lsp-update-server": "Update this language server if an update flow is available.", "settings-info-lsp-view-init-options": "View the effective initialization options as JSON.", - "settings-info-main-ad-rewards": "Watch ads to unlock temporary ad-free access.", "settings-info-main-app-settings": "Language, app behavior, and quick access tools.", "settings-info-main-backup-restore": "Export settings to a backup or restore them later.", "settings-info-main-changelog": "See recent updates and release notes.", diff --git a/src/lib/adConsentCoordinator.mjs b/src/lib/adConsentCoordinator.mjs index de88e63..8cf4495 100644 --- a/src/lib/adConsentCoordinator.mjs +++ b/src/lib/adConsentCoordinator.mjs @@ -23,8 +23,8 @@ function normalizePrivacyState(state) { /** * Coordinates UMP and ad initialization for one application launch. - * Consent is gathered once, ad initialization is idempotent, and a valid - * previous-session UMP state can be used when the network update fails. + * Successful consent collection is cached and ad initialization is idempotent. + * Valid previous-session UMP state can be used when the network update fails. */ export class AdConsentCoordinator { #privacy; @@ -47,7 +47,17 @@ export class AdConsentCoordinator { } start() { - return (this.#consentPromise ??= this.#gatherAndStart()); + this.#consentPromise ??= this.#gatherAndStart().then( + (state) => { + if (!state.canRequestAds) this.#consentPromise = undefined; + return state; + }, + (error) => { + this.#consentPromise = undefined; + throw error; + }, + ); + return this.#consentPromise.then(() => this.state); } showPrivacyOptions() { diff --git a/src/lib/adRewardBannerPolicy.mjs b/src/lib/adRewardBannerPolicy.mjs index bc78243..f997cda 100644 --- a/src/lib/adRewardBannerPolicy.mjs +++ b/src/lib/adRewardBannerPolicy.mjs @@ -45,7 +45,7 @@ export function syncRewardBannerSuppression( * getCurrentState:()=>T, * setCurrentState:(state:T)=>void, * setBannerSuppressed:(reason:string,suppressed:boolean)=>void, - * emitChange:(state:T)=>void, + * emitChange?:(state:T)=>void, * onRefreshError?:(error:unknown)=>void, * onListenerError?:(error:unknown)=>void, * onExpiryNotice?:(state:T)=>void, @@ -101,7 +101,7 @@ export function createRewardStateLifecycle({ syncRewardBannerSuppression(nextState, setBannerSuppressed, now()); try { - emitChange(nextState); + emitChange?.(nextState); } catch (error) { onListenerError(error); } diff --git a/src/lib/adRewards.js b/src/lib/adRewards.js index 459226d..87badcc 100644 --- a/src/lib/adRewards.js +++ b/src/lib/adRewards.js @@ -4,125 +4,10 @@ import { isRewardPassActive, } from "./adRewardBannerPolicy.mjs"; import config from "./config"; -import showRewardedAd, { - isRewardedAdSupported, - isWatchingRewardedAd, -} from "./rewardedAd"; import secureAdRewardState from "./secureAdRewardState"; import { setBannerSuppressed } from "./startAd"; -const ONE_HOUR = 60 * 60 * 1000; - -const OFFERS = [ - { - id: "quick", - title: "Quick pass", - description: "Watch 1 rewarded ad and pause ads for 1 hour.", - adsRequired: 1, - durationMs: ONE_HOUR, - accentClass: "is-quick", - }, - { - id: "focus", - title: "Focus block", - description: - "Watch 2 rewarded ads and pause ads for a random 4, 5, or 6 hours.", - adsRequired: 2, - minDurationMs: 4 * ONE_HOUR, - maxDurationMs: 6 * ONE_HOUR, - accentClass: "is-focus", - }, -]; - -let state = getDefaultState(); -let activeWatchPromise = null; -const listeners = new Set(); - -function getDefaultState() { - return { - adFreeUntil: 0, - lastExpiredRewardUntil: 0, - isActive: false, - remainingMs: 0, - redemptionsToday: 0, - remainingRedemptions: 3, - maxRedemptionsPerDay: 3, - maxActivePassMs: 10 * ONE_HOUR, - hasPendingExpiryNotice: false, - expiryNoticePendingUntil: 0, - canRedeem: true, - redeemDisabledReason: "", - }; -} - -function formatDuration(durationMs) { - const totalHours = Math.round(durationMs / ONE_HOUR); - if (totalHours < 1) return "less than 1 hour"; - if (totalHours === 1) return "1 hour"; - return `${totalHours} hours`; -} - -function formatDurationRange(minDurationMs, maxDurationMs) { - if (!minDurationMs || !maxDurationMs || minDurationMs === maxDurationMs) { - return formatDuration(minDurationMs || maxDurationMs || 0); - } - - const minHours = Math.round(minDurationMs / ONE_HOUR); - const maxHours = Math.round(maxDurationMs / ONE_HOUR); - return `${minHours}-${maxHours} hours`; -} - -function getExpiryDate() { - return state.adFreeUntil ? new Date(state.adFreeUntil) : null; -} - -function emitChange() { - const snapshot = { - ...state, - expiryDate: getExpiryDate(), - }; - listeners.forEach((listener) => { - try { - listener(snapshot); - } catch (error) { - console.error("Reward state listener failed.", error); - } - }); -} - -function notify(title, message, type = "info") { - toast(message, 4000); - window.acode?.pushNotification?.(title, message, { - icon: type === "success" ? "verified" : "notifications", - type, - }); -} - -function normalizeStatus(status) { - const fallback = getDefaultState(); - if (!status || typeof status !== "object") return fallback; - - const adFreeUntil = Number(status.adFreeUntil) || 0; - const remainingMs = Math.max(0, Number(status.remainingMs) || 0); - - return { - ...fallback, - ...status, - adFreeUntil, - lastExpiredRewardUntil: Number(status.lastExpiredRewardUntil) || 0, - remainingMs, - redemptionsToday: Number(status.redemptionsToday) || 0, - remainingRedemptions: Number(status.remainingRedemptions) || 0, - maxRedemptionsPerDay: - Number(status.maxRedemptionsPerDay) || fallback.maxRedemptionsPerDay, - maxActivePassMs: Number(status.maxActivePassMs) || fallback.maxActivePassMs, - expiryNoticePendingUntil: Number(status.expiryNoticePendingUntil) || 0, - isActive: Boolean(status.isActive && adFreeUntil > Date.now()), - hasPendingExpiryNotice: Boolean(status.hasPendingExpiryNotice), - canRedeem: Boolean(status.canRedeem), - redeemDisabledReason: String(status.redeemDisabledReason || ""), - }; -} +let state = normalizeStatus(); const rewardLifecycle = createRewardStateLifecycle({ loadStatus: () => secureAdRewardState.getStatus(), @@ -132,7 +17,6 @@ const rewardLifecycle = createRewardStateLifecycle({ state = nextState; }, setBannerSuppressed, - emitChange, onRefreshError: (error) => console.warn("Failed to refresh rewarded ad state.", error), onListenerError: (error) => @@ -140,180 +24,40 @@ const rewardLifecycle = createRewardStateLifecycle({ onExpiryNotice: () => { notify( "Ad-free pass ended", - "Your rewarded ad-free time has expired. You can watch another rewarded ad anytime.", + "Your rewarded ad-free time has expired. Ads will now resume.", "warning", ); }, }); -async function getRewardIdentity() { - try { - return String(user?.id || "Guest"); - } catch (error) { - console.warn("Failed to resolve rewarded ad user identity.", error); - return String(device?.uuid || "guest"); - } -} - -async function showRewardedStep(offer, step, sessionId) { - const earned = await showRewardedAd({ - serverSideVerification: { - userId: await getRewardIdentity(), - customData: [ - `session=${sessionId}`, - `offer=${offer.id}`, - `step=${step}`, - `ads=${offer.adsRequired}`, - ].join("&"), - }, - }); - if (!earned) throw new Error(strings["rewarded ad incomplete"]); -} - export default { async init() { await rewardLifecycle.initialize(); }, - onChange(listener) { - listeners.add(listener); - return () => listeners.delete(listener); - }, async handleResume() { await rewardLifecycle.resume(); }, - getState() { - return { - ...state, - expiryDate: getExpiryDate(), - }; - }, - getOffers() { - return OFFERS.map((offer) => ({ - ...offer, - durationLabel: formatDurationRange( - offer.minDurationMs || offer.durationMs, - offer.maxDurationMs || offer.durationMs, - ), - })); - }, - getRemainingMs() { - return Math.max(0, state.remainingMs || state.adFreeUntil - Date.now()); - }, - getRemainingLabel() { - const remainingMs = this.getRemainingMs(); - if (!remainingMs) return "No active ad-free pass"; - - const minutes = Math.ceil(remainingMs / (60 * 1000)); - if (minutes < 60) { - return `${minutes} minute${minutes === 1 ? "" : "s"} remaining`; - } - - const hours = Math.floor(minutes / 60); - const remMinutes = minutes % 60; - if (!remMinutes) { - return `${hours} hour${hours === 1 ? "" : "s"} remaining`; - } - - return `${hours}h ${remMinutes}m remaining`; - }, - getExpiryLabel() { - const expiryDate = getExpiryDate(); - if (!expiryDate) return "No active pass"; - return expiryDate.toLocaleString(); - }, isAdFreeActive() { return isRewardPassActive(state); }, canShowAds() { return Boolean(!config.HAS_PRO && !this.isAdFreeActive()); }, - isRewardedSupported() { - return isRewardedAdSupported(); - }, - getRewardedUnavailableReason() { - if (config.HAS_PRO) { - return "Ads are already disabled on this build."; - } - if (!isRewardedAdSupported()) { - return "Rewarded ads are unavailable on this device."; - } - return ""; - }, - canRedeemNow() { - return { - ok: Boolean(state.canRedeem), - reason: state.redeemDisabledReason || "", - }; - }, - isWatchingReward() { - return Boolean(activeWatchPromise) || isWatchingRewardedAd(); - }, - async watchOffer(offerId, { onStep } = {}) { - if (activeWatchPromise) { - return activeWatchPromise; - } - - const offer = OFFERS.find((item) => item.id === offerId); - if (!offer) { - throw new Error("Reward offer not found."); - } - if (!this.isRewardedSupported()) { - throw new Error(this.getRewardedUnavailableReason()); - } - - const sessionId = - typeof crypto?.randomUUID === "function" - ? crypto.randomUUID() - : `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`; - - activeWatchPromise = (async () => { - await rewardLifecycle.refresh({ notifyExpiry: false }); - const redemptionStatus = this.canRedeemNow(); - if (!redemptionStatus.ok) { - throw new Error(redemptionStatus.reason); - } - - for (let step = 1; step <= offer.adsRequired; step += 1) { - onStep?.({ - step, - totalSteps: offer.adsRequired, - offer, - }); - await showRewardedStep(offer, step, sessionId); - - if (step < offer.adsRequired) { - toast( - `Reward ${step}/${offer.adsRequired} complete. Loading the next ad...`, - 2500, - ); - } - } - - const redeemedState = rewardLifecycle.applyStatus( - await secureAdRewardState.redeem(offer.id), - ); - const grantedDurationMs = - Number(redeemedState.appliedDurationMs) || - Number(redeemedState.grantedDurationMs) || - 0; - - notify( - "Ad-free pass started", - `${formatDuration(grantedDurationMs)} unlocked. Ads will stay hidden until ${new Date(redeemedState.adFreeUntil).toLocaleString()}.`, - "success", - ); +}; - return { - offer, - expiresAt: redeemedState.adFreeUntil, - grantedDurationMs, - }; - })().finally(() => { - activeWatchPromise = null; - emitChange(); - }); +function normalizeStatus(status) { + const adFreeUntil = Number(status?.adFreeUntil) || 0; + return { + adFreeUntil, + isActive: Boolean(status?.isActive && adFreeUntil > Date.now()), + hasPendingExpiryNotice: Boolean(status?.hasPendingExpiryNotice), + }; +} - emitChange(); - return activeWatchPromise; - }, -}; +function notify(title, message, type = "info") { + toast(message, 4000); + window.acode?.pushNotification?.(title, message, { + icon: type === "success" ? "verified" : "notifications", + type, + }); +} diff --git a/src/lib/paid/rewardedAd.js b/src/lib/paid/rewardedAd.js index dd4e370..bdc94a7 100644 --- a/src/lib/paid/rewardedAd.js +++ b/src/lib/paid/rewardedAd.js @@ -2,10 +2,6 @@ export function isRewardedAdSupported() { return false; } -export function isWatchingRewardedAd() { - return false; -} - export default function showRewardedAd({ signal } = {}) { if (signal?.aborted) return Promise.resolve(false); return Promise.reject(new Error(strings["rewarded ad unavailable"])); diff --git a/src/lib/rewardedAd.js b/src/lib/rewardedAd.js index fdb69db..7867f06 100644 --- a/src/lib/rewardedAd.js +++ b/src/lib/rewardedAd.js @@ -7,7 +7,10 @@ import startAd, { } from "./startAd"; const RESULT_TIMEOUT_MS = 90_000; +const PRESENTATION_RECOVERY_MS = 10 * 60_000; +const RECOVERY_CALL_TIMEOUT_MS = 10_000; let active = false; +let retryActivePresentation; let nextId = 0; export function isRewardedAdSupported() { @@ -20,19 +23,22 @@ export function isRewardedAdSupported() { ); } -export function isWatchingRewardedAd() { - return active; -} - /** Show one reward, without granting an ad-free pass or applying its reward. */ export default function showRewardedAd({ serverSideVerification, signal, } = {}) { if (signal?.aborted) return Promise.resolve(false); - if (active || !isRewardedAdSupported()) { + if (!isRewardedAdSupported() || (active && !retryActivePresentation)) { return Promise.reject(new Error(strings["rewarded ad unavailable"])); } + if (active) { + return retryActivePresentation().then(() => { + if (signal?.aborted) return false; + if (active) throw new Error(strings["rewarded ad unavailable"]); + return showRewardedAd({ serverSideVerification, signal }); + }); + } active = true; return new Promise((resolve, reject) => { let earned = false; @@ -40,16 +46,24 @@ export default function showRewardedAd({ let presenting = false; let cleaned = false; const unsubscribe = []; - const timeout = setTimeout( - () => finish(new Error(strings["rewarded ad failed"])), - RESULT_TIMEOUT_MS, - ); + let timeout; + let recovery; + let recoveryAttempts = 0; + let recoveryRequest; + let recoveryDeadline; + let releaseRecovery; + let loaded = false; + let showAcknowledged = false; function cleanup() { // A cancelled/timed-out caller must not allow another full-screen ad // until the native ad actually dismisses (show() resolves on opening). if (presenting || cleaned) return; cleaned = true; + clearTimeout(recovery); + clearTimeout(recoveryDeadline); + releaseRecovery?.(); + retryActivePresentation = undefined; for (const off of unsubscribe.splice(0)) off(); active = false; } @@ -78,8 +92,20 @@ export default function showRewardedAd({ !initialized || !getPrivacyState().canRequestAds ) { - throw new Error(strings["rewarded ad unavailable"]); + finish(new Error(strings["rewarded ad unavailable"])); + return; } + timeout = setTimeout( + () => + finish( + new Error( + strings[ + loaded ? "rewarded ad failed" : "rewarded ad unavailable" + ], + ), + ), + RESULT_TIMEOUT_MS, + ); const ad = new admob.RewardedAd({ id: `acode-reward-${++nextId}`, adUnitId: adUnitIdRewarded, @@ -97,9 +123,14 @@ export default function showRewardedAd({ presenting = false; finish(new Error(strings["rewarded ad failed"])); }), - ad.on("loadfail", () => - finish(new Error(strings["rewarded ad failed"])), - ), + ad.on("loadfail", (error) => { + console.warn( + "Rewarded ad could not load", + error?.code, + error?.message, + ); + finish(new Error(strings["rewarded ad unavailable"])); + }), () => { void ad.destroy().catch((error) => { console.warn("Failed to destroy rewarded ad", error); @@ -108,14 +139,79 @@ export default function showRewardedAd({ ); await ad.load(); if (settled) return; + loaded = true; presenting = true; - if ((await ad.show()) === false) { + retryActivePresentation = () => { + if (!showAcknowledged && recoveryAttempts === 0) + return Promise.resolve(); + if (!recoveryRequest) recoveryAttempts = 0; + return recoverPresentation(); + }; + document.addEventListener("resume", resumeRecovery); + unsubscribe.push(() => + document.removeEventListener("resume", resumeRecovery), + ); + recovery = setTimeout(recoverPresentation, PRESENTATION_RECOVERY_MS); + const shown = await ad.show(); + showAcknowledged = true; + clearTimeout(timeout); + if (shown === false) { presenting = false; finish(new Error(strings["rewarded ad failed"])); } - })().catch(() => { + + function resumeRecovery() { + if (recoveryAttempts < 3 || recoveryRequest || !presenting || cleaned) + return; + recoveryAttempts = 0; + void recoverPresentation(); + } + + function recoverPresentation() { + if (!presenting || cleaned) return Promise.resolve(); + if (recoveryRequest) return recoveryRequest; + clearTimeout(recovery); + recoveryAttempts += 1; + const deadline = new Promise((resolve) => { + releaseRecovery = () => resolve(false); + recoveryDeadline = setTimeout( + releaseRecovery, + RECOVERY_CALL_TIMEOUT_MS, + ); + }); + recoveryRequest = Promise.race([ + Promise.resolve().then(() => ad.recoverPresentation()), + deadline, + ]) + .then((recovered) => { + if (!presenting || cleaned || !recovered) return; + presenting = false; + finish( + earned ? null : new Error(strings["rewarded ad failed"]), + earned && !signal?.aborted, + ); + }) + .catch(() => { + // A failed or timed-out check cannot prove dismissal. + }) + .finally(() => { + clearTimeout(recoveryDeadline); + releaseRecovery = undefined; + recoveryRequest = undefined; + if (presenting && !cleaned && recoveryAttempts < 3) { + recovery = setTimeout(recoverPresentation, 60_000); + } + }); + return recoveryRequest; + } + })().catch((error) => { + if (!settled) console.warn("Rewarded ad request failed", error); presenting = false; - finish(new Error(strings["rewarded ad failed"])); + finish( + new Error( + strings[loaded ? "rewarded ad failed" : "rewarded ad unavailable"], + ), + ); }); }); } diff --git a/src/lib/secureAdRewardState.js b/src/lib/secureAdRewardState.js index 51b05ee..5f5c14c 100644 --- a/src/lib/secureAdRewardState.js +++ b/src/lib/secureAdRewardState.js @@ -20,14 +20,4 @@ export default { return null; } }, - async redeem(offerId) { - try { - const raw = await execSystem("redeemReward", [offerId]); - if (!raw) return null; - return typeof raw === "string" ? JSON.parse(raw) : raw; - } catch (error) { - console.warn("Failed to redeem rewarded ad offer.", error); - throw error; - } - }, }; diff --git a/src/lib/startAd.js b/src/lib/startAd.js index 12b10d9..dd1ea51 100644 --- a/src/lib/startAd.js +++ b/src/lib/startAd.js @@ -20,6 +20,7 @@ export let bannerAd = null; /** @type {import("native/admob").InterstitialAd} */ export let interstitialAd = null; let consentCoordinator = null; +let nextAutomaticRetry = 0; export default async function startAd() { if (!canUseAdmob()) { @@ -79,15 +80,33 @@ function canUseAdmob() { } function getConsentCoordinator() { - consentCoordinator ??= new AdConsentCoordinator({ - privacy: admob.privacy, - initializeAds, - onError: (error) => - console.warn("Unable to refresh AdMob consent information:", error), - }); + if (!consentCoordinator) { + consentCoordinator = new AdConsentCoordinator({ + privacy: admob.privacy, + initializeAds, + onError: (error) => + console.warn("Unable to refresh AdMob consent information:", error), + }); + document.addEventListener("resume", retryAdStartup); + window.addEventListener("online", retryAdStartup); + } return consentCoordinator; } +function retryAdStartup() { + if ( + initialized || + !canUseAdmob() || + document.hidden || + navigator.onLine === false || + getPrivacyState().consentStatus === "required" || + Date.now() < nextAutomaticRetry + ) + return; + nextAutomaticRetry = Date.now() + 30_000; + void startAd(); +} + async function initializeAds() { if (initialized) return; await admob.start(); diff --git a/src/native/admob/ads/rewarded.ts b/src/native/admob/ads/rewarded.ts index 8f8808e..cfc87e5 100644 --- a/src/native/admob/ads/rewarded.ts +++ b/src/native/admob/ads/rewarded.ts @@ -1,3 +1,4 @@ +import { execAsync } from "../common"; import { MobileAd, type MobileAdOptions } from "./base"; export interface ServerSideVerificationOptions { @@ -24,7 +25,14 @@ export class RewardedAd extends MobileAd { return super.show(); } - /** Release an Android rewarded ad after dismissal or before presentation. */ + /** Recover a missed dismissal only after native foreground checks. */ + public recoverPresentation(): Promise { + return execAsync("adRecoverPresentation", [ + { id: this.id }, + ]) as Promise; + } + + /** Release a rewarded ad after dismissal or before presentation. */ public destroy() { return super.destroy(); } diff --git a/src/native/admob/common.ts b/src/native/admob/common.ts index da94783..8a2677c 100644 --- a/src/native/admob/common.ts +++ b/src/native/admob/common.ts @@ -6,6 +6,7 @@ export type NativeAction = | "adHide" | "adIsLoaded" | "adLoad" + | "adRecoverPresentation" | "adShow" | "bannerConfig" | "configure" @@ -63,6 +64,11 @@ type MaxAdContentRating = | /** Content suitable for teen and older audiences. */ "T" | /** Content suitability is unspecified. */ ""; +/** + * On iOS, either age flag being true selects Google's child age treatment. + * Omitted/null flags retain their previous values; both false clear treatment. + * See https://developers.google.com/admob/ios/targeting#migrate_to_age_treatment_from_tfcd_and_tfua + */ export interface RequestConfig { maxAdContentRating?: MaxAdContentRating; tagForChildDirectedTreatment?: boolean | null; diff --git a/src/native/globals.d.ts b/src/native/globals.d.ts index 2e12202..97445eb 100644 --- a/src/native/globals.d.ts +++ b/src/native/globals.d.ts @@ -13,8 +13,6 @@ declare global { const ADMOB_BANNER_ID: string; const ADMOB_INTERSTITIAL_ID: string; const ADMOB_REWARDED_ID: string; - const ADMOB_ACADEMY_REWARDED_ID: string; - const ADMOB_ACADEMY_INTERSTITIAL_ID: string; const ADMOB_APP_OPEN_ID: string; interface Window { toast: typeof import("../components/toast").default; diff --git a/src/native/system.ts b/src/native/system.ts index 243a55b..b194eb4 100644 --- a/src/native/system.ts +++ b/src/native/system.ts @@ -81,13 +81,6 @@ const api = { ) { exec(success, error, "getRewardStatus", []); }, - redeemReward( - offerId: string, - success: (status: string | RewardStatus) => void, - error: OnFail, - ) { - exec(success, error, "redeemReward", [offerId]); - }, extractAsset( assetName: string, destinationPath: string, diff --git a/src/native/types/system.d.ts b/src/native/types/system.d.ts index 7023484..7ffda21 100644 --- a/src/native/types/system.d.ts +++ b/src/native/types/system.d.ts @@ -291,11 +291,6 @@ interface System { onSuccess: (status: RewardStatus | string) => void, onFail: OnFail, ): void; - redeemReward( - offerId: string, - onSuccess: (status: RewardStatus | string) => void, - onFail: OnFail, - ): void; /** * Enable/disable native WebView long-press context behavior. * Use this when rendering a custom editor context menu. diff --git a/src/pages/adRewards/adRewards.scss b/src/pages/adRewards/adRewards.scss deleted file mode 100644 index caadfa1..0000000 --- a/src/pages/adRewards/adRewards.scss +++ /dev/null @@ -1,257 +0,0 @@ -#ad-rewards-page { - padding: 16px; - max-width: 600px; - margin: 0 auto; - color: var(--primary-text-color); - - .reward-hero { - margin-bottom: 20px; - - .hero-copy { - margin-bottom: 16px; - - .eyebrow { - display: inline-flex; - align-items: center; - padding: 4px 10px; - border-radius: 6px; - background: color-mix(in srgb, - var(--active-color) 15%, - transparent); - color: var(--active-color); - font-size: 0.72rem; - font-weight: 600; - letter-spacing: 0.05em; - text-transform: uppercase; - } - - h1 { - margin: 10px 0 6px; - font-size: 1.2rem; - font-weight: 700; - line-height: 1.3; - } - - p { - margin: 0; - font-size: 0.85rem; - color: color-mix(in srgb, - var(--primary-text-color) 60%, - transparent); - line-height: 1.5; - } - } - - .reward-status { - padding: 12px 14px; - display: flex; - align-items: center; - gap: 12px; - flex-wrap: wrap; - background: color-mix(in srgb, - var(--primary-color) 10%, - transparent); - border-radius: 10px; - border: 1px solid var(--border-color); - transition: all 0.2s ease; - - &.is-active { - border-color: color-mix(in srgb, - var(--active-color) 50%, - transparent); - background: color-mix(in srgb, - var(--active-color) 10%, - transparent); - } - - .status-label { - font-size: 0.72rem; - font-weight: 600; - text-transform: uppercase; - letter-spacing: 0.04em; - color: color-mix(in srgb, - var(--primary-text-color) 55%, - transparent); - } - - .status-value { - font-size: 0.9rem; - font-weight: 700; - flex: 1; - min-width: 0; - } - - .status-note { - font-size: 0.78rem; - color: color-mix(in srgb, - var(--primary-text-color) 55%, - transparent); - width: 100%; - } - - .status-subnote { - font-size: 0.74rem; - color: color-mix(in srgb, - var(--primary-text-color) 50%, - transparent); - width: 100%; - } - } - } - - .reward-grid { - display: grid; - grid-template-columns: repeat(2, 1fr); - gap: 10px; - margin-bottom: 20px; - } - - .reward-offer { - background: color-mix(in srgb, - var(--popup-background-color) 20%, - transparent); - border-radius: 12px; - border: 1px solid var(--border-color); - padding: 14px; - display: flex; - flex-direction: column; - gap: 8px; - transition: border-color 0.2s ease; - - &.is-focus { - border-color: color-mix(in srgb, - var(--link-text-color) 50%, - transparent); - } - - &.is-upgrade { - border-color: color-mix(in srgb, - var(--button-background-color) 40%, - transparent); - } - - .offer-header { - display: flex; - justify-content: space-between; - align-items: flex-start; - gap: 8px; - } - - .offer-kicker { - font-size: 0.68rem; - font-weight: 600; - text-transform: uppercase; - letter-spacing: 0.04em; - color: color-mix(in srgb, - var(--primary-text-color) 55%, - transparent); - } - - h2 { - margin: 3px 0 0; - font-size: 0.88rem; - font-weight: 600; - } - - .offer-duration { - padding: 3px 8px; - border-radius: 6px; - background: var(--primary-color); - color: var(--primary-text-color); - font-size: 0.68rem; - font-weight: 600; - white-space: nowrap; - align-self: flex-start; - } - - p { - margin: 0; - color: color-mix(in srgb, - var(--primary-text-color) 60%, - transparent); - line-height: 1.45; - font-size: 0.8rem; - flex: 1; - } - - .offer-limit { - font-size: 0.74rem; - line-height: 1.4; - color: color-mix(in srgb, - var(--primary-text-color) 55%, - transparent); - } - } - - .offer-action { - appearance: none; - border: 0; - border-radius: 8px; - padding: 9px 12px; - font: inherit; - font-size: 0.82rem; - font-weight: 600; - background: var(--button-background-color); - color: var(--button-text-color); - cursor: pointer; - transition: all 0.2s ease; - - &:active { - transform: translateY(1px); - opacity: 0.9; - } - - &:disabled { - opacity: 0.45; - cursor: not-allowed; - } - - &.secondary { - background: var(--primary-color); - color: var(--primary-text-color); - } - } - - .reward-notes { - display: grid; - gap: 10px; - - .note-card { - padding: 12px 14px; - border-left: 3px solid var(--active-color); - border-radius: 0 8px 8px 0; - background: color-mix(in srgb, - var(--primary-color) 8%, - transparent); - - h3 { - margin: 0 0 4px; - font-size: 0.82rem; - font-weight: 600; - } - - p { - margin: 0; - line-height: 1.45; - font-size: 0.78rem; - color: color-mix(in srgb, - var(--primary-text-color) 60%, - transparent); - } - } - } -} - - @supports not (gap: 1px) { - .reward-status > * + * { margin-left: 12px; } - .reward-grid > * { margin-right: 10px; margin-bottom: 10px; } - .reward-offer > * + * { margin-top: 8px; } - .offer-header > * + * { margin-left: 8px; } - .reward-notes > * + * { margin-top: 10px; } - } - -@media (max-width: 400px) { - #ad-rewards-page .reward-grid { - grid-template-columns: 1fr; - } -} diff --git a/src/pages/adRewards/index.js b/src/pages/adRewards/index.js deleted file mode 100644 index 98b80c4..0000000 --- a/src/pages/adRewards/index.js +++ /dev/null @@ -1,186 +0,0 @@ -import "./adRewards.scss"; - -import Page from "components/page"; -import loader from "dialogs/loader"; -import actionStack from "lib/actionStack"; -import adRewards from "lib/adRewards"; -import removeAds from "lib/removeAds"; -import helpers from "utils/helpers"; - -let $rewardPage = null; - -export default function openAdRewardsPage() { - if ($rewardPage) { - $rewardPage.show?.(); - return $rewardPage; - } - - const $page = Page("Ad-free passes"); - - function render() { - const rewardState = adRewards.getState(); - const rewardedSupported = adRewards.isRewardedSupported(); - const unavailableReason = adRewards.getRewardedUnavailableReason(); - const offers = adRewards.getOffers(); - const isBusy = adRewards.isWatchingReward(); - const redemptionStatus = adRewards.canRedeemNow(); - const rewardDisabledReason = !rewardedSupported - ? unavailableReason - : !redemptionStatus.ok - ? redemptionStatus.reason - : ""; - - $page.body = ( -
-
-
-
Rewarded ads
-

Trade a short ad break for focused coding time.

-

- Unlock temporary ad-free time without leaving the free version. - When your pass expires, Acode will show a toast and add a - notification in-app. -

-
-
-
- {rewardState.isActive ? "Ad-free active" : "No active pass"} -
-
- {rewardState.isActive - ? adRewards.getRemainingLabel() - : "Watch a rewarded ad to start a pass"} -
-
- {rewardState.isActive - ? `Expires ${adRewards.getExpiryLabel()}` - : "Passes stack on top of any active rewarded time."} -
-
- {rewardState.redemptionsToday}/{rewardState.maxRedemptionsPerDay}{" "} - rewards used today -
-
-
- -
- {offers.map((offer) => ( -
-
-
-
- {offer.adsRequired} rewarded ad - {offer.adsRequired > 1 ? "s" : ""} -
-

{offer.title}

-
-
{offer.durationLabel}
-
-

{offer.description}

- -
- {rewardDisabledReason || - `${rewardState.remainingRedemptions} of ${rewardState.maxRedemptionsPerDay} rewards left today`} -
-
- ))} - -
-
-
-
Permanent option
-

Remove ads for good

-
-
One purchase
-
-

- If you use Acode daily, Pro still gives the cleanest experience. -

- -
-
- -
-
-

How it works

-

- Rewarded passes hide your banners and interstitials until the - timer ends. If you already have time left, new rewards extend the - expiry. -

-
-
-

Limits

-

- You can redeem up to {rewardState.maxRedemptionsPerDay} rewards - per day, and your active ad-free pass is capped at 10 hours. -

-
-
-
- ); - } - - async function purchaseRemoveAds() { - try { - loader.showTitleLoader(); - await removeAds(); - $page.hide(); - } catch (error) { - helpers.error(error); - } finally { - loader.removeTitleLoader(); - } - } - - async function watchOffer(offerId) { - try { - render(); - await adRewards.watchOffer(offerId); - } catch (error) { - helpers.error(error); - } finally { - render(); - } - } - - const unsubscribe = adRewards.onChange(() => { - if ($page.isConnected) { - render(); - } - }); - - $page.onhide = () => { - unsubscribe(); - actionStack.remove("ad-rewards"); - $rewardPage = null; - }; - - actionStack.push({ - id: "ad-rewards", - action: $page.hide, - }); - - render(); - app.append($page); - $rewardPage = $page; - - return $page; -} diff --git a/src/pages/appIconSetting/appIconSetting.js b/src/pages/appIconSetting/appIconSetting.js index 7d3f32a..379983c 100644 --- a/src/pages/appIconSetting/appIconSetting.js +++ b/src/pages/appIconSetting/appIconSetting.js @@ -67,8 +67,12 @@ export default function appIconSetting() { if (loading === value) return; loading = value; $dialog.inert = value; - if (value) loader.create(strings["app icon"], strings["loading..."]); - else loader.destroy(); + if (value) { + loader.create(strings["app icon"], strings["loading..."], { + timeout: 1_000, + oncancel: close, + }); + } else loader.destroy(); }, onChange: close, }; diff --git a/src/settings/mainSettings.js b/src/settings/mainSettings.js index fbf132b..15c3725 100644 --- a/src/settings/mainSettings.js +++ b/src/settings/mainSettings.js @@ -13,7 +13,6 @@ import { requestProPurchase, restorePurchases } from "lib/removeAds"; import appSettings from "lib/settings"; import settings from "lib/settings"; import { showPrivacyOptions, subscribePrivacyState } from "lib/startAd"; -import openAdRewardsPage from "pages/adRewards"; import appIconSetting, { preloadAppIconSetting } from "pages/appIconSetting"; import Changelog from "pages/changelog/changelog"; import plugins from "pages/plugins"; @@ -203,14 +202,7 @@ export default function mainSettings() { ? "iap-pro-purchase-warning-ios" : "iap-pro-purchase-warning" ]; - items.push({ - key: "adRewards", - text: strings["earn ad-free time"], - icon: "play_arrow", - info: strings["settings-info-main-ad-rewards"], - category: categories.supportAcode, - chevron: true, - }); + items.push({ key: "removeads", text: strings["remove ads"], @@ -306,10 +298,6 @@ export default function mainSettings() { plugins(); break; - case "adRewards": - openAdRewardsPage(); - break; - case "formatter": formatterSettings(); break; diff --git a/tests/admob/adConsentCoordinator.test.js b/tests/admob/adConsentCoordinator.test.js index 7b1471b..a3d966e 100644 --- a/tests/admob/adConsentCoordinator.test.js +++ b/tests/admob/adConsentCoordinator.test.js @@ -240,3 +240,54 @@ test("preserves consent state when privacy options reject", async () => { assert.deepEqual(harness.coordinator.state, gatherState); assert.equal(harness.initializeCalls, 1); }); + +test("retries after first-launch offline consent becomes available", async () => { + const harness = createHarness({ gatherError: new Error("offline") }); + await harness.coordinator.start(); + assert.equal(harness.initializeCalls, 0); + harness.privacy.gatherConsent = async () => ({ + consentStatus: "notRequired", + canRequestAds: true, + }); + await harness.coordinator.start(); + assert.equal(harness.initializeCalls, 1); +}); + +test("retries a failed native startup without keeping a rejected promise", async () => { + let attempts = 0; + const coordinator = new AdConsentCoordinator({ + privacy: { + gatherConsent: async () => ({ + consentStatus: "notRequired", + canRequestAds: true, + }), + }, + initializeAds: async () => { + if (++attempts === 1) throw new Error("ATT interrupted"); + }, + }); + await assert.rejects(coordinator.start(), /ATT interrupted/); + await coordinator.start(); + assert.equal(attempts, 2); +}); + +test("cached startup returns current privacy choices without recollecting consent", async () => { + const allowed = { + consentStatus: "obtained", + canRequestAds: true, + privacyOptionsRequired: true, + }; + const revoked = { ...allowed, canRequestAds: false }; + const harness = createHarness({ + gatherState: allowed, + showOptions: async () => revoked, + }); + await harness.coordinator.start(); + await harness.coordinator.showPrivacyOptions(); + const result = await harness.coordinator.start(); + assert.deepEqual(result, revoked); + result.canRequestAds = true; + assert.deepEqual(await harness.coordinator.start(), revoked); + assert.equal(harness.gatherCalls, 1); + assert.equal(harness.initializeCalls, 1); +}); diff --git a/tests/admob/adRewards.test.js b/tests/admob/adRewards.test.js index de4fb1f..e26444a 100644 --- a/tests/admob/adRewards.test.js +++ b/tests/admob/adRewards.test.js @@ -1,73 +1,46 @@ -import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { afterEach, expect, it, vi } from "vitest"; const mocks = vi.hoisted(() => ({ - show: vi.fn(), getStatus: vi.fn(), - redeem: vi.fn(), suppress: vi.fn(), + toast: vi.fn(), })); -vi.mock("components/toast", () => ({ default: vi.fn() })); +vi.mock("components/toast", () => ({ default: mocks.toast })); vi.mock("lib/config", () => ({ default: { HAS_PRO: false } })); -vi.mock("lib/rewardedAd", () => ({ - default: mocks.show, - isRewardedAdSupported: () => true, - isWatchingRewardedAd: () => false, -})); vi.mock("lib/startAd", () => ({ setBannerSuppressed: mocks.suppress })); vi.mock("lib/secureAdRewardState", () => ({ - default: { getStatus: mocks.getStatus, redeem: mocks.redeem }, + default: { getStatus: mocks.getStatus }, })); -let adRewards; -beforeEach(async () => { - vi.resetModules(); - vi.useFakeTimers(); - vi.clearAllMocks(); - vi.stubGlobal("window", {}); - vi.stubGlobal("user", { id: "test-user" }); - vi.stubGlobal("strings", { "rewarded ad incomplete": "Incomplete" }); - mocks.getStatus.mockResolvedValue({ canRedeem: true }); - mocks.show.mockResolvedValue(true); - mocks.redeem.mockResolvedValue({ - canRedeem: true, - isActive: true, - adFreeUntil: Date.now() + 3_600_000, - appliedDurationMs: 3_600_000, - }); - ({ default: adRewards } = await import("lib/adRewards")); -}); + afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); + vi.clearAllMocks(); }); -it("shares duplicate pass requests during status refresh and preserves step verification", async () => { - let refreshed; - mocks.getStatus.mockImplementationOnce( - () => - new Promise((resolve) => { - refreshed = resolve; - }), - ); - const first = adRewards.watchOffer("focus"); - const duplicate = adRewards.watchOffer("focus"); - refreshed({ canRedeem: true }); - await Promise.all([first, duplicate]); - expect(mocks.show).toHaveBeenCalledTimes(2); - const firstMetadata = mocks.show.mock.calls[0][0].serverSideVerification; - const secondMetadata = mocks.show.mock.calls[1][0].serverSideVerification; - expect(firstMetadata.userId).toBe("test-user"); - expect(firstMetadata.customData).toContain("&offer=focus&step=1&ads=2"); - expect(secondMetadata.customData).toBe( - firstMetadata.customData.replace("step=1", "step=2"), - ); - expect(mocks.redeem).toHaveBeenCalledExactlyOnceWith("focus"); +it("honors existing earned time, then resumes ads and announces expiry", async () => { + vi.resetModules(); + vi.useFakeTimers(); + vi.stubGlobal("window", {}); + mocks.getStatus + .mockResolvedValueOnce({ + isActive: true, + adFreeUntil: Date.now() + 3_600_000, + }) + .mockResolvedValue({ isActive: false, hasPendingExpiryNotice: true }); + const { default: adRewards } = await import("lib/adRewards"); + await adRewards.init(); expect(adRewards.isAdFreeActive()).toBe(true); -}); -it("never grants a pass for an incomplete reward and permits retry", async () => { - mocks.show.mockResolvedValueOnce(false); - await expect(adRewards.watchOffer("quick")).rejects.toThrow("Incomplete"); - expect(mocks.redeem).not.toHaveBeenCalled(); - expect(adRewards.isWatchingReward()).toBe(false); - await adRewards.watchOffer("quick"); - expect(mocks.redeem).toHaveBeenCalledExactlyOnceWith("quick"); + expect(adRewards.canShowAds()).toBe(false); + expect(mocks.suppress).toHaveBeenLastCalledWith("rewarded-pass", true); + expect(mocks.toast).not.toHaveBeenCalled(); + + await vi.advanceTimersByTimeAsync(3_600_000); + expect(adRewards.isAdFreeActive()).toBe(false); + expect(adRewards.canShowAds()).toBe(true); + expect(mocks.suppress).toHaveBeenLastCalledWith("rewarded-pass", false); + expect(mocks.toast).toHaveBeenCalledExactlyOnceWith( + "Your rewarded ad-free time has expired. Ads will now resume.", + 4000, + ); }); diff --git a/tests/admob/iosAds.test.js b/tests/admob/iosAds.test.js index 0f890fd..65faa40 100644 --- a/tests/admob/iosAds.test.js +++ b/tests/admob/iosAds.test.js @@ -13,9 +13,19 @@ vi.mock("../../src/lib/bannerVisibilityController.mjs", () => ({ })); vi.mock("../../src/lib/config", () => ({ default: { HAS_PRO: false } })); -beforeEach(() => { +beforeEach(async () => { vi.resetModules(); - vi.stubGlobal("window", { ANDROID_SDK_INT: 0 }); + vi.stubGlobal( + "window", + Object.assign(new EventTarget(), { ANDROID_SDK_INT: 0 }), + ); + vi.stubGlobal( + "document", + Object.assign(new EventTarget(), { hidden: false }), + ); + vi.stubGlobal("navigator", { onLine: true }); + const config = await import("../../src/lib/config"); + config.default.HAS_PRO = false; vi.stubGlobal("Bridge", { platformId: "ios" }); vi.stubGlobal("BuildInfo", { buildType: "debug" }); setBuildConstants("ios", "Debug"); @@ -37,6 +47,7 @@ beforeEach(() => { }); }); afterEach(() => { + vi.restoreAllMocks(); vi.unstubAllGlobals(); vi.unstubAllEnvs(); vi.clearAllMocks(); @@ -123,6 +134,96 @@ test("runtime build metadata cannot replace compiled iOS production IDs", async }); }); +test.each([ + "online", + "resume", +])("recovers failed startup on %s and deduplicates repeated events", async (event) => { + if (event === "online") { + admob.privacy.gatherConsent.mockRejectedValueOnce(new Error("offline")); + admob.privacy.getState = vi + .fn() + .mockResolvedValue({ consentStatus: "unknown", canRequestAds: false }); + } else { + admob.start.mockRejectedValueOnce(new Error("ATT interrupted")); + } + const ads = await import("../../src/lib/startAd.js"); + await ads.default(); + expect(ads.initialized).toBe(false); + let finishConsent; + admob.privacy.gatherConsent.mockImplementationOnce( + () => + new Promise((resolve) => { + finishConsent = resolve; + }), + ); + const target = event === "online" ? window : document; + target.dispatchEvent(new Event(event)); + target.dispatchEvent(new Event(event)); + expect(admob.privacy.gatherConsent).toHaveBeenCalledTimes(2); + finishConsent({ consentStatus: "notRequired", canRequestAds: true }); + await vi.waitFor(() => expect(ads.initialized).toBe(true)); + expect(admob.BannerAd).toHaveBeenCalledOnce(); + expect(admob.InterstitialAd).toHaveBeenCalledOnce(); + window.dispatchEvent(new Event("online")); + document.dispatchEvent(new Event("resume")); + expect(admob.privacy.gatherConsent).toHaveBeenCalledTimes(2); +}); + +test("automatic recovery respects foreground, connectivity and Pro state", async () => { + admob.privacy.gatherConsent.mockResolvedValueOnce({ + consentStatus: "unknown", + canRequestAds: false, + }); + const ads = await import("../../src/lib/startAd.js"); + await ads.default(); + document.hidden = true; + window.dispatchEvent(new Event("online")); + document.hidden = false; + navigator.onLine = false; + document.dispatchEvent(new Event("resume")); + navigator.onLine = true; + const config = await import("../../src/lib/config"); + config.default.HAS_PRO = true; + document.dispatchEvent(new Event("resume")); + expect(admob.privacy.gatherConsent).toHaveBeenCalledOnce(); + expect(admob.BannerAd).not.toHaveBeenCalled(); +}); + +test("recovery does not reopen required consent forms but permits an explicit retry", async () => { + admob.privacy.gatherConsent.mockResolvedValueOnce({ + consentStatus: "required", + canRequestAds: false, + }); + const ads = await import("../../src/lib/startAd.js"); + await ads.default(); + window.dispatchEvent(new Event("online")); + document.dispatchEvent(new Event("resume")); + expect(admob.privacy.gatherConsent).toHaveBeenCalledOnce(); + await ads.default(); + expect(ads.initialized).toBe(true); + expect(admob.privacy.gatherConsent).toHaveBeenCalledTimes(2); +}); + +test("throttles automatic consent retries without delaying explicit user attempts", async () => { + const now = vi.spyOn(Date, "now").mockReturnValue(1_000); + admob.privacy.gatherConsent.mockResolvedValue({ + consentStatus: "unknown", + canRequestAds: false, + }); + const ads = await import("../../src/lib/startAd.js"); + await ads.default(); + window.dispatchEvent(new Event("online")); + for (let i = 0; i < 8; i++) await Promise.resolve(); + document.dispatchEvent(new Event("resume")); + expect(admob.privacy.gatherConsent).toHaveBeenCalledTimes(2); + now.mockReturnValue(31_000); + document.dispatchEvent(new Event("resume")); + for (let i = 0; i < 8; i++) await Promise.resolve(); + expect(admob.privacy.gatherConsent).toHaveBeenCalledTimes(3); + await ads.default(); + expect(admob.privacy.gatherConsent).toHaveBeenCalledTimes(4); +}); + function setBuildConstants(platform, mode) { const ids = getAdConfig(platform, mode); vi.stubGlobal("IS_IOS", platform === "ios"); diff --git a/tests/admob/rewardedAd.test.js b/tests/admob/rewardedAd.test.js index b963e8a..aa01f08 100644 --- a/tests/admob/rewardedAd.test.js +++ b/tests/admob/rewardedAd.test.js @@ -40,6 +40,7 @@ class Ad { load = vi.fn().mockResolvedValue(); show = vi.fn().mockResolvedValue(); destroy = vi.fn().mockResolvedValue(); + recoverPresentation = vi.fn().mockResolvedValue(false); } beforeEach(async () => { vi.resetModules(); @@ -51,6 +52,7 @@ beforeEach(async () => { mocks.platform.isIOS = false; mocks.start.mockReset().mockResolvedValue(); vi.stubGlobal("window", { ANDROID_SDK_INT: 36 }); + vi.stubGlobal("document", new EventTarget()); vi.stubGlobal("admob", { RewardedAd: Ad }); vi.stubGlobal("strings", { "rewarded ad unavailable": "Unavailable", @@ -140,7 +142,9 @@ describe("shared rewarded ad lifecycle", () => { const assertion = event === "dismiss" ? expect(result).resolves.toBe(false) - : expect(result).rejects.toThrow("Failed"); + : expect(result).rejects.toThrow( + event.startsWith("load") ? "Unavailable" : "Failed", + ); await flush(); instances[0].emit(event); await assertion; @@ -238,21 +242,273 @@ describe("shared rewarded ad lifecycle", () => { await next; vi.restoreAllMocks(); }); - it("rejects a presentation timeout and ignores late reward and dismissal", async () => { + it("releases the presentation lock if a cancelled show rejects late", async () => { + let rejectShow; + vi.spyOn(Ad.prototype, "on").mockImplementationOnce( + function (name, callback) { + this.show.mockImplementation( + () => + new Promise((resolve, reject) => { + rejectShow = reject; + }), + ); + this.listeners.set(name, callback); + return () => this.listeners.delete(name); + }, + ); + const controller = new AbortController(); + const result = showRewardedAd({ signal: controller.signal }); + await flush(); + controller.abort(); + await expect(result).resolves.toBe(false); + rejectShow(new Error("Presentation was interrupted")); + await flush(); + expect(instances[0].destroy).toHaveBeenCalledOnce(); + const retry = showRewardedAd(); + await flush(); + instances[1].emit("dismiss"); + await expect(retry).resolves.toBe(false); + }); + it("does not expire while a displayed ad is being watched or on its end card", async () => { const result = showRewardedAd(); - const assertion = expect(result).rejects.toThrow("Failed"); await flush(); - await vi.advanceTimersByTimeAsync(90_000); - await assertion; + await vi.advanceTimersByTimeAsync(180_000); await expect(showRewardedAd()).rejects.toThrow("Unavailable"); - expect(instances[0].destroy).not.toHaveBeenCalled(); instances[0].emit("reward"); instances[0].emit("dismiss"); - expect(instances[0].listeners.size).toBe(0); + await expect(result).resolves.toBe(true); + expect(vi.getTimerCount()).toBe(0); + }); + it.each([ + false, + true, + ])("recovers a missed dismissal without granting a reward (iOS: %s)", async (ios) => { + mocks.platform.isIOS = ios; + const result = showRewardedAd(); + const rejected = expect(result).rejects.toThrow("Failed"); + await flush(); + const ad = instances[0]; + ad.recoverPresentation.mockResolvedValue(true); + await vi.advanceTimersByTimeAsync(599_999); + expect(ad.recoverPresentation).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + await rejected; + expect(ad.destroy).toHaveBeenCalledOnce(); + expect(vi.getTimerCount()).toBe(0); + const next = showRewardedAd(); + await flush(); + instances[1].emit("dismiss"); + await expect(next).resolves.toBe(false); + }); + it("honors an earned reward only after native recovery confirms dismissal", async () => { + const result = showRewardedAd(); + await flush(); + const ad = instances[0]; + ad.emit("reward"); + ad.recoverPresentation.mockResolvedValue(false); + await vi.advanceTimersByTimeAsync(600_000); + expect(ad.destroy).not.toHaveBeenCalled(); + await expect(showRewardedAd()).rejects.toThrow("Unavailable"); + ad.recoverPresentation.mockResolvedValue(true); + await vi.advanceTimersByTimeAsync(60_000); + await expect(result).resolves.toBe(true); + expect(ad.destroy).toHaveBeenCalledOnce(); + }); + it("pauses visible-ad polling after three checks without unlocking and resumes safely", async () => { + const controller = new AbortController(); + const result = showRewardedAd({ signal: controller.signal }); + await flush(); + controller.abort(); + await result; + const ad = instances[0]; + await vi.advanceTimersByTimeAsync(3_600_000); + expect(ad.recoverPresentation).toHaveBeenCalledTimes(3); + expect(vi.getTimerCount()).toBe(0); + expect(ad.destroy).not.toHaveBeenCalled(); + expect(instances).toHaveLength(1); + ad.recoverPresentation.mockResolvedValue(true); + document.dispatchEvent(new Event("resume")); + await flush(); + expect(ad.destroy).toHaveBeenCalledOnce(); + }); + it("keeps the presentation lock until native recovery confirms dismissal after cancellation", async () => { + mocks.platform.isIOS = true; + const controller = new AbortController(); + const result = showRewardedAd({ signal: controller.signal }); + await flush(); + controller.abort(); + await expect(result).resolves.toBe(false); + const ad = instances[0]; + ad.recoverPresentation + .mockResolvedValueOnce(false) + .mockRejectedValueOnce(new Error("Bridge unavailable")) + .mockResolvedValue(true); + await vi.advanceTimersByTimeAsync(600_000); + expect(ad.destroy).not.toHaveBeenCalled(); + expect(instances).toHaveLength(1); + await vi.advanceTimersByTimeAsync(60_000); + expect(ad.destroy).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(60_000); + expect(ad.destroy).toHaveBeenCalledOnce(); + expect(vi.getTimerCount()).toBe(0); + }); + it("pauses recovery after three bridge errors and retries safely on resume", async () => { + const controller = new AbortController(); + const result = showRewardedAd({ signal: controller.signal }); + await flush(); + controller.abort(); + await result; + const ad = instances[0]; + ad.recoverPresentation.mockRejectedValue(new Error("Bridge unavailable")); + await vi.advanceTimersByTimeAsync(900_000); + expect(ad.recoverPresentation).toHaveBeenCalledTimes(3); + expect(vi.getTimerCount()).toBe(0); + expect(ad.destroy).not.toHaveBeenCalled(); + expect(instances).toHaveLength(1); + ad.recoverPresentation.mockResolvedValue(true); + document.dispatchEvent(new Event("resume")); + await flush(); + expect(ad.destroy).toHaveBeenCalledOnce(); + document.dispatchEvent(new Event("resume")); + expect(ad.recoverPresentation).toHaveBeenCalledTimes(4); + }); + it("does not recover while the first show request is still opening", async () => { + let acknowledge; + vi.spyOn(Ad.prototype, "on").mockImplementationOnce( + function (name, callback) { + this.show.mockImplementation( + () => + new Promise((resolve) => { + acknowledge = resolve; + }), + ); + this.listeners.set(name, callback); + return () => this.listeners.delete(name); + }, + ); + const previous = showRewardedAd(); + await flush(); + await expect(showRewardedAd()).rejects.toThrow("Unavailable"); + expect(instances[0].recoverPresentation).not.toHaveBeenCalled(); + acknowledge(); + await flush(); + instances[0].emit("dismiss"); + await expect(previous).resolves.toBe(false); + }); + it("recovers on the next user request after polling stops without a resume event", async () => { + const controller = new AbortController(); + const previous = showRewardedAd({ signal: controller.signal }); + await vi.advanceTimersByTimeAsync(0); + controller.abort(); + await previous; + await vi.advanceTimersByTimeAsync(3_600_000); + expect(instances[0].recoverPresentation).toHaveBeenCalledTimes(3); + instances[0].recoverPresentation.mockResolvedValue(true); + const next = showRewardedAd(); + await vi.advanceTimersByTimeAsync(0); + expect(instances).toHaveLength(2); + instances[1].emit("dismiss"); + await expect(next).resolves.toBe(false); + }); + it("bounds a hung recovery call and ignores its late success", async () => { + const controller = new AbortController(); + const previous = showRewardedAd({ signal: controller.signal }); + await vi.advanceTimersByTimeAsync(0); + controller.abort(); + await previous; + let complete; + const ad = instances[0]; + ad.recoverPresentation.mockImplementation( + () => + new Promise((resolve) => { + complete = resolve; + }), + ); + const next = showRewardedAd(); + const rejected = expect(next).rejects.toThrow("Unavailable"); + await vi.advanceTimersByTimeAsync(10_000); + await rejected; + complete(true); + await vi.advanceTimersByTimeAsync(0); + expect(ad.destroy).not.toHaveBeenCalled(); + expect(instances).toHaveLength(1); + ad.recoverPresentation.mockResolvedValue(true); + const retry = showRewardedAd(); + await vi.advanceTimersByTimeAsync(0); + expect(instances).toHaveLength(2); + instances[1].emit("dismiss"); + await expect(retry).resolves.toBe(false); + expect(vi.getTimerCount()).toBe(0); + }); + it("coalesces user recovery attempts and releases them on normal dismissal", async () => { + const previous = showRewardedAd(); + await vi.advanceTimersByTimeAsync(0); + const ad = instances[0]; + ad.recoverPresentation.mockImplementation(() => new Promise(() => {})); + const first = showRewardedAd(); + const second = showRewardedAd(); + const secondRejected = expect(second).rejects.toThrow("Unavailable"); + await vi.advanceTimersByTimeAsync(0); + expect(ad.recoverPresentation).toHaveBeenCalledOnce(); + ad.emit("dismiss"); + await expect(previous).resolves.toBe(false); + await vi.advanceTimersByTimeAsync(0); + await secondRejected; + expect(instances).toHaveLength(2); + instances[1].emit("dismiss"); + await expect(first).resolves.toBe(false); + expect(vi.getTimerCount()).toBe(0); + }); + it("reports expected unavailability without a warning", async () => { + const warn = vi.spyOn(console, "warn"); + mocks.allowed = false; + await expect(showRewardedAd()).rejects.toThrow("Unavailable"); + expect(warn).not.toHaveBeenCalled(); + }); + it("recovers the presentation lock when the show reply itself is lost", async () => { + mocks.platform.isIOS = true; + vi.spyOn(Ad.prototype, "on").mockImplementationOnce( + function (name, callback) { + this.show.mockImplementation(() => new Promise(() => {})); + this.recoverPresentation.mockResolvedValue(true); + this.listeners.set(name, callback); + return () => this.listeners.delete(name); + }, + ); + const result = showRewardedAd(); + const rejected = expect(result).rejects.toThrow("Failed"); + await vi.advanceTimersByTimeAsync(90_000); + await rejected; + expect(instances[0].destroy).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(510_000); expect(instances[0].destroy).toHaveBeenCalledOnce(); expect(vi.getTimerCount()).toBe(0); }); - it("times out initialization and never presents a late ad", async () => { + it("ignores a late recovery response after normal dismissal and a new ad", async () => { + mocks.platform.isIOS = true; + const result = showRewardedAd(); + await flush(); + let complete; + instances[0].recoverPresentation.mockImplementation( + () => + new Promise((resolve) => { + complete = resolve; + }), + ); + await vi.advanceTimersByTimeAsync(600_000); + instances[0].emit("dismiss"); + await expect(result).resolves.toBe(false); + const next = showRewardedAd(); + await flush(); + complete(true); + await flush(); + await expect(showRewardedAd()).rejects.toThrow("Unavailable"); + expect(instances[1].destroy).not.toHaveBeenCalled(); + instances[1].emit("dismiss"); + await next; + expect(vi.getTimerCount()).toBe(0); + }); + it("lets users finish privacy prompts without an ad timeout", async () => { let complete; mocks.start.mockImplementation( () => @@ -261,12 +517,38 @@ describe("shared rewarded ad lifecycle", () => { }), ); const result = showRewardedAd(); - const assertion = expect(result).rejects.toThrow("Failed"); + await vi.advanceTimersByTimeAsync(180_000); + expect(instances).toHaveLength(0); + expect(vi.getTimerCount()).toBe(0); + complete(); + await flush(); + instances[0].emit("reward"); + instances[0].emit("dismiss"); + await expect(result).resolves.toBe(true); + }); + it("times out a stalled load without showing or granting a late reward", async () => { + let complete; + vi.spyOn(Ad.prototype, "on").mockImplementationOnce( + function (name, callback) { + this.load.mockImplementation( + () => + new Promise((resolve) => { + complete = resolve; + }), + ); + this.listeners.set(name, callback); + return () => this.listeners.delete(name); + }, + ); + const result = showRewardedAd(); + const assertion = expect(result).rejects.toThrow("Unavailable"); + await flush(); await vi.advanceTimersByTimeAsync(90_000); await assertion; complete(); await flush(); - expect(instances).toHaveLength(0); + expect(instances[0].show).not.toHaveBeenCalled(); + expect(instances[0].destroy).toHaveBeenCalledOnce(); expect(vi.getTimerCount()).toBe(0); }); }); diff --git a/tests/unit/adBuildConfig.test.js b/tests/unit/adBuildConfig.test.js index 8ef3db1..b31de56 100644 --- a/tests/unit/adBuildConfig.test.js +++ b/tests/unit/adBuildConfig.test.js @@ -19,8 +19,6 @@ fs.writeFileSync( banner: ADMOB_BANNER_ID, interstitial: ADMOB_INTERSTITIAL_ID, rewarded: ADMOB_REWARDED_ID, - academyRewarded: ADMOB_ACADEMY_REWARDED_ID, - academyInterstitial: ADMOB_ACADEMY_INTERSTITIAL_ID, appOpen: ADMOB_APP_OPEN_ID, };`, ); diff --git a/tests/unit/alpineBuild.test.js b/tests/unit/alpineBuild.test.js new file mode 100644 index 0000000..01198b9 --- /dev/null +++ b/tests/unit/alpineBuild.test.js @@ -0,0 +1,96 @@ +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, expect, test } from "vitest"; + +const directories = []; +afterEach(() => { + for (const directory of directories.splice(0)) { + fs.rmSync(directory, { recursive: true, force: true }); + } +}); + +test("Alpine keeps unchanged builds incremental and rebuilds after an SDK change", () => { + const fixture = createFixture(); + fixture.run("/sdk/old"); + fixture.run("/sdk/old"); + expect(fixture.calls()).toHaveLength(1); + fs.writeFileSync(path.join(fixture.build, "old-sdk-object.o"), "stale"); + fixture.run("/sdk/new"); + expect(fixture.calls()).toHaveLength(2); + expect(fs.existsSync(path.join(fixture.build, "old-sdk-object.o"))).toBe( + false, + ); + expect( + fs.readFileSync(path.join(fixture.build, "configured-cross.ini"), "utf8"), + ).toContain("/sdk/new"); + fixture.run("/sdk/new"); + expect(fixture.calls()).toHaveLength(2); +}); + +test("Alpine repairs legacy caches and retries a failed reconfiguration", () => { + const fixture = createFixture(); + fs.mkdirSync(path.join(fixture.build, "meson-private"), { recursive: true }); + fs.writeFileSync(path.join(fixture.build, "build.ninja"), "legacy SDK cache"); + fixture.run("/sdk/current", true); + expect(fs.existsSync(path.join(fixture.build, "configured-cross.ini"))).toBe( + false, + ); + fixture.run("/sdk/current"); + expect(fixture.calls()).toHaveLength(2); + expect( + fs.readFileSync(path.join(fixture.build, "configured-cross.ini"), "utf8"), + ).toContain("/sdk/current"); +}); + +function createFixture() { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "acode-alpine-build-")); + directories.push(root); + const tools = path.join(root, "tools"); + const derived = path.join(root, "derived"); + const build = path.join(derived, "Alpine-iphonesimulator"); + const log = path.join(root, "setup.log"); + fs.mkdirSync(tools); + const stub = `#!${process.execPath} +const fs=require('fs'),path=require('path'); +const args=process.argv.slice(2),tool=path.basename(process.argv[1]); +if(tool==='meson') { + const build=args.find(arg=>arg.endsWith('/Alpine-iphonesimulator')); + const cross=args[args.indexOf('--cross-file')+1]; + fs.appendFileSync(process.env.SETUP_LOG,JSON.stringify(args)+'\\n'); + if(args.includes('--wipe')) fs.rmSync(build,{recursive:true,force:true}); + if(!fs.existsSync(cross)) throw Error('Wipe removed cross file'); + fs.mkdirSync(path.join(build,'meson-private'),{recursive:true}); + if(process.env.FAIL_SETUP==='1') process.exit(1); + fs.writeFileSync(path.join(build,'build.ninja'),'configured'); +} else if(tool==='ninja') { + const build=args[args.indexOf('-C')+1]; + fs.mkdirSync(path.join(build,'vdso/arm64'),{recursive:true}); + fs.writeFileSync(path.join(build,'vdso/arm64/libvdso.so.elf'),'fixture'); +} +`; + for (const name of ["shasum", "meson", "ninja", "ld.lld"]) { + fs.writeFileSync(path.join(tools, name), stub, { mode: 0o755 }); + } + return { + build, + calls: () => fs.readFileSync(log, "utf8").trim().split("\n"), + run(sdk, fail = false) { + const result = spawnSync("/bin/bash", ["platforms/ios/Alpine/build.sh"], { + encoding: "utf8", + env: { + PATH: `${tools}:/usr/bin:/bin`, + ACODE_BUILD_TOOLS: tools, + ACODE_LLD_BIN: tools, + SDKROOT: sdk, + DERIVED_FILE_DIR: derived, + PLATFORM_NAME: "iphonesimulator", + SETUP_LOG: log, + FAIL_SETUP: fail ? "1" : "0", + }, + }); + expect(result.status, result.stderr).toBe(fail ? 1 : 0); + }, + }; +} diff --git a/tests/unit/appIconSetting.test.js b/tests/unit/appIconSetting.test.js index e8b7922..8fa1222 100644 --- a/tests/unit/appIconSetting.test.js +++ b/tests/unit/appIconSetting.test.js @@ -304,6 +304,7 @@ it("opens one complete grid and closes only after native success, preserving the expect(h.loader.create).toHaveBeenCalledExactlyOnceWith( "App icon", "Loading...", + { timeout: 1_000, oncancel: expect.any(Function) }, ); expect(h.dialog.inert).toBe(true); expect(document.querySelector("#__loader button")).toBeNull(); @@ -664,3 +665,33 @@ it("wraps keyboard focus but lets Escape dismiss the top confirmation first", as vi.runAllTimers(); await h.closed; }); + +it("lets users cancel a stalled reward through the loading overlay and reopen the picker", async () => { + mocks.reward.mockImplementation( + ({ signal }) => + new Promise((resolve) => { + signal.addEventListener("abort", () => resolve(false), { once: true }); + }), + ); + const h = dialogHarness(); + const pending = h.click(); + confirmSelection(); + await vi.waitFor(() => expect(pendingConfirm()).toBeTruthy()); + confirmSelection(); + await vi.waitFor(() => expect(mocks.reward).toHaveBeenCalledOnce()); + await vi.advanceTimersByTimeAsync(1_000); + const cancel = document.querySelector("#__loader button"); + expect(cancel?.textContent).toBe("Cancel"); + cancel.click(); + await pending; + await vi.advanceTimersByTimeAsync(300); + await h.closed; + expect(h.selection.signal.aborted).toBe(true); + expect(system.setAppIcon).not.toHaveBeenCalled(); + expect(document.querySelector("#__loader")).toBeNull(); + const reopened = h.open(); + await actionStack.pop(); + await vi.advanceTimersByTimeAsync(300); + await reopened; + expect(actionStack.length).toBe(0); +}); diff --git a/tests/unit/paidAds.test.js b/tests/unit/paidAds.test.js index 4508b05..6f60b77 100644 --- a/tests/unit/paidAds.test.js +++ b/tests/unit/paidAds.test.js @@ -1,7 +1,6 @@ import { afterEach, expect, test, vi } from "vitest"; import showRewardedAd, { isRewardedAdSupported, - isWatchingRewardedAd, } from "../../src/lib/paid/rewardedAd"; import startAd, { getPrivacyState, @@ -15,7 +14,6 @@ test("paid APIs preserve unavailable-ad behavior without a native advertising br vi.stubGlobal("strings", { "rewarded ad unavailable": "Reward unavailable" }); await expect(startAd()).resolves.toBeUndefined(); expect(isRewardedAdSupported()).toBe(false); - expect(isWatchingRewardedAd()).toBe(false); await expect(showRewardedAd()).rejects.toThrow("Reward unavailable"); const controller = new AbortController(); controller.abort();