Files
patbond-flutter/lib/analytics/analytics_service.dart
T
lixi 3f8388e5d4
CI / flutter-gates (push) Successful in 50s
fix: 清零 flutter analyze 问题并修复隐私红线正则缺陷(CI 门禁)
- 修复真实缺陷:隐私红线 RegExp 使用 Dart 不支持的 (?i) 内联标志,构造即抛异常
  导致带 props 的事件被静默丢弃;改为 caseSensitive: false
- 清理埋点模块未用 import/字段/变量(4 warning)
- 构造函数改用初始化形参(含 Dart 3.12 私有具名参数)
- E2E 手动脚本声明 ignore avoid_print + library 指令
- 门禁:format 0 changed / analyze No issues / flutter test 34 passed
2026-09-04 19:44:46 +08:00

112 lines
3.6 KiB
Dart

import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:uuid/uuid.dart';
/// Simplified analytics client for M0 (report 13 + ticket 19): track events
/// to backend POST /api/v1/events. Queue failures locally (shared_preferences,
/// max 500), flush on successful upload or when full. Network errors are
/// silently discarded (no retry as spec'd); privacy red-line enforced locally.
class AnalyticsService {
AnalyticsService({
required this.apiBaseUrl,
required this.getAccessToken,
String? anonymousId,
this._userId,
}) : _anonymousId = anonymousId ?? const Uuid().v4();
// M0:内存队列,满 _flushThreshold 条上传一次;持久化队列留 M1(报告 19 §3)。
static const _flushThreshold = 20;
final String apiBaseUrl;
final String Function()? getAccessToken;
final String _anonymousId;
String? _userId;
final List<Map<String, dynamic>> _pendingEvents = [];
/// Sets userId after login (M0: no sessionId logic, simplified).
void identify(String userId) {
_userId = userId;
}
/// Clears userId on logout (anonymousId remains).
void reset() {
_userId = null;
}
/// Tracks event (never throws, never awaits network). Props are validated
/// for privacy red-line patterns locally before queuing.
Future<void> trackEvent(
String eventName, [
Map<String, dynamic>? props,
]) async {
try {
if (props != null && _containsForbiddenField(props)) {
debugPrint('Analytics: event $eventName rejected (forbidden field)');
return;
}
final event = {
'eventId': const Uuid().v4(),
'eventName': eventName,
'eventVersion': 1,
'anonymousId': _anonymousId,
if (_userId != null) 'userId': _userId,
'sessionId': const Uuid().v4(), // Simplified: unique per event (M0)
'clientTs': DateTime.now().toUtc().toIso8601String(),
'appVersion': '1.0.0+1', // TODO: read from package_info_plus
'platform': Platform.isAndroid ? 'android' : 'ios',
'osVersion': Platform.isAndroid
? 'android-14'
: 'ios-17', // TODO: device_info_plus
if (props != null && props.isNotEmpty) 'props': props,
};
_pendingEvents.add(event);
if (_pendingEvents.length >= _flushThreshold) {
await _flush();
}
} catch (error) {
debugPrint('Analytics track failed: $error');
}
}
Future<void> _flush() async {
if (_pendingEvents.isEmpty) return;
final batch = List<Map<String, dynamic>>.from(_pendingEvents);
_pendingEvents.clear();
try {
await _upload(batch);
} catch (error) {
debugPrint('Analytics upload failed, discarding batch: $error');
}
}
Future<void> _upload(List<Map<String, dynamic>> events) async {
final token = getAccessToken?.call();
final request =
await HttpClient().postUrl(Uri.parse('$apiBaseUrl/api/v1/events'))
..headers.contentType = ContentType.json;
if (token != null) {
request.headers.add('Authorization', 'Bearer $token');
}
request.add(utf8.encode(jsonEncode({'events': events})));
final response = await request.close();
if (response.statusCode != 202) {
throw Exception('Upload failed with ${response.statusCode}');
}
}
bool _containsForbiddenField(Map<String, dynamic> props) {
// Dart RegExp 不支持 (?i) 内联标志(原写法构造即抛异常,事件被静默丢弃)。
final pattern = RegExp(
r'password|token|secret|phone|mobile|email|credential|idfa|gaid',
caseSensitive: false,
);
return props.keys.any((key) => pattern.hasMatch(key));
}
}