mirror of
https://github.com/GopeedLab/gopeed.git
synced 2026-11-12 11:24:08 +00:00
fix(analytics): use Android ID and persist UUID fallbacks (#1624)
This commit is contained in:
9 files changed
+61
-29
No files matched your search
@@ -1,8 +1,10 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:android_id/android_id.dart';
|
||||
import 'package:device_info_plus/device_info_plus.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
import 'log_util.dart';
|
||||
import 'package_info.dart';
|
||||
@@ -31,12 +33,23 @@ class Analytics {
|
||||
|
||||
String get clientId => _initialized ? _clientId : '';
|
||||
|
||||
Future<void> init({String fallbackClientId = ''}) async {
|
||||
if (_initialized || !AnalyticsConfig.isConfigured) return;
|
||||
_clientId = await _getDeviceId(fallbackClientId);
|
||||
/// Returns a newly generated fallback ID for the caller to persist, if any.
|
||||
Future<String?> init({String fallbackClientId = ''}) async {
|
||||
if (_initialized || !AnalyticsConfig.isConfigured) return null;
|
||||
final deviceId = await _getDeviceId();
|
||||
String? generatedClientId;
|
||||
if (deviceId != null && deviceId.isNotEmpty) {
|
||||
_clientId = deviceId;
|
||||
} else if (fallbackClientId.isNotEmpty) {
|
||||
_clientId = fallbackClientId;
|
||||
} else {
|
||||
_clientId = const Uuid().v4();
|
||||
generatedClientId = _clientId;
|
||||
}
|
||||
_sessionId = DateTime.now().millisecondsSinceEpoch ~/ 1000;
|
||||
_dio = Dio(BaseOptions(connectTimeout: const Duration(seconds: 10), receiveTimeout: const Duration(seconds: 10)));
|
||||
_initialized = true;
|
||||
return generatedClientId;
|
||||
}
|
||||
|
||||
Future<void> logAppOpen() => logEvent('app_open');
|
||||
@@ -70,14 +83,14 @@ class Analytics {
|
||||
}
|
||||
}
|
||||
|
||||
Future<String> _getDeviceId(String fallbackClientId) async {
|
||||
Future<String?> _getDeviceId() async {
|
||||
if (kIsWeb) return null;
|
||||
|
||||
String? deviceId;
|
||||
try {
|
||||
final info = DeviceInfoPlugin();
|
||||
if (kIsWeb) {
|
||||
deviceId = null;
|
||||
} else if (Platform.isAndroid) {
|
||||
deviceId = (await info.androidInfo).id;
|
||||
if (Platform.isAndroid) {
|
||||
deviceId = await const AndroidId().getId();
|
||||
} else if (Platform.isIOS) {
|
||||
deviceId = (await info.iosInfo).identifierForVendor;
|
||||
} else if (Platform.isMacOS) {
|
||||
@@ -91,14 +104,6 @@ class Analytics {
|
||||
logger.w('GA4Analytics: failed to read device id: $error');
|
||||
}
|
||||
|
||||
if (deviceId == null || deviceId.isEmpty) {
|
||||
deviceId = fallbackClientId;
|
||||
if (deviceId.isEmpty) {
|
||||
final random = DateTime.now().microsecondsSinceEpoch % 2147483647;
|
||||
final timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000;
|
||||
deviceId = '$random.$timestamp';
|
||||
}
|
||||
}
|
||||
return deviceId;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user