a26e0b93b5
- billing module with a testable seam: models (product ids, purchase events), StoreClient + PlayStoreClient over in_app_purchase, Entitlements persisted in SharedPreferences, BillingService orchestrating query/buy/restore/grant. - rules encoded: grant before completePurchase (Play refunds unacknowledged purchases after three days), pending purchases are shown but never granted, restorePurchases on start so a reinstall keeps the purchase, and Remove Ads only hides interstitials - rewarded video stays available. - ads gate: AdsService.adsRemoved stops both the counter and the preload, so an owner never requests an interstitial. - settings sheet: shop section (price from the store, never hardcoded), "restore purchases", and "delete local data" with confirmation; the existing mail-based deletion request stays the account-deletion path since the app has no accounts. - 9 new tests with a fake store cover purchase, restore, pending, cancel, error, restart persistence, missing store and a store that throws. 17 total. - verified on device: the app talks to the real Play Billing service (IInAppBillingService in logcat) and degrades to "no products created" without a crash; com.android.vending.BILLING is in the merged manifest. - docs: monetization 7c (rules + verification), decision D6 (local entitlement until purchases affect the server), compliance rows for billing/restore/ deletion, blocked.md 3c (create remove_ads in the Console). - release 0.9.0 (13).
498 lines
17 KiB
Dart
498 lines
17 KiB
Dart
import 'dart:async';
|
||
|
||
import 'package:flame/game.dart';
|
||
import 'package:flutter/foundation.dart';
|
||
import 'package:flutter/services.dart';
|
||
import 'package:flutter/material.dart';
|
||
import 'package:shared_preferences/shared_preferences.dart';
|
||
import 'package:url_launcher/url_launcher.dart';
|
||
|
||
import 'src/ads/ads_service.dart';
|
||
import 'src/billing/billing_service.dart';
|
||
import 'src/billing/entitlements.dart';
|
||
import 'src/billing/models.dart';
|
||
import 'src/billing/store_client.dart';
|
||
import 'src/game/iron_arc_game.dart';
|
||
import 'src/native/native_match.dart';
|
||
import 'src/net/api_client.dart';
|
||
import 'src/net/match_session.dart';
|
||
import 'src/net/offline_queue.dart';
|
||
import 'src/ui/links.dart';
|
||
import 'src/ui/splash_screen.dart';
|
||
import 'src/ui/widgets.dart';
|
||
|
||
/// Started in `main()`, so the boot log line covers the whole cold start
|
||
/// (engine, Dart isolate and native match load). Must be initialised eagerly -
|
||
/// a top-level `final` would only start on first access.
|
||
final Stopwatch _bootWatch = Stopwatch();
|
||
|
||
void main() {
|
||
_bootWatch.start();
|
||
runApp(const IronArcApp());
|
||
}
|
||
|
||
class IronArcApp extends StatelessWidget {
|
||
const IronArcApp({super.key});
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
return MaterialApp(
|
||
title: 'Iron Arc',
|
||
debugShowCheckedModeBanner: false,
|
||
theme: ThemeData.dark(useMaterial3: true),
|
||
home: const MatchScreen(),
|
||
);
|
||
}
|
||
}
|
||
|
||
/// Hotseat match with optional server sync (`adb reverse tcp:8080 tcp:8080`).
|
||
class MatchScreen extends StatefulWidget {
|
||
const MatchScreen({super.key});
|
||
|
||
@override
|
||
State<MatchScreen> createState() => _MatchScreenState();
|
||
}
|
||
|
||
class _MatchScreenState extends State<MatchScreen> {
|
||
static const _baseUrl = 'http://127.0.0.1:8080';
|
||
|
||
/// Minimum time the splash stays up, so even a warm start shows the brand
|
||
/// instead of a single-frame flicker.
|
||
static const _minSplash = Duration(milliseconds: 700);
|
||
|
||
int _seed = 42;
|
||
late final ApiClient _api = ApiClient(baseUrl: _baseUrl);
|
||
late final OfflineQueue _queue = OfflineQueue();
|
||
late final AdsService _ads = AdsService();
|
||
late final MatchSession _session =
|
||
MatchSession(client: _api, queue: _queue, deviceId: 'pending');
|
||
|
||
/// Null while booting. Constructing a game loads the native match library,
|
||
/// which must not block the first frame - that used to be the white screen.
|
||
IronArcGame? _game;
|
||
bool _splashGone = false;
|
||
|
||
Entitlements? _entitlements;
|
||
BillingService? _billing;
|
||
|
||
@override
|
||
void initState() {
|
||
super.initState();
|
||
// Boot after the first frame so the splash is painted before any blocking
|
||
// work (FFI library load, shared preferences, ad SDK).
|
||
WidgetsBinding.instance.addPostFrameCallback((_) => _bootstrap());
|
||
}
|
||
|
||
/// Session, native match and ad SDK - all while the splash is on screen.
|
||
Future<void> _bootstrap() async {
|
||
// Measured from the first Flutter frame, so the pulse is always visible
|
||
// even when the engine took seconds to start (debug builds, cold JIT).
|
||
final splashStart = Stopwatch()..start();
|
||
|
||
await _initSession();
|
||
final game = _buildGame();
|
||
if (!mounted) return;
|
||
|
||
// Keep the brand moment on screen even when everything loads instantly.
|
||
final left = _minSplash - splashStart.elapsed;
|
||
if (left > Duration.zero) await Future<void>.delayed(left);
|
||
if (!mounted) return;
|
||
|
||
setState(() => _game = game);
|
||
// Fade out over the already-built match, then drop the splash from the tree.
|
||
await Future<void>.delayed(const Duration(milliseconds: 320));
|
||
if (!mounted) return;
|
||
setState(() => _splashGone = true);
|
||
|
||
debugPrint('iron_arc: ready after ${_bootWatch.elapsedMilliseconds} ms');
|
||
|
||
// Store first: entitlements gate the interstitials that ads would load.
|
||
final entitlements = await Entitlements.load();
|
||
if (!mounted) return;
|
||
_entitlements = entitlements;
|
||
entitlements.addListener(_syncAdsGate);
|
||
_syncAdsGate();
|
||
final billing = BillingService(
|
||
entitlements: entitlements,
|
||
client: PlayStoreClient(),
|
||
);
|
||
_billing = billing;
|
||
unawaited(billing.init());
|
||
|
||
_ads.initialize();
|
||
}
|
||
|
||
/// Owners of "Remove Ads" never see an interstitial.
|
||
void _syncAdsGate() => _ads.adsRemoved = _entitlements?.adsRemoved ?? false;
|
||
|
||
@override
|
||
void dispose() {
|
||
_entitlements?.removeListener(_syncAdsGate);
|
||
_billing?.dispose();
|
||
_ads.dispose();
|
||
_api.close();
|
||
_session.dispose();
|
||
super.dispose();
|
||
}
|
||
|
||
/// Loads or creates a stable device id, then refreshes the offline queue.
|
||
Future<void> _initSession() async {
|
||
final prefs = await SharedPreferences.getInstance();
|
||
var id = prefs.getString('iron_arc.device_id');
|
||
if (id == null || id.length < 4) {
|
||
id = 'dev-${DateTime.now().microsecondsSinceEpoch.toRadixString(16)}';
|
||
await prefs.setString('iron_arc.device_id', id);
|
||
}
|
||
_session.deviceId = id;
|
||
await _session.refreshQueueSize();
|
||
}
|
||
|
||
IronArcGame _buildGame({int? seed, String? replayJson}) {
|
||
final game = replayJson != null
|
||
? IronArcGame(matchFactory: () => NativeMatch.playback(replayJson))
|
||
: IronArcGame(seed: seed ?? _seed);
|
||
game.onShotResolved = (expect, command, localHashAfter) {
|
||
if (game.isPlayback) return;
|
||
if (_session.status == SyncStatus.online) {
|
||
_session.submitShot(
|
||
expectHash: expect,
|
||
command: command,
|
||
localHashAfter: localHashAfter,
|
||
replayJson: game.replayJson(),
|
||
);
|
||
} else if (game.hud.value.isFinished) {
|
||
_session.enqueueReplay(game.replayJson());
|
||
}
|
||
if (game.hud.value.isFinished) _ads.onMatchFinished();
|
||
};
|
||
return game;
|
||
}
|
||
|
||
Future<void> _startOnline() async {
|
||
final seed = await _session.startOnlineMatch();
|
||
if (!mounted || seed == null) {
|
||
_toast('Server nicht erreichbar');
|
||
return;
|
||
}
|
||
setState(() {
|
||
_seed = seed;
|
||
_game = _buildGame(seed: seed);
|
||
});
|
||
_toast('Online-Match ${_session.matchId}');
|
||
}
|
||
|
||
void _playReplay() {
|
||
final game = _game;
|
||
if (game == null) return;
|
||
final json = game.replayJson();
|
||
debugPrint('iron_arc: replay tapped, ${json.length} bytes');
|
||
if (json.isEmpty) {
|
||
_toast('Kein Replay vorhanden');
|
||
return;
|
||
}
|
||
setState(() => _game = _buildGame(replayJson: json));
|
||
_toast('Replay läuft');
|
||
}
|
||
|
||
/// Settings sheet: privacy options (UMP requirement) and ad status.
|
||
void _openSettings() {
|
||
showModalBottomSheet<void>(
|
||
context: context,
|
||
backgroundColor: const Color(0xFF0B1220),
|
||
builder: (sheetContext) => SafeArea(
|
||
child: Column(
|
||
mainAxisSize: MainAxisSize.min,
|
||
children: [
|
||
ListTile(
|
||
leading: const Icon(Icons.privacy_tip_outlined),
|
||
title: const Text('Datenschutz-Optionen'),
|
||
subtitle: Text(_ads.consentLabel),
|
||
onTap: () async {
|
||
Navigator.pop(sheetContext);
|
||
await _ads.showPrivacyOptions();
|
||
if (mounted) _toast('Consent: ${_ads.consentLabel}');
|
||
},
|
||
),
|
||
ListTile(
|
||
leading: const Icon(Icons.description_outlined),
|
||
title: const Text('Datenschutzerklärung'),
|
||
subtitle: const Text('Öffnet die Webseite'),
|
||
trailing: const Icon(Icons.open_in_new, size: 18),
|
||
onTap: () async {
|
||
Navigator.pop(sheetContext);
|
||
final ok = await launchUrl(
|
||
Uri.parse(kPrivacyPolicyUrl),
|
||
mode: LaunchMode.externalApplication,
|
||
);
|
||
if (!ok && mounted) _toast('Keine App zum Öffnen gefunden');
|
||
},
|
||
),
|
||
_shopSection(sheetContext),
|
||
ListTile(
|
||
leading: const Icon(Icons.campaign_outlined),
|
||
title: const Text('Werbe-Status'),
|
||
subtitle: Text(_ads.statusLabel),
|
||
),
|
||
ListTile(
|
||
leading: const Icon(Icons.fingerprint),
|
||
title: const Text('Geraete-ID'),
|
||
subtitle: SelectableText(_session.deviceId,
|
||
style: const TextStyle(fontSize: 12)),
|
||
trailing: IconButton(
|
||
icon: const Icon(Icons.copy, size: 18),
|
||
onPressed: () async {
|
||
await Clipboard.setData(
|
||
ClipboardData(text: _session.deviceId));
|
||
if (mounted) _toast('Geraete-ID kopiert');
|
||
},
|
||
),
|
||
),
|
||
ListTile(
|
||
leading: const Icon(Icons.delete_outline),
|
||
title: const Text('Datenlöschung anfragen'),
|
||
subtitle: const Text('E-Mail mit vorausgefüllter Geräte-ID'),
|
||
onTap: () async {
|
||
Navigator.pop(sheetContext);
|
||
final ok = await launchUrl(deletionRequestUri(_session.deviceId));
|
||
if (!ok && mounted) _toast('Keine E-Mail-App gefunden');
|
||
},
|
||
),
|
||
ListTile(
|
||
leading: const Icon(Icons.cleaning_services_outlined),
|
||
title: const Text('Lokale Daten löschen'),
|
||
subtitle: const Text('Verlauf, Warteschlange, Geräte-ID'),
|
||
onTap: () async {
|
||
Navigator.pop(sheetContext);
|
||
final confirmed = await showDialog<bool>(
|
||
context: context,
|
||
builder: (ctx) => AlertDialog(
|
||
title: const Text('Lokale Daten löschen?'),
|
||
content: const Text(
|
||
'Entfernt Offline-Warteschlange, Replays und die Geräte-ID '
|
||
'von diesem Gerät. Käufe bleiben erhalten.'),
|
||
actions: [
|
||
TextButton(
|
||
onPressed: () => Navigator.pop(ctx, false),
|
||
child: const Text('Abbrechen')),
|
||
FilledButton(
|
||
onPressed: () => Navigator.pop(ctx, true),
|
||
child: const Text('Löschen')),
|
||
],
|
||
),
|
||
);
|
||
if (confirmed != true || !mounted) return;
|
||
final prefs = await SharedPreferences.getInstance();
|
||
await prefs.clear();
|
||
if (!mounted) return;
|
||
_toast('Lokale Daten gelöscht – App neu starten');
|
||
},
|
||
),
|
||
if (kDebugMode)
|
||
ListTile(
|
||
leading: const Icon(Icons.restart_alt),
|
||
title: const Text('Consent zuruecksetzen (Debug)'),
|
||
onTap: () async {
|
||
Navigator.pop(sheetContext);
|
||
await _ads.resetConsent();
|
||
if (mounted) _toast('Consent zurueckgesetzt - App neu starten');
|
||
},
|
||
),
|
||
const SizedBox(height: 8),
|
||
],
|
||
),
|
||
),
|
||
);
|
||
}
|
||
|
||
/// Store section of the settings sheet (M7c).
|
||
Widget _shopSection(BuildContext sheetContext) {
|
||
final billing = _billing;
|
||
final ent = _entitlements;
|
||
if (billing == null || ent == null) {
|
||
return const ListTile(
|
||
leading: Icon(Icons.shopping_bag_outlined),
|
||
title: Text('Werbung entfernen'),
|
||
subtitle: Text('Store wird geladen …'),
|
||
enabled: false,
|
||
);
|
||
}
|
||
return ListenableBuilder(
|
||
listenable: Listenable.merge([billing, ent]),
|
||
builder: (context, _) {
|
||
final owned = ent.adsRemoved;
|
||
final price = billing.product(ProductIds.removeAds)?.price;
|
||
return Column(
|
||
mainAxisSize: MainAxisSize.min,
|
||
children: [
|
||
const Divider(height: 1, color: Color(0xFF1B2C44)),
|
||
ListTile(
|
||
leading: Icon(
|
||
owned ? Icons.verified : Icons.block,
|
||
color: owned ? const Color(0xFFFFB347) : null,
|
||
),
|
||
title: const Text('Werbung entfernen'),
|
||
subtitle: Text(owned
|
||
? 'Gekauft - keine Interstitials mehr'
|
||
: billing.busy
|
||
? 'Einen Moment …'
|
||
: price ?? billing.error ?? 'Preis wird geladen …'),
|
||
trailing: owned
|
||
? null
|
||
: const Icon(Icons.shopping_bag_outlined, size: 18),
|
||
enabled: !owned && billing.canPurchase && !billing.busy,
|
||
onTap: owned
|
||
? null
|
||
: () async {
|
||
Navigator.pop(sheetContext);
|
||
final started = await billing.buy(ProductIds.removeAds);
|
||
if (!mounted) return;
|
||
_toast(started
|
||
? 'Kauf gestartet'
|
||
: billing.error ?? 'Kauf nicht möglich');
|
||
},
|
||
),
|
||
if (!owned)
|
||
ListTile(
|
||
leading: const Icon(Icons.restore),
|
||
title: const Text('Käufe wiederherstellen'),
|
||
enabled: billing.available && !billing.busy,
|
||
onTap: () async {
|
||
Navigator.pop(sheetContext);
|
||
await billing.restore();
|
||
if (!mounted) return;
|
||
_toast(ent.adsRemoved
|
||
? 'Käufe wiederhergestellt'
|
||
: 'Keine Käufe gefunden');
|
||
},
|
||
),
|
||
],
|
||
);
|
||
},
|
||
);
|
||
}
|
||
|
||
Future<void> _showRewardedAd() async {
|
||
if (!_ads.isAdsAllowed) {
|
||
_toast('Anzeigen erst nach Zustimmung');
|
||
return;
|
||
}
|
||
final reward = await _ads.showRewarded();
|
||
if (!mounted) return;
|
||
_toast(reward == null ? 'Keine Anzeige verfügbar' : 'Belohnung: +$reward');
|
||
}
|
||
|
||
Future<void> _flushQueue() async {
|
||
final validated = await _session.flushQueue();
|
||
if (mounted) _toast('$validated Replay(s) validiert');
|
||
}
|
||
|
||
void _restart() {
|
||
setState(() {
|
||
_seed += 1;
|
||
_game = _buildGame(seed: _seed);
|
||
});
|
||
}
|
||
|
||
void _toast(String message) {
|
||
ScaffoldMessenger.of(context)
|
||
..clearSnackBars()
|
||
..showSnackBar(SnackBar(
|
||
content: Text(message),
|
||
duration: const Duration(seconds: 2),
|
||
behavior: SnackBarBehavior.floating,
|
||
));
|
||
}
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
final game = _game;
|
||
return Scaffold(
|
||
backgroundColor: SplashScreen.background,
|
||
body: Stack(
|
||
children: [
|
||
// The match only exists once the native library and session are up;
|
||
// until then the pulsing splash covers the whole window.
|
||
if (game != null) _buildMatch(game),
|
||
if (!_splashGone)
|
||
Positioned.fill(
|
||
child: AnimatedOpacity(
|
||
opacity: game == null ? 1 : 0,
|
||
duration: const Duration(milliseconds: 280),
|
||
curve: Curves.easeOut,
|
||
child: const SplashScreen(),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
);
|
||
}
|
||
|
||
/// HUD, canvas and controls of a running match.
|
||
Widget _buildMatch(IronArcGame game) {
|
||
return SafeArea(
|
||
child: Column(
|
||
children: [
|
||
Padding(
|
||
padding: const EdgeInsets.fromLTRB(12, 8, 12, 0),
|
||
child: Column(
|
||
children: [
|
||
ValueListenableBuilder<HudState>(
|
||
valueListenable: game.hud,
|
||
builder: (context, hud, _) => Hud(hud: hud),
|
||
),
|
||
const SizedBox(height: 6),
|
||
AnimatedBuilder(
|
||
animation: _session,
|
||
builder: (context, _) =>
|
||
StatusBar(session: _session, onSettings: _openSettings),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
// Play area: gestures only affect the game, never the controls.
|
||
Expanded(
|
||
child: Stack(
|
||
children: [
|
||
Positioned.fill(
|
||
child: GameWidget(key: ValueKey(game), game: game)),
|
||
Positioned.fill(
|
||
child: GestureDetector(
|
||
behavior: HitTestBehavior.opaque,
|
||
onPanStart: (d) => game.beginAim(d.localPosition),
|
||
onPanUpdate: (d) => game.updateAim(d.localPosition),
|
||
onPanEnd: (_) => game.releaseAim(),
|
||
),
|
||
),
|
||
Positioned(
|
||
left: 16,
|
||
right: 16,
|
||
bottom: 8,
|
||
child: ValueListenableBuilder<HudState>(
|
||
valueListenable: game.hud,
|
||
builder: (context, hud, _) => hud.isFinished
|
||
? GameOver(hud: hud, onRestart: _restart)
|
||
: HintBubble(hud: hud),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
Padding(
|
||
padding: const EdgeInsets.fromLTRB(12, 8, 12, 8),
|
||
child: AnimatedBuilder(
|
||
animation: _session,
|
||
builder: (context, _) => Controls(
|
||
session: _session,
|
||
onOnline: _startOnline,
|
||
onReplay: _playReplay,
|
||
onFlush: _flushQueue,
|
||
onAd: _showRewardedAd,
|
||
),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
);
|
||
}
|
||
}
|