branch backend + ajout du serveur backend, next, et sqlite
This commit is contained in:
@@ -18,6 +18,7 @@ import '../../services/score_calculator_service.dart';
|
||||
import '../../services/grouping_analyzer_service.dart';
|
||||
import '../../services/distortion_correction_service.dart';
|
||||
import '../../services/opencv_target_service.dart';
|
||||
import '../../services/ai_export_service.dart';
|
||||
|
||||
enum AnalysisState { initial, loading, success, error }
|
||||
|
||||
@@ -688,6 +689,42 @@ class AnalysisProvider extends ChangeNotifier {
|
||||
_groupingResult = _groupingAnalyzerService.analyzeGrouping(_shots);
|
||||
}
|
||||
|
||||
/// Exporte l'image et le json vers le backend IA
|
||||
Future<bool> exportToAiBackend() async {
|
||||
if (_imagePath == null || _targetType == null) {
|
||||
_errorMessage = "Impossible d'exporter : image ou type de cible manquant.";
|
||||
notifyListeners();
|
||||
return false;
|
||||
}
|
||||
|
||||
// Identifiant de session temporaire si non sauvegardée
|
||||
final sessionId = _shots.isNotEmpty && _shots.first.sessionId.isNotEmpty
|
||||
? _shots.first.sessionId
|
||||
: 'session_${DateTime.now().millisecondsSinceEpoch}';
|
||||
|
||||
final service = AiExportService(); // Local instanciation for simplicity
|
||||
|
||||
_state = AnalysisState.loading;
|
||||
notifyListeners();
|
||||
|
||||
final success = await service.exportData(
|
||||
imagePath: _imagePath!,
|
||||
sessionId: sessionId,
|
||||
targetType: _targetType!,
|
||||
targetCenterX: _targetCenterX,
|
||||
targetCenterY: _targetCenterY,
|
||||
targetRadius: _targetRadius,
|
||||
shots: _shots,
|
||||
);
|
||||
|
||||
_state = AnalysisState.success;
|
||||
if (!success) {
|
||||
_errorMessage = "Échec de l'export vers le serveur IA.";
|
||||
}
|
||||
notifyListeners();
|
||||
return success;
|
||||
}
|
||||
|
||||
/// Save the session
|
||||
Future<Session> saveSession({String? notes}) async {
|
||||
if (_imagePath == null || _targetType == null) {
|
||||
|
||||
@@ -15,6 +15,7 @@ import '../../data/repositories/session_repository.dart';
|
||||
import '../../services/target_detection_service.dart';
|
||||
import '../../services/score_calculator_service.dart';
|
||||
import '../../services/grouping_analyzer_service.dart';
|
||||
import '../../services/wallet_identity_service.dart';
|
||||
import 'analysis_provider.dart';
|
||||
import 'widgets/target_overlay.dart';
|
||||
import 'widgets/target_calibration.dart';
|
||||
@@ -133,6 +134,47 @@ class _AnalysisScreenContentState extends State<_AnalysisScreenContent> {
|
||||
);
|
||||
},
|
||||
),
|
||||
FutureBuilder<bool>(
|
||||
future: WalletIdentityService().isUploadEnabled(),
|
||||
builder: (context, snapshot) {
|
||||
final isEnabled = snapshot.data ?? false;
|
||||
if (!isEnabled) return const SizedBox.shrink();
|
||||
|
||||
return IconButton(
|
||||
icon: const Icon(Icons.cloud_upload),
|
||||
onPressed: () async {
|
||||
final provider = context.read<AnalysisProvider>();
|
||||
if (provider.state != AnalysisState.success) return;
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Exportation en cours...')),
|
||||
);
|
||||
|
||||
final success = await provider.exportToAiBackend();
|
||||
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).hideCurrentSnackBar();
|
||||
if (success) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Export réussi vers le backend IA !'),
|
||||
backgroundColor: AppTheme.successColor,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(provider.errorMessage ?? 'Erreur d\'export'),
|
||||
backgroundColor: AppTheme.errorColor,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
tooltip: 'Exporter pour IA',
|
||||
);
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.help_outline),
|
||||
onPressed: () => _showHelpDialog(context),
|
||||
|
||||
@@ -12,6 +12,7 @@ import '../../data/repositories/session_repository.dart';
|
||||
import '../capture/capture_screen.dart';
|
||||
import '../history/history_screen.dart';
|
||||
import '../statistics/statistics_screen.dart';
|
||||
import '../settings/settings_screen.dart';
|
||||
import 'widgets/stats_card.dart';
|
||||
|
||||
class HomeScreen extends StatefulWidget {
|
||||
@@ -58,6 +59,11 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
onPressed: () => _navigateToHistory(context),
|
||||
tooltip: 'Historique',
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.settings),
|
||||
onPressed: () => _navigateToSettings(context),
|
||||
tooltip: 'Paramètres',
|
||||
),
|
||||
],
|
||||
),
|
||||
body: RefreshIndicator(
|
||||
@@ -237,4 +243,11 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
// Refresh stats when returning
|
||||
_loadStats();
|
||||
}
|
||||
|
||||
void _navigateToSettings(BuildContext context) {
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(builder: (_) => const SettingsScreen()),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
339
lib/features/settings/settings_screen.dart
Normal file
339
lib/features/settings/settings_screen.dart
Normal file
@@ -0,0 +1,339 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'dart:convert';
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import '../../core/constants/app_constants.dart';
|
||||
import '../../core/theme/app_theme.dart';
|
||||
import '../../services/wallet_identity_service.dart';
|
||||
|
||||
class SettingsScreen extends StatefulWidget {
|
||||
const SettingsScreen({super.key});
|
||||
|
||||
@override
|
||||
State<SettingsScreen> createState() => _SettingsScreenState();
|
||||
}
|
||||
|
||||
class _SettingsScreenState extends State<SettingsScreen> {
|
||||
final WalletIdentityService _walletService = WalletIdentityService();
|
||||
String? _identityPhrase;
|
||||
int? _photoCount;
|
||||
bool _isLoadingStats = false;
|
||||
bool _isUploadEnabled = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadIdentity();
|
||||
}
|
||||
|
||||
Future<void> _loadIdentity() async {
|
||||
final phrase = await _walletService.getIdentityPhrase();
|
||||
final isEnabled = await _walletService.isUploadEnabled();
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_identityPhrase = phrase;
|
||||
_isUploadEnabled = isEnabled;
|
||||
});
|
||||
_fetchStats(phrase);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _fetchStats(String phrase) async {
|
||||
setState(() => _isLoadingStats = true);
|
||||
try {
|
||||
final phraseBytes = utf8.encode(phrase);
|
||||
final walletHash = sha256.convert(phraseBytes).toString();
|
||||
|
||||
// Utilise 10.0.2.2 pour l'émulateur Android, sinon localhost
|
||||
final baseUrl = Theme.of(context).platform == TargetPlatform.android
|
||||
? 'http://10.0.2.2:3000'
|
||||
: 'http://localhost:3000';
|
||||
|
||||
final response = await http.get(Uri.parse('$baseUrl/api/stats/$walletHash'));
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final data = jsonDecode(response.body);
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_photoCount = data['stats']['photo_count'] ?? 0;
|
||||
_isLoadingStats = false;
|
||||
});
|
||||
}
|
||||
} else {
|
||||
if (mounted) setState(() => _isLoadingStats = false);
|
||||
}
|
||||
} catch (e) {
|
||||
print('Erreur lors du chargement des statistiques: $e');
|
||||
if (mounted) setState(() => _isLoadingStats = false);
|
||||
}
|
||||
}
|
||||
|
||||
void _copyToClipboard() {
|
||||
if (_identityPhrase != null) {
|
||||
Clipboard.setData(ClipboardData(text: _identityPhrase!));
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Identité copiée dans le presse-papiers'),
|
||||
backgroundColor: AppTheme.successColor,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void _showIdentityDialog() {
|
||||
if (_identityPhrase == null) return;
|
||||
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('Votre Identité Unique', textAlign: TextAlign.center),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Icon(Icons.security, size: 48, color: AppTheme.primaryColor),
|
||||
const SizedBox(height: 16),
|
||||
const Text(
|
||||
'Cette phrase de 15 mots vous identifie de manière unique. Ne la partagez qu\'en cas de besoin.',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(fontSize: 14, color: Colors.grey),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.grey.withAlpha(20),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: AppTheme.primaryColor.withAlpha(100)),
|
||||
),
|
||||
child: Text(
|
||||
_identityPhrase!,
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
letterSpacing: 0.5,
|
||||
height: 1.5,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: const Text('Fermer'),
|
||||
),
|
||||
ElevatedButton.icon(
|
||||
icon: const Icon(Icons.copy, size: 18),
|
||||
label: const Text('Copier'),
|
||||
onPressed: () {
|
||||
_copyToClipboard();
|
||||
Navigator.pop(context);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _showOptInDisclaimer(bool value) {
|
||||
if (!value) {
|
||||
// Si on désactive, pas besoin de disclaimer, on le fait direct.
|
||||
_walletService.setUploadEnabled(false);
|
||||
setState(() {
|
||||
_isUploadEnabled = false;
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
showDialog(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('Participer à l\'entraînement IA', textAlign: TextAlign.center),
|
||||
content: const Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.psychology, size: 48, color: AppTheme.primaryColor),
|
||||
SizedBox(height: 16),
|
||||
Text(
|
||||
'En activant cette option, vous acceptez d\'envoyer vos photos de cibles à notre serveur sécurisé.',
|
||||
style: TextStyle(fontWeight: FontWeight.bold),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
SizedBox(height: 12),
|
||||
Text(
|
||||
'🔒 Anonymat Garanti : L\'envoi est totalement anonymisé. Votre identité est remplacée par un hash cryptographique incassable.',
|
||||
style: TextStyle(fontSize: 13),
|
||||
),
|
||||
SizedBox(height: 12),
|
||||
Text(
|
||||
'🎁 Avantages Futurs : Votre contribution (Hash de Wallet) sera comptabilisée. Lors de la sortie publique de notre IA, les participants actifs recevront des fonctionnalités premium ou des badges exclusifs en récompense !',
|
||||
style: TextStyle(fontSize: 13),
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: const Text('Refuser', style: TextStyle(color: Colors.grey)),
|
||||
),
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(backgroundColor: AppTheme.primaryColor),
|
||||
onPressed: () {
|
||||
_walletService.setUploadEnabled(true);
|
||||
setState(() {
|
||||
_isUploadEnabled = true;
|
||||
});
|
||||
Navigator.pop(context);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Merci pour votre contribution !'),
|
||||
backgroundColor: AppTheme.successColor,
|
||||
),
|
||||
);
|
||||
},
|
||||
child: const Text('J\'accepte', style: TextStyle(color: Colors.white)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Paramètres'),
|
||||
),
|
||||
body: ListView(
|
||||
padding: const EdgeInsets.all(AppConstants.defaultPadding),
|
||||
children: [
|
||||
_buildSectionHeader('Identité'),
|
||||
_buildSettingsTile(
|
||||
context: context,
|
||||
icon: Icons.fingerprint,
|
||||
title: 'Identité Wallet',
|
||||
subtitle: _identityPhrase != null ? 'Phrase de 15 mots générée' : 'Génération en cours...',
|
||||
onTap: _showIdentityDialog,
|
||||
),
|
||||
_buildSettingsTile(
|
||||
context: context,
|
||||
icon: Icons.color_lens_outlined,
|
||||
title: 'Apparence',
|
||||
subtitle: 'Thème clair/sombre (à venir)',
|
||||
onTap: () {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Fonctionnalité en développement')),
|
||||
);
|
||||
},
|
||||
),
|
||||
|
||||
const SizedBox(height: 24),
|
||||
_buildSectionHeader('Configuration Serveur IA'),
|
||||
Card(
|
||||
elevation: 0,
|
||||
color: Colors.transparent,
|
||||
margin: const EdgeInsets.only(bottom: 8.0),
|
||||
child: SwitchListTile(
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 4.0),
|
||||
title: const Text('Participer à l\'entraînement IA', style: TextStyle(fontWeight: FontWeight.w500)),
|
||||
subtitle: const Text('Aidez-nous à améliorer la détection tout en gagnant des avantages', style: TextStyle(fontSize: 12)),
|
||||
secondary: const Icon(Icons.psychology, color: AppTheme.textPrimary),
|
||||
value: _isUploadEnabled,
|
||||
activeColor: AppTheme.primaryColor,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12.0),
|
||||
side: BorderSide(color: Colors.grey.withAlpha(50), width: 1),
|
||||
),
|
||||
onChanged: _showOptInDisclaimer,
|
||||
),
|
||||
),
|
||||
if (_isUploadEnabled)
|
||||
_buildSettingsTile(
|
||||
context: context,
|
||||
icon: Icons.cloud_outlined,
|
||||
title: 'Adresse du Serveur IA',
|
||||
subtitle: 'http://localhost:3000/api/upload',
|
||||
onTap: () {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Changement d\'adresse à venir')),
|
||||
);
|
||||
},
|
||||
),
|
||||
if (_isUploadEnabled)
|
||||
_buildSettingsTile(
|
||||
context: context,
|
||||
icon: Icons.data_usage,
|
||||
title: 'Photos Exportées',
|
||||
subtitle: _isLoadingStats
|
||||
? 'Chargement...'
|
||||
: (_photoCount != null ? '$_photoCount photos envoyées à l\'IA' : 'Non disponible'),
|
||||
onTap: () {
|
||||
if (_identityPhrase != null) {
|
||||
_fetchStats(_identityPhrase!);
|
||||
}
|
||||
},
|
||||
),
|
||||
|
||||
const SizedBox(height: 24),
|
||||
_buildSectionHeader('À propos'),
|
||||
_buildSettingsTile(
|
||||
context: context,
|
||||
icon: Icons.info_outline,
|
||||
title: 'Version de l\'application',
|
||||
subtitle: '1.0.0',
|
||||
onTap: () {},
|
||||
),
|
||||
_buildSettingsTile(
|
||||
context: context,
|
||||
icon: Icons.privacy_tip_outlined,
|
||||
title: 'Politique de confidentialité',
|
||||
onTap: () {},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSectionHeader(String title) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 4.0),
|
||||
child: Text(
|
||||
title,
|
||||
style: const TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: AppTheme.primaryColor,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSettingsTile({
|
||||
required BuildContext context,
|
||||
required IconData icon,
|
||||
required String title,
|
||||
String? subtitle,
|
||||
required VoidCallback onTap,
|
||||
}) {
|
||||
return Card(
|
||||
elevation: 0,
|
||||
color: Colors.transparent,
|
||||
margin: const EdgeInsets.only(bottom: 8.0),
|
||||
child: ListTile(
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 4.0),
|
||||
leading: Icon(icon, color: AppTheme.textPrimary),
|
||||
title: Text(title, style: const TextStyle(fontWeight: FontWeight.w500)),
|
||||
subtitle: subtitle != null ? Text(subtitle, style: const TextStyle(fontSize: 12)) : null,
|
||||
trailing: const Icon(Icons.chevron_right, color: Colors.grey),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12.0),
|
||||
side: BorderSide(color: Colors.grey.withAlpha(50), width: 1),
|
||||
),
|
||||
onTap: onTap,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
146
lib/services/ai_export_service.dart
Normal file
146
lib/services/ai_export_service.dart
Normal file
@@ -0,0 +1,146 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:device_info_plus/device_info_plus.dart';
|
||||
import 'package:crypto/crypto.dart';
|
||||
import '../data/models/shot.dart';
|
||||
import '../data/models/target_type.dart';
|
||||
import 'wallet_identity_service.dart';
|
||||
|
||||
class AiExportService {
|
||||
// Utilise 10.0.2.2 pour l'émulateur Android, sinon localhost.
|
||||
// Pour un appareil physique, il faudra utiliser l'IP locale du PC (ex: 192.168.1.X).
|
||||
static String get _defaultApiUrl {
|
||||
if (Platform.isAndroid) {
|
||||
return 'http://10.0.2.2:3000/api/upload';
|
||||
}
|
||||
return 'http://localhost:3000/api/upload';
|
||||
}
|
||||
|
||||
/// Extrait les informations de l'appareil
|
||||
Future<Map<String, dynamic>> _getDeviceInfo() async {
|
||||
final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
|
||||
Map<String, dynamic> deviceData = {'model': 'Unknown', 'os': 'Unknown'};
|
||||
|
||||
try {
|
||||
if (Platform.isAndroid) {
|
||||
final androidInfo = await deviceInfoPlugin.androidInfo;
|
||||
deviceData['model'] = '${androidInfo.brand} ${androidInfo.model}';
|
||||
deviceData['os'] = 'Android ${androidInfo.version.release}';
|
||||
} else if (Platform.isIOS) {
|
||||
final iosInfo = await deviceInfoPlugin.iosInfo;
|
||||
deviceData['model'] = iosInfo.name;
|
||||
deviceData['os'] = '${iosInfo.systemName} ${iosInfo.systemVersion}';
|
||||
} else if (Platform.isWindows) {
|
||||
final windowsInfo = await deviceInfoPlugin.windowsInfo;
|
||||
deviceData['model'] = 'Windows PC';
|
||||
deviceData['os'] = 'Windows ${windowsInfo.majorVersion}.${windowsInfo.minorVersion}';
|
||||
}
|
||||
} catch (e) {
|
||||
print('Erreur lors de la récupération des infos appareil: $e');
|
||||
}
|
||||
|
||||
return deviceData;
|
||||
}
|
||||
|
||||
/// Exporte l'image et les données de plotting vers le serveur
|
||||
Future<bool> exportData({
|
||||
required String imagePath,
|
||||
required String sessionId,
|
||||
required TargetType targetType,
|
||||
required double targetCenterX,
|
||||
required double targetCenterY,
|
||||
required double targetRadius,
|
||||
required List<Shot> shots,
|
||||
String? apiUrl,
|
||||
}) async {
|
||||
try {
|
||||
final url = Uri.parse(apiUrl ?? _defaultApiUrl);
|
||||
final request = http.MultipartRequest('POST', url);
|
||||
|
||||
// 1. Prepare image
|
||||
final file = File(imagePath);
|
||||
if (!await file.exists()) {
|
||||
throw Exception('Le fichier image n\'existe pas');
|
||||
}
|
||||
|
||||
// Read image metadata (approximate dimensions since decoding image can be heavy)
|
||||
// On the frontend we usually have aspectRatio, here we use generic values if not available.
|
||||
final deviceData = await _getDeviceInfo();
|
||||
|
||||
// We approximate the target corners from center and radius
|
||||
// radius is relative (0 to 1). We need image width/height to get pixels.
|
||||
// But we can just pass relative corners as well, or a normalized bounding box.
|
||||
// Let's create normalized corners (0 to 1).
|
||||
final corners = [
|
||||
{"norm_x": targetCenterX - targetRadius, "norm_y": targetCenterY - targetRadius},
|
||||
{"norm_x": targetCenterX + targetRadius, "norm_y": targetCenterY - targetRadius},
|
||||
{"norm_x": targetCenterX + targetRadius, "norm_y": targetCenterY + targetRadius},
|
||||
{"norm_x": targetCenterX - targetRadius, "norm_y": targetCenterY + targetRadius},
|
||||
];
|
||||
|
||||
// Format the impacts
|
||||
final formattedImpacts = shots.asMap().entries.map((entry) {
|
||||
final index = entry.key;
|
||||
final shot = entry.value;
|
||||
return {
|
||||
"id": index + 1,
|
||||
"label": "bullet_hole",
|
||||
"score": shot.score,
|
||||
"coords": {
|
||||
"norm_x": shot.x,
|
||||
"norm_y": shot.y
|
||||
}
|
||||
};
|
||||
}).toList();
|
||||
|
||||
// Get and hash the wallet identity
|
||||
final walletService = WalletIdentityService();
|
||||
final phrase = await walletService.getIdentityPhrase();
|
||||
final phraseBytes = utf8.encode(phrase);
|
||||
final walletHash = sha256.convert(phraseBytes).toString();
|
||||
|
||||
// Build JSON payload
|
||||
final plottingJson = {
|
||||
"session_id": sessionId,
|
||||
"wallet_hash": walletHash,
|
||||
"timestamp": DateTime.now().toIso8601String(),
|
||||
"device_info": deviceData,
|
||||
"target_metadata": {
|
||||
"type": targetType.name,
|
||||
"distance_meters": 25, // Default/placeholder
|
||||
"weapon": "Unknown", // Default/placeholder
|
||||
// The backend could extract exact width/height from the image.
|
||||
},
|
||||
"plotting": {
|
||||
"target_corners": corners,
|
||||
"impacts": formattedImpacts
|
||||
}
|
||||
};
|
||||
|
||||
// Add fields to request
|
||||
request.fields['plotting'] = jsonEncode(plottingJson);
|
||||
|
||||
// Add file
|
||||
request.files.add(
|
||||
await http.MultipartFile.fromPath('photo', imagePath),
|
||||
);
|
||||
|
||||
// Send request
|
||||
final response = await request.send();
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final responseData = await response.stream.bytesToString();
|
||||
print('Export réussi: $responseData');
|
||||
return true;
|
||||
} else {
|
||||
final errorData = await response.stream.bytesToString();
|
||||
print('Erreur d\'export: ${response.statusCode} - $errorData');
|
||||
return false;
|
||||
}
|
||||
} catch (e) {
|
||||
print('Exception lors de l\'export: $e');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
112
lib/services/wallet_identity_service.dart
Normal file
112
lib/services/wallet_identity_service.dart
Normal file
@@ -0,0 +1,112 @@
|
||||
import 'dart:math';
|
||||
import 'dart:convert';
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:device_info_plus/device_info_plus.dart';
|
||||
import 'dart:io';
|
||||
|
||||
class WalletIdentityService {
|
||||
static const String _prefsKey = 'wallet_identity_phrase';
|
||||
static const String _uploadEnabledKey = 'is_ai_upload_enabled';
|
||||
|
||||
// A standard list of 256 words (8 bits of entropy per word)
|
||||
static const List<String> _wordList = [
|
||||
// ... same as before
|
||||
'abandon', 'ability', 'able', 'about', 'above', 'absent', 'absorb', 'abstract', 'absurd', 'abuse',
|
||||
'access', 'accident', 'account', 'accuse', 'achieve', 'acid', 'acoustic', 'acquire', 'across', 'act',
|
||||
'action', 'actor', 'actress', 'actual', 'adapt', 'add', 'addict', 'address', 'adjust', 'admit',
|
||||
'adult', 'advance', 'advice', 'aerobic', 'affair', 'afford', 'afraid', 'again', 'age', 'agent',
|
||||
'agree', 'ahead', 'aim', 'air', 'airport', 'aisle', 'alarm', 'album', 'alcohol', 'alert',
|
||||
'alien', 'all', 'alley', 'allow', 'almost', 'alone', 'alpha', 'already', 'also', 'alter',
|
||||
'always', 'amateur', 'amazing', 'among', 'amount', 'amused', 'analyst', 'anchor', 'ancient', 'anger',
|
||||
'angle', 'angry', 'animal', 'ankle', 'announce', 'annual', 'another', 'answer', 'antenna', 'antique',
|
||||
'anxiety', 'any', 'apart', 'apology', 'appear', 'apple', 'approve', 'april', 'arch', 'arctic',
|
||||
'area', 'arena', 'argue', 'arm', 'armed', 'armor', 'army', 'around', 'arrange', 'arrest',
|
||||
'arrive', 'arrow', 'art', 'artefact', 'artist', 'artwork', 'ask', 'aspect', 'assault', 'asset',
|
||||
'assist', 'assume', 'asthma', 'athlete', 'atom', 'attack', 'attend', 'attitude', 'attract', 'auction',
|
||||
'audit', 'august', 'aunt', 'author', 'auto', 'autumn', 'average', 'avocado', 'avoid', 'awake',
|
||||
'aware', 'away', 'awesome', 'awful', 'awkward', 'axis', 'baby', 'bachelor', 'bacon', 'badge',
|
||||
'bag', 'balance', 'balcony', 'ball', 'bamboo', 'banana', 'banner', 'bar', 'barely', 'bargain',
|
||||
'barrel', 'base', 'basic', 'basket', 'battle', 'beach', 'bean', 'beauty', 'because', 'become',
|
||||
'beef', 'before', 'begin', 'behave', 'behind', 'believe', 'below', 'belt', 'bench', 'benefit',
|
||||
'best', 'betray', 'better', 'between', 'beyond', 'bicycle', 'bid', 'bike', 'bind', 'biology',
|
||||
'bird', 'birth', 'bitter', 'black', 'blade', 'blame', 'blanket', 'blast', 'bleak', 'bless',
|
||||
'blind', 'blood', 'blossom', 'blouse', 'blue', 'blur', 'blush', 'board', 'boat', 'body',
|
||||
'boil', 'bomb', 'bone', 'bonus', 'book', 'boost', 'border', 'boring', 'borrow', 'boss',
|
||||
'bottom', 'bounce', 'box', 'boy', 'bracket', 'brain', 'brand', 'brass', 'brave', 'bread',
|
||||
'breeze', 'brick', 'bridge', 'brief', 'bright', 'bring', 'brisk', 'broccoli', 'broken', 'bronze',
|
||||
'broom', 'brother', 'brown', 'brush', 'bubble', 'buddy', 'budget', 'buffalo', 'build', 'bulb',
|
||||
'bulk', 'bullet', 'bundle', 'bunker', 'burden', 'burger', 'burst', 'bus', 'business', 'butter'
|
||||
];
|
||||
|
||||
/// Vérifie si l'utilisateur a accepté l'envoi de données à l'IA
|
||||
Future<bool> isUploadEnabled() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getBool(_uploadEnabledKey) ?? false;
|
||||
}
|
||||
|
||||
/// Active ou désactive l'envoi de données
|
||||
Future<void> setUploadEnabled(bool enabled) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setBool(_uploadEnabledKey, enabled);
|
||||
}
|
||||
|
||||
/// Gets the unique 15-word identity phrase
|
||||
Future<String> getIdentityPhrase() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
|
||||
// Check if we already generated it
|
||||
final existingPhrase = prefs.getString(_prefsKey);
|
||||
if (existingPhrase != null && existingPhrase.isNotEmpty) {
|
||||
return existingPhrase;
|
||||
}
|
||||
|
||||
// Generate new phrase based on device ID
|
||||
final phrase = await _generatePhraseFromDevice();
|
||||
|
||||
// Save for future use
|
||||
await prefs.setString(_prefsKey, phrase);
|
||||
|
||||
return phrase;
|
||||
}
|
||||
|
||||
Future<String> _generatePhraseFromDevice() async {
|
||||
final deviceInfo = DeviceInfoPlugin();
|
||||
String deviceId = 'unknown_device_${DateTime.now().millisecondsSinceEpoch}';
|
||||
|
||||
try {
|
||||
if (Platform.isAndroid) {
|
||||
final androidInfo = await deviceInfo.androidInfo;
|
||||
deviceId = androidInfo.id; // Unique Android ID
|
||||
} else if (Platform.isIOS) {
|
||||
final iosInfo = await deviceInfo.iosInfo;
|
||||
deviceId = iosInfo.identifierForVendor ?? deviceId;
|
||||
} else if (Platform.isWindows) {
|
||||
final windowsInfo = await deviceInfo.windowsInfo;
|
||||
deviceId = windowsInfo.deviceId;
|
||||
}
|
||||
} catch (e) {
|
||||
print('Erreur lecture device ID: $e');
|
||||
}
|
||||
|
||||
// Add a salt to the device ID
|
||||
final salt = 'bully_app_wallet_salt_v1';
|
||||
final bytes = utf8.encode(deviceId + salt);
|
||||
final digest = sha256.convert(bytes);
|
||||
|
||||
// Use the hash to seed a random number generator
|
||||
// We take the first 4 bytes of the hash as the seed
|
||||
final seedBytes = digest.bytes.sublist(0, 4);
|
||||
final seed = (seedBytes[0] << 24) | (seedBytes[1] << 16) | (seedBytes[2] << 8) | seedBytes[3];
|
||||
|
||||
final random = Random(seed);
|
||||
|
||||
List<String> phraseWords = [];
|
||||
for (int i = 0; i < 15; i++) {
|
||||
final randomIndex = random.nextInt(_wordList.length);
|
||||
phraseWords.add(_wordList[randomIndex]);
|
||||
}
|
||||
|
||||
return phraseWords.join(' ');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user