Files
logic-puzzle/lib/services/ads.dart
T

317 lines
9.1 KiB
Dart

import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'ad_pacing.dart';
import 'ad_audience.dart';
import 'play_metrics.dart';
class Ads {
Ads({this.enabled = true, this.pacing, this.metrics});
final bool enabled;
final AdPacing? pacing;
final PlayMetrics? metrics;
bool _showing = false;
bool foreground = true;
AdAudience _audience = AdAudience.unknown;
bool _consentReady = false;
int _generation = 0;
AdAudience get audience => _audience;
bool get adsAllowed => supported && _audience.allowsAds;
Future<void> setAudience(AdAudience audience) async {
_audience = audience;
await start();
}
void _clearAds() {
_reward?.dispose();
_interstitial?.dispose();
_reward = null;
_interstitial = null;
_rewardAt = _interstitialAt = null;
_rewardLoading = _interstitialLoading = false;
}
void _paid(AdWithoutView ad, String format) {
ad.onPaidEvent = (ad, value, precision, currency) {
metrics?.paid(
format: format,
micros: value,
currency: currency,
precision: precision.name,
test: ad.adUnitId.contains('3940256099942544'),
);
};
}
void _impression(Ad ad, String format) => metrics?.event(
'${ad.adUnitId.contains('3940256099942544') ? 'test' : 'configured'}_${format}_impressions',
);
RewardedAd? _reward;
InterstitialAd? _interstitial;
bool _started = false,
_rewardLoading = false,
_interstitialLoading = false,
_disposed = false;
DateTime? _rewardAt, _interstitialAt;
bool get supported =>
enabled &&
!kIsWeb &&
(defaultTargetPlatform == TargetPlatform.android ||
defaultTargetPlatform == TargetPlatform.iOS);
Future<void> start() async {
final generation = ++_generation;
_consentReady = false;
_clearAds();
// Under-13 and unknown-age players never initialize the SDK or request ads.
if (!supported || _disposed || !_audience.allowsAds) return;
// Teenagers receive child-directed treatment; adults receive standard
// treatment. Both keep the general-audience rating.
await MobileAds.instance.updateRequestConfiguration(
RequestConfiguration(
ageRestrictedTreatment: _audience.restricted
? AgeRestrictedTreatment.child
: AgeRestrictedTreatment.unspecified,
maxAdContentRating: MaxAdContentRating.g,
),
);
if (_disposed || generation != _generation) return;
ConsentInformation.instance.requestConsentInfoUpdate(
ConsentRequestParameters(tagForUnderAgeOfConsent: _audience.restricted),
() {
if (_disposed || generation != _generation) return;
ConsentForm.loadAndShowConsentFormIfRequired(
(_) => _initialize(generation),
);
},
(_) => _initialize(generation),
);
}
Future<void> _initialize(int generation) async {
if (_disposed ||
generation != _generation ||
!_audience.allowsAds ||
!await ConsentInformation.instance.canRequestAds()) {
return;
}
if (_disposed || generation != _generation) return;
if (!_started) {
_started = true;
await MobileAds.instance.initialize();
}
if (_disposed || generation != _generation) return;
_consentReady = true;
await _load();
}
Future<void> _load() async {
if (_disposed ||
!_consentReady ||
!_audience.allowsAds ||
!supported ||
!await ConsentInformation.instance.canRequestAds()) {
return;
}
final generation = _generation;
if (_disposed || !_consentReady) return;
final ios = defaultTargetPlatform == TargetPlatform.iOS;
if (_reward == null && !_rewardLoading) {
_rewardLoading = true;
RewardedAd.load(
adUnitId: const String.fromEnvironment('ADMOB_REWARDED_ID').isNotEmpty
? const String.fromEnvironment('ADMOB_REWARDED_ID')
: ios
? 'ca-app-pub-3940256099942544/1712485313'
: 'ca-app-pub-3940256099942544/5224354917',
request: const AdRequest(),
rewardedAdLoadCallback: RewardedAdLoadCallback(
onAdLoaded: (a) {
if (generation != _generation) {
a.dispose();
return;
}
_rewardLoading = false;
if (_disposed || !_consentReady) {
a.dispose();
return;
}
_reward = a;
_paid(a, 'rewarded');
_rewardAt = DateTime.now();
},
onAdFailedToLoad: (_) {
if (generation != _generation) return;
_rewardLoading = false;
},
),
);
}
if (_interstitial == null && !_interstitialLoading) {
_interstitialLoading = true;
InterstitialAd.load(
adUnitId:
const String.fromEnvironment('ADMOB_INTERSTITIAL_ID').isNotEmpty
? const String.fromEnvironment('ADMOB_INTERSTITIAL_ID')
: ios
? 'ca-app-pub-3940256099942544/4411468910'
: 'ca-app-pub-3940256099942544/1033173712',
request: const AdRequest(),
adLoadCallback: InterstitialAdLoadCallback(
onAdLoaded: (a) {
if (generation != _generation) {
a.dispose();
return;
}
_interstitialLoading = false;
if (_disposed || !_consentReady) {
a.dispose();
return;
}
_interstitial = a;
_paid(a, 'interstitial');
_interstitialAt = DateTime.now();
},
onAdFailedToLoad: (_) {
if (generation != _generation) return;
_interstitialLoading = false;
},
),
);
}
}
Future<bool> hint(VoidCallback earned) async {
if (!supported ||
!_consentReady ||
!_audience.allowsAds ||
_disposed ||
_showing ||
!foreground ||
!await ConsentInformation.instance.canRequestAds()) {
return false;
}
if (_disposed || _showing || !foreground) return false;
metrics?.event('rewarded_opportunities');
final a = _reward;
_reward = null;
if (a == null ||
_rewardAt == null ||
DateTime.now().difference(_rewardAt!).inMinutes >= 58) {
a?.dispose();
unawaited(_load());
metrics?.event('rewarded_unavailable');
return false;
}
_showing = true;
var granted = false;
a.fullScreenContentCallback = FullScreenContentCallback(
onAdShowedFullScreenContent: (_) => pacing?.shown(automatic: false),
onAdImpression: (ad) => _impression(ad, 'rewarded'),
onAdDismissedFullScreenContent: (ad) {
_showing = false;
ad.dispose();
_load();
},
onAdFailedToShowFullScreenContent: (ad, e) {
_showing = false;
ad.dispose();
_load();
},
);
try {
await a.show(
onUserEarnedReward: (ad, reward) {
if (granted) return;
granted = true;
metrics?.event('rewarded_earned');
earned();
},
);
} catch (_) {
_showing = false;
a.dispose();
unawaited(_load());
return false;
}
return true;
}
Future<void> between(VoidCallback next) async {
if (!supported ||
!_consentReady ||
!_audience.allowsAds ||
_disposed ||
_showing ||
!foreground ||
!(pacing?.allowed ?? true) ||
!await ConsentInformation.instance.canRequestAds()) {
next();
return;
}
if (_disposed || _showing || !foreground) {
next();
return;
}
metrics?.event('interstitial_opportunities');
final a = _interstitial;
_interstitial = null;
if (a == null ||
_interstitialAt == null ||
DateTime.now().difference(_interstitialAt!).inMinutes >= 58) {
a?.dispose();
next();
metrics?.event('interstitial_unavailable');
unawaited(_load());
return;
}
var routed = false;
_showing = true;
void finish() {
if (routed) return;
routed = true;
_showing = false;
a.dispose();
next();
_load();
}
a.fullScreenContentCallback = FullScreenContentCallback(
onAdShowedFullScreenContent: (_) => pacing?.shown(automatic: true),
onAdImpression: (ad) => _impression(ad, 'interstitial'),
onAdDismissedFullScreenContent: (_) => finish(),
onAdFailedToShowFullScreenContent: (_, e) => finish(),
);
try {
await a.show();
} catch (_) {
finish();
}
}
Future<bool> privacy() async {
// No ads means no ad-privacy form and no reason to touch the SDK.
if (!supported || !_audience.allowsAds) return false;
if (await ConsentInformation.instance
.getPrivacyOptionsRequirementStatus() !=
PrivacyOptionsRequirementStatus.required) {
return false;
}
final generation = ++_generation;
_consentReady = false;
_clearAds();
ConsentForm.showPrivacyOptionsForm((_) => _initialize(generation));
return true;
}
void dispose() {
_disposed = true;
_generation++;
_consentReady = false;
_clearAds();
}
}