fix:第一轮跑
This commit is contained in:
1 parent
e834ec7586
commit
33235f450b
56 files changed
+4357
-210
No files matched your search
@@ -0,0 +1,32 @@
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import '../../mall/application/mall_tab_config.dart';
|
||||
import '../data/ads_api_client.dart';
|
||||
import 'splash_ad_controller.dart';
|
||||
|
||||
final adConfigForegroundRefresherProvider = Provider(
|
||||
(ref) => AdConfigForegroundRefresher(
|
||||
() => ref.invalidate(featuredAdsProvider(homeBannerAdPlacement)),
|
||||
() => ref.read(splashAdControllerProvider).refresh(),
|
||||
() => ref.read(mallTabConfigProvider.notifier).refresh(),
|
||||
),
|
||||
);
|
||||
|
||||
class AdConfigForegroundRefresher {
|
||||
AdConfigForegroundRefresher(this._banner, this._splash, this._mall);
|
||||
final void Function() _banner;
|
||||
final Future<void> Function() _splash, _mall;
|
||||
Future<void>? _running;
|
||||
Future<void> refresh() =>
|
||||
_running ??= _refresh().whenComplete(() => _running = null);
|
||||
Future<void> _refresh() async {
|
||||
try {
|
||||
_banner();
|
||||
} catch (_) {}
|
||||
try {
|
||||
await _splash();
|
||||
} catch (_) {}
|
||||
try {
|
||||
await _mall();
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io' show File;
|
||||
|
||||
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
|
||||
import '../../../common/storage/storage_service.dart';
|
||||
import '../data/ads_api_client.dart';
|
||||
|
||||
class SplashAdEntry {
|
||||
const SplashAdEntry(this.ad, this.dailyCap, this.assetPath, this.cachedAtMs);
|
||||
final AdCreative ad;
|
||||
final int dailyCap;
|
||||
final String? assetPath;
|
||||
final int cachedAtMs;
|
||||
bool get valid =>
|
||||
ad.isRenderable &&
|
||||
DateTime.now().millisecondsSinceEpoch <
|
||||
cachedAtMs + const Duration(hours: 24).inMilliseconds &&
|
||||
(ad.endAtMs <= 0 || ad.endAtMs > DateTime.now().millisecondsSinceEpoch);
|
||||
Map<String, dynamic> toJson() => {
|
||||
'ad': ad.toJson(),
|
||||
'dailyCap': dailyCap,
|
||||
'assetPath': assetPath,
|
||||
'cachedAtMs': cachedAtMs,
|
||||
};
|
||||
factory SplashAdEntry.fromJson(Map<String, dynamic> map) => SplashAdEntry(
|
||||
AdCreative.fromJson(Map<String, dynamic>.from(map['ad'] as Map)),
|
||||
(map['dailyCap'] as num?)?.toInt() ?? 0,
|
||||
map['assetPath'] as String?,
|
||||
(map['cachedAtMs'] as num?)?.toInt() ?? 0,
|
||||
);
|
||||
}
|
||||
|
||||
class SplashAdController {
|
||||
SplashAdController(this._api);
|
||||
final AdsApiClient _api;
|
||||
static const _entryKey = 'ads.splash.entry';
|
||||
static const _dailyKey = 'ads.splash.daily';
|
||||
Future<SplashAdEntry?> coldLaunchDecision() async {
|
||||
final raw = StorageService.to.preferences.getString(_entryKey);
|
||||
if (raw == null) return null;
|
||||
try {
|
||||
final entry = SplashAdEntry.fromJson(
|
||||
Map<String, dynamic>.from(jsonDecode(raw) as Map),
|
||||
);
|
||||
if (!entry.valid || !_underCap(entry) || !await _ready(entry)) {
|
||||
return null;
|
||||
}
|
||||
return entry;
|
||||
} catch (_) {
|
||||
await clearCache();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
bool _underCap(SplashAdEntry entry) {
|
||||
final value = StorageService.to.preferences.getString(_dailyKey);
|
||||
final today = DateTime.now().toIso8601String().substring(0, 10);
|
||||
if (value == null) return true;
|
||||
final map = Map<String, dynamic>.from(jsonDecode(value) as Map);
|
||||
return map['date'] != today ||
|
||||
entry.dailyCap <= 0 ||
|
||||
((map['count'] as num?)?.toInt() ?? 0) < entry.dailyCap;
|
||||
}
|
||||
|
||||
Future<bool> _ready(SplashAdEntry entry) async =>
|
||||
entry.assetPath != null && await File(entry.assetPath!).exists();
|
||||
Future<void> markShown(SplashAdEntry entry) async {
|
||||
final today = DateTime.now().toIso8601String().substring(0, 10);
|
||||
final raw = StorageService.to.preferences.getString(_dailyKey);
|
||||
var count = 0;
|
||||
if (raw != null) {
|
||||
final m = Map<String, dynamic>.from(jsonDecode(raw) as Map);
|
||||
if (m['date'] == today) count = (m['count'] as num?)?.toInt() ?? 0;
|
||||
}
|
||||
await StorageService.to.preferences.setString(
|
||||
_dailyKey,
|
||||
jsonEncode({'date': today, 'count': count + 1}),
|
||||
);
|
||||
await _report(entry.ad, 'ad_impression');
|
||||
}
|
||||
|
||||
Future<void> refresh() async {
|
||||
try {
|
||||
final result = await _api.getAdResult(splashAdPlacement);
|
||||
if (!result.enabled || result.ad == null) {
|
||||
await _clearEntry();
|
||||
return;
|
||||
}
|
||||
final file = await DefaultCacheManager().getSingleFile(
|
||||
result.ad!.imageUrl,
|
||||
);
|
||||
if (!await file.exists()) return;
|
||||
await StorageService.to.preferences.setString(
|
||||
_entryKey,
|
||||
jsonEncode(
|
||||
SplashAdEntry(
|
||||
result.ad!,
|
||||
result.dailyCap,
|
||||
file.path,
|
||||
DateTime.now().millisecondsSinceEpoch,
|
||||
).toJson(),
|
||||
),
|
||||
);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
Future<void> _report(AdCreative ad, String event, {String? clickId}) async {
|
||||
try {
|
||||
await _api.report(ad, event, clickId: clickId);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
Future<void> skip(SplashAdEntry entry) => _report(entry.ad, 'ad_skip');
|
||||
Future<void> clearCache() async {
|
||||
await _clearEntry();
|
||||
await StorageService.to.preferences.remove(_dailyKey);
|
||||
}
|
||||
|
||||
Future<void> _clearEntry() async {
|
||||
await StorageService.to.preferences.remove(_entryKey);
|
||||
}
|
||||
}
|
||||
|
||||
final splashAdControllerProvider = Provider(
|
||||
(ref) => SplashAdController(ref.watch(adsApiClientProvider)),
|
||||
);
|
||||
@@ -0,0 +1,57 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
import '../../../common/router/app_router.dart';
|
||||
import '../data/ads_api_client.dart';
|
||||
import '../presentation/splash_ad_dialog.dart';
|
||||
import 'splash_ad_controller.dart';
|
||||
|
||||
final startupAdResolvedProvider = StateProvider<bool>((_) => false);
|
||||
|
||||
abstract final class StartupAdService {
|
||||
static Future<void>? _running;
|
||||
static Future<void> showIfAvailable(BuildContext context, WidgetRef ref) =>
|
||||
_running ??= _show(context, ref);
|
||||
static Future<void> _show(BuildContext context, WidgetRef ref) async {
|
||||
final controller = ref.read(splashAdControllerProvider);
|
||||
try {
|
||||
final entry = await controller.coldLaunchDecision();
|
||||
if (entry != null && context.mounted) {
|
||||
final result = await showGeneralDialog<SplashAdResult>(
|
||||
context: context,
|
||||
useRootNavigator: true,
|
||||
barrierDismissible: false,
|
||||
barrierColor: Colors.black,
|
||||
pageBuilder: (ctx, _, _) => SplashAdDialog(
|
||||
entry: entry,
|
||||
onShown: () => unawaited(controller.markShown(entry)),
|
||||
onClick: () async {
|
||||
final id = ref.read(adsApiClientProvider).newClickId();
|
||||
final uri = entry.ad.clickUri(id);
|
||||
if (uri != null) {
|
||||
unawaited(
|
||||
ref
|
||||
.read(adsApiClientProvider)
|
||||
.report(entry.ad, 'ad_click', clickId: id),
|
||||
);
|
||||
if (entry.ad.openMode == AdOpenMode.inApp) {
|
||||
context.push(
|
||||
'${AppRoutes.web}?url=${Uri.encodeComponent(uri.toString())}',
|
||||
);
|
||||
} else {
|
||||
await launchUrl(uri, mode: LaunchMode.externalApplication);
|
||||
}
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
if (result == SplashAdResult.skipped) unawaited(controller.skip(entry));
|
||||
}
|
||||
} finally {
|
||||
ref.read(startupAdResolvedProvider.notifier).state = true;
|
||||
unawaited(controller.refresh());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
import '../../../common/network/dio_provider.dart';
|
||||
|
||||
const splashAdPlacement = 'splash';
|
||||
const homeBannerAdPlacement = 'home_banner';
|
||||
|
||||
enum AdMediaType { image, gif, video, unsupported }
|
||||
|
||||
enum AdOpenMode { external, inApp }
|
||||
|
||||
class AdCreative {
|
||||
const AdCreative({
|
||||
required this.adId,
|
||||
required this.placement,
|
||||
required this.targetApp,
|
||||
required this.title,
|
||||
required this.imageUrl,
|
||||
required this.mediaType,
|
||||
required this.h5Url,
|
||||
required this.trackingId,
|
||||
required this.countdownSeconds,
|
||||
required this.endAtMs,
|
||||
required this.trackedUrl,
|
||||
required this.openMode,
|
||||
});
|
||||
final String adId,
|
||||
placement,
|
||||
targetApp,
|
||||
title,
|
||||
imageUrl,
|
||||
h5Url,
|
||||
trackingId,
|
||||
trackedUrl;
|
||||
final AdMediaType mediaType;
|
||||
final int countdownSeconds, endAtMs;
|
||||
final AdOpenMode openMode;
|
||||
Uri? get mediaUri => _http(imageUrl);
|
||||
Uri? get targetUri => _http(trackedUrl) ?? _http(h5Url);
|
||||
bool get isRenderable =>
|
||||
adId.isNotEmpty &&
|
||||
mediaUri != null &&
|
||||
targetUri != null &&
|
||||
mediaType != AdMediaType.unsupported &&
|
||||
(endAtMs <= 0 || endAtMs > DateTime.now().millisecondsSinceEpoch);
|
||||
Uri? clickUri(String clickId) {
|
||||
final uri = targetUri;
|
||||
if (uri == null) return null;
|
||||
return uri.replace(
|
||||
queryParameters: {
|
||||
...uri.queryParameters,
|
||||
'ad_id': adId,
|
||||
'placement': placement,
|
||||
'tracking_id': trackingId,
|
||||
'click_id': clickId,
|
||||
'target_app': targetApp,
|
||||
'hook_type': placement,
|
||||
'ts': DateTime.now().millisecondsSinceEpoch.toString(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'adId': adId,
|
||||
'placement': placement,
|
||||
'targetApp': targetApp,
|
||||
'title': title,
|
||||
'imageUrl': imageUrl,
|
||||
'mediaType': mediaType.index,
|
||||
'h5Url': h5Url,
|
||||
'trackingId': trackingId,
|
||||
'countdownSeconds': countdownSeconds,
|
||||
'endAtMs': endAtMs,
|
||||
'trackedUrl': trackedUrl,
|
||||
'openMode': openMode.index,
|
||||
};
|
||||
factory AdCreative.fromJson(Map<String, dynamic> value) => AdCreative(
|
||||
adId: '${value['adId'] ?? ''}',
|
||||
placement: '${value['placement'] ?? ''}',
|
||||
targetApp: '${value['targetApp'] ?? ''}',
|
||||
title: '${value['title'] ?? ''}',
|
||||
imageUrl: '${value['imageUrl'] ?? ''}',
|
||||
mediaType:
|
||||
AdMediaType.values[(value['mediaType'] as num?)?.toInt().clamp(
|
||||
0,
|
||||
AdMediaType.values.length - 1,
|
||||
) ??
|
||||
AdMediaType.unsupported.index],
|
||||
h5Url: '${value['h5Url'] ?? ''}',
|
||||
trackingId: '${value['trackingId'] ?? ''}',
|
||||
countdownSeconds: (value['countdownSeconds'] as num?)?.toInt() ?? 0,
|
||||
endAtMs: (value['endAtMs'] as num?)?.toInt() ?? 0,
|
||||
trackedUrl: '${value['trackedUrl'] ?? ''}',
|
||||
openMode: (value['openMode'] as num?)?.toInt() == AdOpenMode.inApp.index
|
||||
? AdOpenMode.inApp
|
||||
: AdOpenMode.external,
|
||||
);
|
||||
factory AdCreative.fromProto(ProtoMessage fields) => AdCreative(
|
||||
adId: fields.string(1),
|
||||
placement: fields.string(2),
|
||||
targetApp: fields.string(3),
|
||||
title: fields.string(4),
|
||||
imageUrl: fields.string(6),
|
||||
mediaType: switch (fields.integer(7)) {
|
||||
1 => AdMediaType.image,
|
||||
2 => AdMediaType.gif,
|
||||
3 => AdMediaType.video,
|
||||
_ => AdMediaType.unsupported,
|
||||
},
|
||||
h5Url: fields.string(9),
|
||||
trackingId: fields.string(10),
|
||||
countdownSeconds: fields.integer(11),
|
||||
endAtMs: fields.integer(13),
|
||||
trackedUrl: fields.string(14),
|
||||
openMode: fields.integer(15) == 2 ? AdOpenMode.inApp : AdOpenMode.external,
|
||||
);
|
||||
}
|
||||
|
||||
class GetAdResult {
|
||||
const GetAdResult(this.enabled, this.ad, this.dailyCap);
|
||||
final bool enabled;
|
||||
final AdCreative? ad;
|
||||
final int dailyCap;
|
||||
}
|
||||
|
||||
class FeaturedAdsState {
|
||||
const FeaturedAdsState(this.enabled, this.ads, {this.trackingId});
|
||||
final bool enabled;
|
||||
final List<AdCreative> ads;
|
||||
final String? trackingId;
|
||||
bool get hasAds => enabled && ads.isNotEmpty;
|
||||
}
|
||||
|
||||
class AdsApiClient {
|
||||
AdsApiClient(this._dio);
|
||||
final Dio _dio;
|
||||
Future<GetAdResult> getAdResult(String placement) async {
|
||||
final response = await _dio.get<List<int>>(
|
||||
'/api/v1/ads',
|
||||
queryParameters: {'placement': placement},
|
||||
options: protobufOptions(),
|
||||
);
|
||||
final root = ProtoMessage(response.data ?? const []);
|
||||
final creative = root.message(2);
|
||||
final ad = AdCreative.fromProto(creative);
|
||||
return GetAdResult(
|
||||
root.integer(1) != 0,
|
||||
ad.isRenderable ? ad : null,
|
||||
root.integer(3),
|
||||
);
|
||||
}
|
||||
|
||||
Future<FeaturedAdsState> listAds(String placement) async {
|
||||
final response = await _dio.get<List<int>>(
|
||||
'/api/v1/ads/list',
|
||||
queryParameters: {'placement': placement},
|
||||
options: protobufOptions(),
|
||||
);
|
||||
final root = ProtoMessage(response.data ?? const []);
|
||||
final ads = root
|
||||
.messages(2)
|
||||
.map(AdCreative.fromProto)
|
||||
.where((ad) => ad.isRenderable)
|
||||
.toList(growable: false);
|
||||
return FeaturedAdsState(
|
||||
root.integer(1) != 0,
|
||||
ads,
|
||||
trackingId: root.string(3).isEmpty ? null : root.string(3),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> report(
|
||||
AdCreative ad,
|
||||
String event, {
|
||||
String? clickId,
|
||||
String? trackingId,
|
||||
}) => _dio.post<List<int>>(
|
||||
'/api/v1/ads/events',
|
||||
data: _Writer()
|
||||
.string(1, event)
|
||||
.string(2, ad.placement)
|
||||
.string(3, ad.adId)
|
||||
.string(4, trackingId ?? ad.trackingId)
|
||||
.string(5, clickId ?? '')
|
||||
.integer(6, DateTime.now().millisecondsSinceEpoch)
|
||||
.toBytes(),
|
||||
options: protobufOptions(),
|
||||
);
|
||||
String newClickId() => const Uuid().v4();
|
||||
}
|
||||
|
||||
final adsApiClientProvider = Provider(
|
||||
(ref) => AdsApiClient(ref.watch(dioProvider)),
|
||||
);
|
||||
final featuredAdsProvider = FutureProvider.autoDispose
|
||||
.family<FeaturedAdsState, String>(
|
||||
(ref, placement) => ref.watch(adsApiClientProvider).listAds(placement),
|
||||
);
|
||||
|
||||
Uri? _http(String raw) {
|
||||
final uri = Uri.tryParse(raw.trim());
|
||||
return uri != null &&
|
||||
uri.host.isNotEmpty &&
|
||||
(uri.scheme == 'https' || uri.scheme == 'http')
|
||||
? uri
|
||||
: null;
|
||||
}
|
||||
|
||||
class ProtoMessage {
|
||||
ProtoMessage(this.bytes);
|
||||
final List<int> bytes;
|
||||
Map<int, List<Object>>? _cache;
|
||||
Map<int, List<Object>> get _fields => _cache ??= _read();
|
||||
int integer(int tag) => (_fields[tag]?.lastOrNull as int?) ?? 0;
|
||||
String string(int tag) {
|
||||
final value = _fields[tag]?.lastOrNull;
|
||||
return value is List<int> ? String.fromCharCodes(value) : '';
|
||||
}
|
||||
|
||||
ProtoMessage message(int tag) {
|
||||
final value = _fields[tag]?.lastOrNull;
|
||||
return ProtoMessage(value is List<int> ? value : const []);
|
||||
}
|
||||
|
||||
List<ProtoMessage> messages(int tag) => (_fields[tag] ?? const [])
|
||||
.whereType<List<int>>()
|
||||
.map(ProtoMessage.new)
|
||||
.toList();
|
||||
Map<int, List<Object>> _read() {
|
||||
final out = <int, List<Object>>{};
|
||||
var i = 0;
|
||||
int v() {
|
||||
var n = 0, s = 0;
|
||||
while (i < bytes.length) {
|
||||
final b = bytes[i++];
|
||||
n |= (b & 127) << s;
|
||||
if (b < 128) return n;
|
||||
s += 7;
|
||||
}
|
||||
throw const FormatException('Invalid protobuf');
|
||||
}
|
||||
|
||||
while (i < bytes.length) {
|
||||
final key = v(), tag = key >> 3;
|
||||
Object value;
|
||||
if ((key & 7) == 0) {
|
||||
value = v();
|
||||
} else if ((key & 7) == 2) {
|
||||
final l = v(), end = i + l;
|
||||
if (end > bytes.length) throw const FormatException('Invalid protobuf');
|
||||
value = bytes.sublist(i, end);
|
||||
i = end;
|
||||
} else {
|
||||
throw const FormatException('Unsupported protobuf');
|
||||
}
|
||||
(out[tag] ??= []).add(value);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
extension on List<Object> {
|
||||
Object? get lastOrNull => isEmpty ? null : last;
|
||||
}
|
||||
|
||||
class _Writer {
|
||||
final b = BytesBuilder(copy: false);
|
||||
_Writer string(int t, String value) {
|
||||
final d = value.codeUnits;
|
||||
v((t << 3) | 2);
|
||||
v(d.length);
|
||||
b.add(d);
|
||||
return this;
|
||||
}
|
||||
|
||||
_Writer integer(int t, int value) {
|
||||
v(t << 3);
|
||||
v(value);
|
||||
return this;
|
||||
}
|
||||
|
||||
Uint8List toBytes() => b.toBytes();
|
||||
void v(int n) {
|
||||
while (n > 127) {
|
||||
b.addByte((n & 127) | 128);
|
||||
n >>= 7;
|
||||
}
|
||||
b.addByte(n);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io' show File;
|
||||
|
||||
import 'package:flutter/foundation.dart' show kIsWeb;
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:video_player/video_player.dart';
|
||||
|
||||
import '../data/ads_api_client.dart';
|
||||
|
||||
/// 统一渲染广告图片/GIF/视频;开屏可优先使用已缓存的本地素材。
|
||||
class AdMedia extends StatefulWidget {
|
||||
const AdMedia({
|
||||
super.key,
|
||||
required this.ad,
|
||||
this.assetPath,
|
||||
this.fit = BoxFit.cover,
|
||||
});
|
||||
final AdCreative ad;
|
||||
final String? assetPath;
|
||||
final BoxFit fit;
|
||||
@override
|
||||
State<AdMedia> createState() => _AdMediaState();
|
||||
}
|
||||
|
||||
class _AdMediaState extends State<AdMedia> {
|
||||
VideoPlayerController? player;
|
||||
bool ready = false, failed = false;
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_load();
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant AdMedia old) {
|
||||
super.didUpdateWidget(old);
|
||||
if (old.ad.adId != widget.ad.adId || old.assetPath != widget.assetPath) {
|
||||
unawaited(player?.dispose() ?? Future.value());
|
||||
player = null;
|
||||
ready = false;
|
||||
failed = false;
|
||||
_load();
|
||||
}
|
||||
}
|
||||
|
||||
void _load() {
|
||||
if (widget.ad.mediaType != AdMediaType.video) return;
|
||||
final uri = widget.ad.mediaUri;
|
||||
if (uri == null) return;
|
||||
final path = widget.assetPath;
|
||||
final controller = !kIsWeb && path != null && path.isNotEmpty
|
||||
? VideoPlayerController.file(File(path))
|
||||
: VideoPlayerController.networkUrl(uri);
|
||||
player = controller;
|
||||
unawaited(
|
||||
controller
|
||||
.initialize()
|
||||
.then((_) async {
|
||||
await controller.setLooping(true);
|
||||
await controller.setVolume(0);
|
||||
await controller.play();
|
||||
if (mounted) setState(() => ready = true);
|
||||
})
|
||||
.catchError((_) {
|
||||
if (mounted) setState(() => failed = true);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
player?.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (widget.ad.mediaType != AdMediaType.video) {
|
||||
final path = widget.assetPath;
|
||||
if (!kIsWeb && path != null && path.isNotEmpty) {
|
||||
return Image.file(
|
||||
File(path),
|
||||
fit: widget.fit,
|
||||
width: double.infinity,
|
||||
height: double.infinity,
|
||||
errorBuilder: (_, _, _) => _error(),
|
||||
);
|
||||
}
|
||||
return Image.network(
|
||||
widget.ad.imageUrl,
|
||||
fit: widget.fit,
|
||||
width: double.infinity,
|
||||
height: double.infinity,
|
||||
errorBuilder: (_, _, _) => _error(),
|
||||
);
|
||||
}
|
||||
final c = player;
|
||||
if (failed) return _error();
|
||||
if (c == null || !ready) {
|
||||
return const ColoredBox(
|
||||
color: Color(0xFF161616),
|
||||
child: Center(child: CircularProgressIndicator()),
|
||||
);
|
||||
}
|
||||
return FittedBox(
|
||||
fit: widget.fit,
|
||||
clipBehavior: Clip.hardEdge,
|
||||
child: SizedBox(
|
||||
width: c.value.size.width,
|
||||
height: c.value.size.height,
|
||||
child: VideoPlayer(c),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _error() => const ColoredBox(
|
||||
color: Color(0xFF161616),
|
||||
child: Center(
|
||||
child: Icon(Icons.broken_image_outlined, color: Colors.white54),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
import '../../../common/router/app_router.dart';
|
||||
import '../data/ads_api_client.dart';
|
||||
import 'ad_media.dart';
|
||||
|
||||
class HomeAdBanner extends ConsumerStatefulWidget {
|
||||
const HomeAdBanner({super.key});
|
||||
@override
|
||||
ConsumerState<HomeAdBanner> createState() => _HomeAdBannerState();
|
||||
}
|
||||
|
||||
class _HomeAdBannerState extends ConsumerState<HomeAdBanner> {
|
||||
final pages = PageController();
|
||||
final impressed = <String>{};
|
||||
Timer? timer;
|
||||
int index = 0;
|
||||
int _length = 0;
|
||||
@override
|
||||
void dispose() {
|
||||
timer?.cancel();
|
||||
pages.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _sync(List<AdCreative> ads) {
|
||||
if (_length == ads.length) return;
|
||||
_length = ads.length;
|
||||
timer?.cancel();
|
||||
if (ads.length > 1) {
|
||||
timer = Timer.periodic(const Duration(seconds: 4), (_) {
|
||||
if (pages.hasClients) {
|
||||
pages.nextPage(
|
||||
duration: const Duration(milliseconds: 320),
|
||||
curve: Curves.easeOut,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void _impression(AdCreative ad, String? id) {
|
||||
if (!impressed.add(ad.adId)) return;
|
||||
unawaited(
|
||||
ref
|
||||
.read(adsApiClientProvider)
|
||||
.report(ad, 'ad_impression', trackingId: id),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _open(AdCreative ad, String? tracking) async {
|
||||
final client = ref.read(adsApiClientProvider);
|
||||
final id = client.newClickId();
|
||||
final uri = ad.clickUri(id);
|
||||
if (uri == null) return;
|
||||
unawaited(client.report(ad, 'ad_click', clickId: id, trackingId: tracking));
|
||||
if (!mounted) return;
|
||||
if (ad.openMode == AdOpenMode.inApp) {
|
||||
context.push(
|
||||
'${AppRoutes.web}?url=${Uri.encodeComponent(uri.toString())}',
|
||||
);
|
||||
} else {
|
||||
await launchUrl(uri, mode: LaunchMode.externalApplication);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final async = ref.watch(featuredAdsProvider(homeBannerAdPlacement));
|
||||
return async.maybeWhen(
|
||||
data: (value) {
|
||||
if (!value.hasAds) return const SizedBox.shrink();
|
||||
final ads = value.ads;
|
||||
_sync(ads);
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted) {
|
||||
_impression(ads[index.clamp(0, ads.length - 1)], value.trackingId);
|
||||
}
|
||||
});
|
||||
return Column(
|
||||
children: [
|
||||
AspectRatio(
|
||||
aspectRatio: 750 / 200,
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
child: PageView.builder(
|
||||
controller: pages,
|
||||
onPageChanged: (page) {
|
||||
setState(() => index = page % ads.length);
|
||||
_impression(ads[index], value.trackingId);
|
||||
},
|
||||
itemBuilder: (_, page) {
|
||||
final ad = ads[page % ads.length];
|
||||
return GestureDetector(
|
||||
onTap: () => _open(ad, value.trackingId),
|
||||
child: AdMedia(ad: ad),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
if (ads.length > 1)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: List.generate(
|
||||
ads.length,
|
||||
(i) => Container(
|
||||
width: i == index ? 14 : 6,
|
||||
height: 6,
|
||||
margin: const EdgeInsets.symmetric(horizontal: 3),
|
||||
decoration: BoxDecoration(
|
||||
color: i == index
|
||||
? Theme.of(context).colorScheme.primary
|
||||
: Theme.of(context).dividerColor,
|
||||
borderRadius: BorderRadius.circular(3),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
orElse: () => const SizedBox.shrink(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../application/splash_ad_controller.dart';
|
||||
import 'ad_media.dart';
|
||||
|
||||
enum SplashAdResult { clicked, skipped, completed }
|
||||
|
||||
class SplashAdDialog extends StatefulWidget {
|
||||
const SplashAdDialog({
|
||||
super.key,
|
||||
required this.entry,
|
||||
required this.onClick,
|
||||
required this.onShown,
|
||||
});
|
||||
final SplashAdEntry entry;
|
||||
final Future<void> Function() onClick;
|
||||
final VoidCallback onShown;
|
||||
@override
|
||||
State<SplashAdDialog> createState() => _SplashAdDialogState();
|
||||
}
|
||||
|
||||
class _SplashAdDialogState extends State<SplashAdDialog> {
|
||||
Timer? timer;
|
||||
late int remain;
|
||||
bool opening = false;
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
remain = widget.entry.ad.countdownSeconds.clamp(1, 5);
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
widget.onShown();
|
||||
});
|
||||
timer = Timer.periodic(const Duration(seconds: 1), (_) {
|
||||
if (remain <= 1) {
|
||||
Navigator.of(context).pop(SplashAdResult.completed);
|
||||
} else if (mounted) {
|
||||
setState(() => remain--);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
timer?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> open() async {
|
||||
if (opening) return;
|
||||
opening = true;
|
||||
timer?.cancel();
|
||||
await widget.onClick();
|
||||
if (mounted) Navigator.of(context).pop(SplashAdResult.clicked);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Material(
|
||||
color: Colors.black,
|
||||
child: Stack(
|
||||
children: [
|
||||
Positioned.fill(
|
||||
child: GestureDetector(
|
||||
onTap: open,
|
||||
child: AdMedia(
|
||||
ad: widget.entry.ad,
|
||||
assetPath: widget.entry.assetPath,
|
||||
),
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
top: MediaQuery.paddingOf(context).top + 16,
|
||||
right: 18,
|
||||
child: FilledButton(
|
||||
onPressed: () => Navigator.of(context).pop(SplashAdResult.skipped),
|
||||
child: Text('跳过 ${remain}s'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user