update
This commit is contained in:
@@ -1,10 +1,16 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
import 'dart:io' as io;
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter_giphy_picker/giphy_ui.dart';
|
import 'package:flutter_giphy_picker/giphy_ui.dart';
|
||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
import 'package:shared_preferences/shared_preferences.dart';
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:file_picker/file_picker.dart';
|
||||||
|
import 'dart:io';
|
||||||
|
import 'package:url_launcher/url_launcher.dart';
|
||||||
|
import 'package:intl/intl.dart';
|
||||||
|
|
||||||
class ChatScreen extends StatefulWidget {
|
class ChatScreen extends StatefulWidget {
|
||||||
final String usernameExpediteur;
|
final String usernameExpediteur;
|
||||||
@@ -27,6 +33,7 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
bool _isButtonEnabled = false;
|
bool _isButtonEnabled = false;
|
||||||
late Timer _pollingTimer;
|
late Timer _pollingTimer;
|
||||||
bool _isInitialLoading = true;
|
bool _isInitialLoading = true;
|
||||||
|
bool _showScrollToBottom = false;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
@@ -35,6 +42,19 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
_loadExpediteur();
|
_loadExpediteur();
|
||||||
_controller.addListener(_updateButtonState);
|
_controller.addListener(_updateButtonState);
|
||||||
_startPolling();
|
_startPolling();
|
||||||
|
_scrollController.addListener(() {
|
||||||
|
final maxScroll = _scrollController.position.maxScrollExtent;
|
||||||
|
final currentScroll = _scrollController.offset;
|
||||||
|
final threshold = 100.0;
|
||||||
|
|
||||||
|
final shouldShow = (maxScroll - currentScroll) > threshold;
|
||||||
|
|
||||||
|
if (shouldShow != _showScrollToBottom) {
|
||||||
|
setState(() {
|
||||||
|
_showScrollToBottom = shouldShow;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
void _startPolling() {
|
void _startPolling() {
|
||||||
@@ -155,18 +175,26 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
|
|
||||||
Future<String> _dechiffrerMessage(String encryptedMessage, String key) async {
|
Future<String> _dechiffrerMessage(String encryptedMessage, String key) async {
|
||||||
final uri =
|
final uri =
|
||||||
Uri.parse('https://nexuschat.derickexm.be/messages/uncrypt_message/');
|
Uri.parse('https://nexuschat.derickexm.be/messages/uncrypt_messages/');
|
||||||
final response = await http.post(
|
final response = await http.post(
|
||||||
uri,
|
uri,
|
||||||
headers: {'Content-Type': 'application/json'},
|
headers: {'Content-Type': 'application/json'},
|
||||||
body: jsonEncode({
|
body: jsonEncode({
|
||||||
'encrypted_message': encryptedMessage,
|
"messages": [
|
||||||
'key': key,
|
{"encrypted_message": encryptedMessage, "key": key}
|
||||||
|
]
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
if (response.statusCode == 200) {
|
if (response.statusCode == 200) {
|
||||||
final data = jsonDecode(response.body);
|
final data = jsonDecode(response.body);
|
||||||
return data['decrypted_message'] ?? encryptedMessage;
|
if (data['results'] != null &&
|
||||||
|
data['results'] is List &&
|
||||||
|
data['results'].isNotEmpty) {
|
||||||
|
final first = data['results'][0];
|
||||||
|
return first['decrypted_message'] ?? encryptedMessage;
|
||||||
|
} else {
|
||||||
|
return encryptedMessage;
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
print("Erreur déchiffrement: ${response.body}");
|
print("Erreur déchiffrement: ${response.body}");
|
||||||
return encryptedMessage;
|
return encryptedMessage;
|
||||||
@@ -184,24 +212,51 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
final jsonResponse = jsonDecode(response.body);
|
final jsonResponse = jsonDecode(response.body);
|
||||||
if (jsonResponse.containsKey('messages')) {
|
if (jsonResponse.containsKey('messages')) {
|
||||||
final List<dynamic> messagesList = jsonResponse['messages'];
|
final List<dynamic> messagesList = jsonResponse['messages'];
|
||||||
final decryptedMessages =
|
|
||||||
await Future.wait(messagesList.map((msg) async {
|
|
||||||
final isMe = msg['expediteur'].toString() == expediteur;
|
|
||||||
|
|
||||||
final encrypted = msg['messages'].toString();
|
final batch = messagesList
|
||||||
final cle = msg['key']?.toString() ?? '';
|
.map((msg) => {
|
||||||
final texte = await _dechiffrerMessage(encrypted, cle);
|
"encrypted_message": msg['messages'].toString(),
|
||||||
return {
|
"key": msg['key']?.toString() ?? ''
|
||||||
|
})
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
final decryptUri = Uri.parse(
|
||||||
|
'https://nexuschat.derickexm.be/messages/uncrypt_messages/');
|
||||||
|
final decryptResponse = await http.post(
|
||||||
|
decryptUri,
|
||||||
|
headers: {'Content-Type': 'application/json'},
|
||||||
|
body: jsonEncode({"messages": batch}),
|
||||||
|
);
|
||||||
|
|
||||||
|
List<String> textesDecryptes = [];
|
||||||
|
|
||||||
|
if (decryptResponse.statusCode == 200) {
|
||||||
|
final decryptedData = jsonDecode(decryptResponse.body);
|
||||||
|
if (decryptedData['results'] is List) {
|
||||||
|
textesDecryptes = List<String>.from(decryptedData['results']
|
||||||
|
.map((item) => item['decrypted_message'] ?? ''));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final List<Map<String, dynamic>> finalMessages = [];
|
||||||
|
for (int i = 0; i < messagesList.length; i++) {
|
||||||
|
final msg = messagesList[i];
|
||||||
|
final text = i < textesDecryptes.length
|
||||||
|
? textesDecryptes[i]
|
||||||
|
: msg['messages'].toString();
|
||||||
|
finalMessages.add({
|
||||||
'sender': msg['expediteur'].toString(),
|
'sender': msg['expediteur'].toString(),
|
||||||
'text': texte,
|
'text': text,
|
||||||
'encrypted': msg['messages'].toString(),
|
'encrypted': msg['messages'].toString(),
|
||||||
'timestamp': msg['sent_at'].toString(),
|
'sent_at': msg['sent_at'].toString(),
|
||||||
'key': msg['key']?.toString() ?? '',
|
'key': msg['key']?.toString() ?? '',
|
||||||
'type': msg['type'] ?? 'text'
|
'type': msg['type'] ?? 'text',
|
||||||
};
|
});
|
||||||
}));
|
print(msg['sent_at'].toString());
|
||||||
|
}
|
||||||
|
|
||||||
setState(() {
|
setState(() {
|
||||||
messages = decryptedMessages;
|
messages = finalMessages;
|
||||||
_isInitialLoading = false;
|
_isInitialLoading = false;
|
||||||
});
|
});
|
||||||
_scrollToBottom();
|
_scrollToBottom();
|
||||||
@@ -227,13 +282,38 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
if (response.statusCode == 200) {
|
if (response.statusCode == 200) {
|
||||||
print("✅ Message supprimé");
|
print(" Message supprimé");
|
||||||
_fetchMessages(); // refresh
|
_fetchMessages(); // refresh
|
||||||
} else {
|
} else {
|
||||||
print("❌ Erreur suppression: ${response.body}");
|
print("Erreur suppression: ${response.body}");
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
print("❌ Erreur _supprimerMessage: $e");
|
print(" Erreur _supprimerMessage: $e");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _sendnotification(String messageText) async {
|
||||||
|
if (destinataire.isEmpty) return;
|
||||||
|
|
||||||
|
final url =
|
||||||
|
Uri.parse("https://nexuschat.derickexm.be/users/send_notifications");
|
||||||
|
final body = jsonEncode({
|
||||||
|
'destinataire': destinataire,
|
||||||
|
'type': 'text',
|
||||||
|
'contenu': messageText,
|
||||||
|
'owner': expediteur
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
final response = await http.post(url,
|
||||||
|
headers: {'Content-Type': 'application/json'}, body: body);
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
print("✅ Notification envoyée.");
|
||||||
|
} else {
|
||||||
|
print("❌ Erreur envoi notification: ${response.body}");
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
print("❌ Exception envoi notification: $e");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -273,26 +353,31 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
print("🔍 expediteur: $expediteur");
|
print("🔍 expediteur: $expediteur");
|
||||||
if (expediteur == null || message.trim().isEmpty) return;
|
if (expediteur == null || message.trim().isEmpty) return;
|
||||||
|
|
||||||
final now = DateTime.now();
|
|
||||||
|
|
||||||
final cryptoData = await _chiffrerMessage(message.trim());
|
final cryptoData = await _chiffrerMessage(message.trim());
|
||||||
print("Résultat chiffrement : $cryptoData");
|
|
||||||
final encryptedMessage = cryptoData['encrypted_message'] ?? '';
|
final encryptedMessage = cryptoData['encrypted_message'] ?? '';
|
||||||
final key = cryptoData['key'] ?? '';
|
final key = cryptoData['key'] ?? '';
|
||||||
// Ajout du texte en clair
|
|
||||||
final plainText = _controller.text.trim();
|
final plainText = _controller.text.trim();
|
||||||
if (key == null || key.isEmpty) {
|
|
||||||
|
// --- MODIFIED LINE FOR TIMESTAMP ---
|
||||||
|
// Get current local time, then convert to UTC, then add 2 hours (for CEST / UTC+2)
|
||||||
|
// This ensures the time sent is what CEST time would be for this moment.
|
||||||
|
final nowCestTime = DateTime.now().toUtc().add(Duration(hours: 2));
|
||||||
|
final nowCestIsoFormatted =
|
||||||
|
DateFormat("yyyy-MM-dd HH:mm:ss").format(nowCestTime);
|
||||||
|
|
||||||
|
if (key.isEmpty) {
|
||||||
print('❌ Clé de chiffrement manquante. Message non envoyé.');
|
print('❌ Clé de chiffrement manquante. Message non envoyé.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Affichage local temporaire (sera remplacé par le polling)
|
||||||
setState(() {
|
setState(() {
|
||||||
messages = List<Map<String, dynamic>>.from(messages)
|
messages = List<Map<String, dynamic>>.from(messages)
|
||||||
..add({
|
..add({
|
||||||
'sender': expediteur ?? '',
|
'sender': expediteur ?? '',
|
||||||
'text': plainText,
|
'text': plainText,
|
||||||
'encrypted': encryptedMessage,
|
'encrypted': encryptedMessage,
|
||||||
'timestamp': now.toIso8601String(),
|
'timestamp': 'En cours...', // Temporaire, will be updated by polling
|
||||||
'key': key,
|
'key': key,
|
||||||
'type': 'text'
|
'type': 'text'
|
||||||
});
|
});
|
||||||
@@ -303,6 +388,8 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
|
|
||||||
print("✉️ Envoi du message chiffré : $encryptedMessage");
|
print("✉️ Envoi du message chiffré : $encryptedMessage");
|
||||||
print("🔑 Clé : $key");
|
print("🔑 Clé : $key");
|
||||||
|
print(
|
||||||
|
"⏰ Timestamp envoyé à l'API (CEST): $nowCestIsoFormatted"); // Add this debug print
|
||||||
|
|
||||||
try {
|
try {
|
||||||
final response = await http.post(
|
final response = await http.post(
|
||||||
@@ -312,74 +399,162 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
'expediteur': expediteur,
|
'expediteur': expediteur,
|
||||||
'destinataire': destinataire,
|
'destinataire': destinataire,
|
||||||
'message': encryptedMessage,
|
'message': encryptedMessage,
|
||||||
// Correction : horodatage en heure locale (Belgique)
|
|
||||||
'timestamp': DateTime.now().toIso8601String(),
|
|
||||||
'id_conversation': idConversation,
|
'id_conversation': idConversation,
|
||||||
// Correction : forcer 'key' non vide
|
'key': key,
|
||||||
'key': key.isNotEmpty ? key : 'test'
|
'type': 'text',
|
||||||
|
'timestamp':
|
||||||
|
nowCestIsoFormatted, // --- USE THE CEST FORMATTED STRING ---
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
print("📡 Status Code: ${response.statusCode}");
|
||||||
|
print("📡 Response: ${response.body}");
|
||||||
|
|
||||||
if (response.statusCode == 200) {
|
if (response.statusCode == 200) {
|
||||||
|
print("✅ Message envoyé avec succès");
|
||||||
|
|
||||||
|
await Future.delayed(Duration(milliseconds: 500));
|
||||||
|
await _fetchMessages();
|
||||||
|
|
||||||
final jsonResponse = jsonDecode(response.body);
|
final jsonResponse = jsonDecode(response.body);
|
||||||
if (jsonResponse.containsKey('reply')) {
|
if (jsonResponse.containsKey('reply')) {
|
||||||
setState(() {
|
setState(() {
|
||||||
messages.add({
|
messages.add({
|
||||||
'sender': destinataire,
|
'sender': destinataire,
|
||||||
'text': jsonResponse['reply'],
|
'text': jsonResponse['reply'],
|
||||||
'timestamp': DateTime.now().toIso8601String(),
|
'timestamp': 'À l\'instant',
|
||||||
|
'type': 'text'
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
_scrollToBottom();
|
_scrollToBottom();
|
||||||
}
|
}
|
||||||
|
await _sendnotification(message.trim());
|
||||||
|
} else {
|
||||||
|
print('❌ Erreur HTTP ${response.statusCode}: ${response.body}');
|
||||||
|
setState(() {
|
||||||
|
messages.removeLast();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
print('Erreur sendMessage: $e');
|
print('❌ Erreur exception sendMessage: $e');
|
||||||
|
setState(() {
|
||||||
|
messages.removeLast();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 🎭 Fonction _sendGif simplifiée
|
||||||
Future<void> _sendGif(String gifUrl) async {
|
Future<void> _sendGif(String gifUrl) async {
|
||||||
if (expediteur == null || gifUrl.isEmpty) return;
|
if (expediteur == null || gifUrl.isEmpty) return;
|
||||||
print('📤 Préparation à l’envoi du GIF :');
|
|
||||||
print(' ↪️ URL : $gifUrl');
|
|
||||||
|
|
||||||
final nowUtcIso = DateTime.now().toIso8601String();
|
print('📤 Préparation à l\'envoi du GIF : $gifUrl');
|
||||||
// Désactivation du chiffrement pour les GIFs
|
final nowCestTime = DateTime.now().toUtc().add(Duration(hours: 2));
|
||||||
final encryptedMessage = gifUrl;
|
final nowCestIsoFormatted =
|
||||||
final key = 'test';
|
DateFormat("yyyy-MM-dd HH:mm:ss").format(nowCestTime);
|
||||||
print(' 🔐 Encrypted : $encryptedMessage');
|
|
||||||
print(' 🔑 Key : $key');
|
final cryptoData = await _chiffrerMessage(gifUrl);
|
||||||
print(' 💬 ID conversation : $idConversation');
|
final encryptedMessage = cryptoData['encrypted_message'] ?? gifUrl;
|
||||||
|
final key = cryptoData['key'] ?? 'test';
|
||||||
|
|
||||||
|
// Affichage local temporaire
|
||||||
setState(() {
|
setState(() {
|
||||||
messages = List<Map<String, dynamic>>.from(messages)
|
messages = List<Map<String, dynamic>>.from(messages)
|
||||||
..add({
|
..add({
|
||||||
'sender': expediteur ?? '',
|
'sender': expediteur ?? '',
|
||||||
'text': gifUrl,
|
'text': gifUrl,
|
||||||
'encrypted': encryptedMessage,
|
'encrypted': encryptedMessage,
|
||||||
'timestamp': nowUtcIso,
|
'sent_at': 'En cours...',
|
||||||
'key': key,
|
'key': key,
|
||||||
'type': 'gif'
|
'type': 'gif'
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
_scrollToBottom();
|
_scrollToBottom();
|
||||||
|
|
||||||
|
try {
|
||||||
|
final response = await http.post(
|
||||||
|
Uri.parse('https://nexuschat.derickexm.be/messages/send_message/'),
|
||||||
|
headers: {'Content-Type': 'application/json'},
|
||||||
|
body: jsonEncode({
|
||||||
|
'expediteur': expediteur,
|
||||||
|
'destinataire': destinataire,
|
||||||
|
'message': encryptedMessage,
|
||||||
|
'id_conversation': idConversation,
|
||||||
|
'key': key,
|
||||||
|
'type': 'gif',
|
||||||
|
'timestamp': nowCestIsoFormatted, // --- INCLUDE THIS IN THE BODY ---
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
print("📡 GIF Status: ${response.statusCode}");
|
||||||
|
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
print('✅ GIF envoyé avec succès.');
|
||||||
|
// Refresh pour récupérer le vrai timestamp
|
||||||
|
await Future.delayed(Duration(milliseconds: 500));
|
||||||
|
await _fetchMessages();
|
||||||
|
} else {
|
||||||
|
print('❌ Erreur envoi GIF : ${response.body}');
|
||||||
|
setState(() {
|
||||||
|
messages.removeLast();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
print('❌ Erreur réseau envoi GIF : $e');
|
||||||
|
setState(() {
|
||||||
|
messages.removeLast();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _scrollToBottom({bool force = false}) {
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
|
if (_scrollController.hasClients) {
|
||||||
|
final maxScroll = _scrollController.position.maxScrollExtent;
|
||||||
|
final currentScroll = _scrollController.offset;
|
||||||
|
final threshold = 100.0;
|
||||||
|
|
||||||
|
if (force || (maxScroll - currentScroll) < threshold) {
|
||||||
|
_scrollController.animateTo(
|
||||||
|
maxScroll,
|
||||||
|
duration: Duration(milliseconds: 300),
|
||||||
|
curve: Curves.easeOut,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _sendFile(String fileUrl) async {
|
||||||
|
if (expediteur == null || fileUrl.isEmpty) return;
|
||||||
|
|
||||||
|
final nowUtcIso = DateTime.now().toIso8601String();
|
||||||
|
final cryptoData = await _chiffrerMessage(fileUrl);
|
||||||
|
final encryptedMessage = cryptoData['encrypted_message'] ?? fileUrl;
|
||||||
|
final key = cryptoData['key'] ?? 'test';
|
||||||
|
|
||||||
|
setState(() {
|
||||||
|
messages = List<Map<String, dynamic>>.from(messages)
|
||||||
|
..add({
|
||||||
|
'sender': expediteur ?? '',
|
||||||
|
'text': fileUrl,
|
||||||
|
'encrypted': encryptedMessage,
|
||||||
|
'timestamp': nowUtcIso,
|
||||||
|
'key': key,
|
||||||
|
'type': 'file'
|
||||||
|
});
|
||||||
|
});
|
||||||
|
_scrollToBottom();
|
||||||
|
|
||||||
final body = jsonEncode({
|
final body = jsonEncode({
|
||||||
'expediteur': expediteur,
|
'expediteur': expediteur,
|
||||||
'destinataire': destinataire,
|
'destinataire': destinataire,
|
||||||
'message': encryptedMessage,
|
'message': encryptedMessage,
|
||||||
'timestamp': nowUtcIso,
|
// 'timestamp': nowUtcIso, // removed
|
||||||
'id_conversation': idConversation,
|
'id_conversation': idConversation,
|
||||||
'key': key,
|
'key': key,
|
||||||
'type': 'gif'
|
'type': 'file'
|
||||||
});
|
});
|
||||||
print("📦 Corps envoyé à l’API :");
|
|
||||||
print(" expediteur : ${expediteur}");
|
|
||||||
print(" destinataire : ${destinataire}");
|
|
||||||
print(" message : $encryptedMessage");
|
|
||||||
print(" key : $key");
|
|
||||||
print(" timestamp : $nowUtcIso");
|
|
||||||
print(" id_conversation: $idConversation");
|
|
||||||
print(" type : gif");
|
|
||||||
print("🔒 Longueur message : ${encryptedMessage.length}");
|
|
||||||
try {
|
try {
|
||||||
final response = await http.post(
|
final response = await http.post(
|
||||||
Uri.parse('https://nexuschat.derickexm.be/messages/send_message/'),
|
Uri.parse('https://nexuschat.derickexm.be/messages/send_message/'),
|
||||||
@@ -388,30 +563,16 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
);
|
);
|
||||||
|
|
||||||
if (response.statusCode != 200) {
|
if (response.statusCode != 200) {
|
||||||
print('Erreur envoi GIF : ${response.body}');
|
print('Erreur envoi fichier : ${response.body}');
|
||||||
} else {
|
} else {
|
||||||
print('✅ GIF envoyé avec succès.');
|
print('✅ Fichier envoyé avec succès.');
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
print('Erreur réseau envoi GIF : $e');
|
print('Erreur réseau envoi fichier : $e');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void _scrollToBottom() {
|
///
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
|
||||||
if (_scrollController.hasClients) {
|
|
||||||
_scrollController.animateTo(
|
|
||||||
_scrollController.position.maxScrollExtent,
|
|
||||||
duration: Duration(milliseconds: 300),
|
|
||||||
curve: Curves.easeOut,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
void _selectPhoto() {
|
|
||||||
print('Sélectionner une photo');
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _selectGif() async {
|
Future<void> _selectGif() async {
|
||||||
GiphyLocale? fr;
|
GiphyLocale? fr;
|
||||||
@@ -441,7 +602,9 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
),
|
),
|
||||||
title: Text(destinataire),
|
title: Text(destinataire),
|
||||||
),
|
),
|
||||||
body: _isInitialLoading
|
body: Stack(
|
||||||
|
children: [
|
||||||
|
_isInitialLoading
|
||||||
? const Center(child: CircularProgressIndicator())
|
? const Center(child: CircularProgressIndicator())
|
||||||
: Column(
|
: Column(
|
||||||
children: [
|
children: [
|
||||||
@@ -452,17 +615,10 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
itemBuilder: (context, index) {
|
itemBuilder: (context, index) {
|
||||||
final message = messages[index];
|
final message = messages[index];
|
||||||
final isMe = message['sender'] == expediteur;
|
final isMe = message['sender'] == expediteur;
|
||||||
|
|
||||||
// Formatage de l'heure
|
|
||||||
final time =
|
|
||||||
DateTime.tryParse(message['timestamp'] ?? '');
|
|
||||||
final formattedTime = time != null
|
|
||||||
? "${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}"
|
|
||||||
: '';
|
|
||||||
|
|
||||||
return Container(
|
return Container(
|
||||||
alignment:
|
alignment: isMe
|
||||||
isMe ? Alignment.centerRight : Alignment.centerLeft,
|
? Alignment.centerRight
|
||||||
|
: Alignment.centerLeft,
|
||||||
margin: const EdgeInsets.symmetric(
|
margin: const EdgeInsets.symmetric(
|
||||||
vertical: 4, horizontal: 8),
|
vertical: 4, horizontal: 8),
|
||||||
child: Column(
|
child: Column(
|
||||||
@@ -487,21 +643,26 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
? () {
|
? () {
|
||||||
showDialog(
|
showDialog(
|
||||||
context: context,
|
context: context,
|
||||||
builder: (BuildContext context) {
|
builder:
|
||||||
|
(BuildContext context) {
|
||||||
return AlertDialog(
|
return AlertDialog(
|
||||||
title: Text(
|
title: Text(
|
||||||
"Supprimer le message ?"),
|
"Supprimer le message ?"),
|
||||||
actions: [
|
actions: [
|
||||||
TextButton(
|
TextButton(
|
||||||
child: Text("Annuler"),
|
child:
|
||||||
|
Text("Annuler"),
|
||||||
onPressed: () =>
|
onPressed: () =>
|
||||||
Navigator.of(context)
|
Navigator.of(
|
||||||
|
context)
|
||||||
.pop(),
|
.pop(),
|
||||||
),
|
),
|
||||||
TextButton(
|
TextButton(
|
||||||
child: Text("Supprimer"),
|
child:
|
||||||
|
Text("Supprimer"),
|
||||||
onPressed: () {
|
onPressed: () {
|
||||||
Navigator.of(context)
|
Navigator.of(
|
||||||
|
context)
|
||||||
.pop();
|
.pop();
|
||||||
_supprimerMessage(
|
_supprimerMessage(
|
||||||
message);
|
message);
|
||||||
@@ -520,12 +681,40 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
color: isMe
|
color: isMe
|
||||||
? Colors.orange
|
? Colors.orange
|
||||||
: Colors.grey[300],
|
: Colors.grey[300],
|
||||||
borderRadius: BorderRadius.circular(10),
|
borderRadius:
|
||||||
|
BorderRadius.circular(10),
|
||||||
),
|
),
|
||||||
child: message['type'] == 'gif'
|
child: message['type'] == 'gif'
|
||||||
? Image.network(message['text'] ?? '')
|
? Image.network(
|
||||||
: Text(
|
|
||||||
message['text'] ?? '',
|
message['text'] ?? '',
|
||||||
|
errorBuilder: (context, error,
|
||||||
|
stackTrace) {
|
||||||
|
return Text(
|
||||||
|
"Erreur de chargement du GIF");
|
||||||
|
})
|
||||||
|
: message['text']
|
||||||
|
.toString()
|
||||||
|
.startsWith('http')
|
||||||
|
? GestureDetector(
|
||||||
|
onTap: () => launchUrl(
|
||||||
|
Uri.parse(
|
||||||
|
message['text'])),
|
||||||
|
child: Text(
|
||||||
|
'📎 Fichier joint',
|
||||||
|
style: TextStyle(
|
||||||
|
decoration:
|
||||||
|
TextDecoration
|
||||||
|
.underline,
|
||||||
|
color:
|
||||||
|
Colors.blueAccent,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
: Text(
|
||||||
|
message['owner'] != null
|
||||||
|
? "Message de ${message['owner']}"
|
||||||
|
: (message['text'] ??
|
||||||
|
''),
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
color: isMe
|
color: isMe
|
||||||
? Colors.white
|
? Colors.white
|
||||||
@@ -537,13 +726,29 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
if (formattedTime.isNotEmpty)
|
|
||||||
Padding(
|
Padding(
|
||||||
padding: const EdgeInsets.only(top: 2),
|
padding: const EdgeInsets.only(top: 2),
|
||||||
child: Text(
|
child: Builder(
|
||||||
formattedTime,
|
builder: (context) {
|
||||||
|
final rawDateStr = message['sent_at'] ??
|
||||||
|
message['timestamp'];
|
||||||
|
DateTime? parsedDate;
|
||||||
|
try {
|
||||||
|
parsedDate =
|
||||||
|
DateTime.tryParse(rawDateStr ?? '');
|
||||||
|
} catch (_) {}
|
||||||
|
final display = parsedDate != null
|
||||||
|
? DateFormat("d MMMM yyyy à HH:mm",
|
||||||
|
"fr_FR")
|
||||||
|
.format(parsedDate)
|
||||||
|
: '';
|
||||||
|
return Text(
|
||||||
|
display,
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
fontSize: 10, color: Colors.grey[600]),
|
fontSize: 10,
|
||||||
|
color: Colors.grey[600]),
|
||||||
|
);
|
||||||
|
},
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
@@ -578,20 +783,21 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
inputFormatters: [
|
inputFormatters: [
|
||||||
_EnterKeyFormatter(
|
_EnterKeyFormatter(
|
||||||
onEnter: () {
|
onEnter: () {
|
||||||
if (_controller.text.trim().isNotEmpty) {
|
if (_controller.text
|
||||||
|
.trim()
|
||||||
|
.isNotEmpty) {
|
||||||
sendMessage(_controller.text);
|
sendMessage(_controller.text);
|
||||||
_controller
|
_controller.clear();
|
||||||
.clear(); // 👈 Ajout explicite du clear ici
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
SizedBox(width: 8),
|
SizedBox(width: 5),
|
||||||
Container(
|
Container(
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
color: Colors.orange.shade100, // plus doux
|
color: Colors.orange.shade100,
|
||||||
borderRadius: BorderRadius.circular(12),
|
borderRadius: BorderRadius.circular(12),
|
||||||
),
|
),
|
||||||
child: IconButton(
|
child: IconButton(
|
||||||
@@ -618,14 +824,14 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
: null,
|
: null,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
SizedBox(width: 8),
|
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
Padding(
|
Padding(
|
||||||
padding: const EdgeInsets.only(bottom: 4, top: 2),
|
padding: const EdgeInsets.only(bottom: 4, top: 2),
|
||||||
child: Text(
|
child: Text(
|
||||||
"🔒 Messages chiffrés de bout en bout",
|
"🔒 Messages chiffrés de bout en bout",
|
||||||
style: TextStyle(fontSize: 12, color: Colors.grey),
|
style:
|
||||||
|
TextStyle(fontSize: 12, color: Colors.grey),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
@@ -633,6 +839,19 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
if (_showScrollToBottom)
|
||||||
|
Positioned(
|
||||||
|
bottom: 100,
|
||||||
|
right: 16,
|
||||||
|
child: FloatingActionButton(
|
||||||
|
mini: true,
|
||||||
|
backgroundColor: Colors.orange,
|
||||||
|
child: Icon(Icons.arrow_downward),
|
||||||
|
onPressed: () => _scrollToBottom(force: true),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -106,9 +106,11 @@ class _ContactsState extends State<Contacts>
|
|||||||
);
|
);
|
||||||
if (response.statusCode == 200) {
|
if (response.statusCode == 200) {
|
||||||
final data = json.decode(response.body);
|
final data = json.decode(response.body);
|
||||||
|
final users = data['users'];
|
||||||
|
users.shuffle();
|
||||||
setState(() {
|
setState(() {
|
||||||
_users = data['users'];
|
_users = users;
|
||||||
_filteredUsers = _users;
|
_filteredUsers = users.length > 3 ? users.take(3).toList() : users;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -119,9 +121,13 @@ class _ContactsState extends State<Contacts>
|
|||||||
void _filterUsers() {
|
void _filterUsers() {
|
||||||
final query = _searchController.text.toLowerCase();
|
final query = _searchController.text.toLowerCase();
|
||||||
setState(() {
|
setState(() {
|
||||||
|
if (query.isEmpty) {
|
||||||
|
_filteredUsers = [];
|
||||||
|
} else {
|
||||||
_filteredUsers = _users
|
_filteredUsers = _users
|
||||||
.where((user) => user['username'].toLowerCase().contains(query))
|
.where((user) => user['username'].toLowerCase().contains(query))
|
||||||
.toList();
|
.toList();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,6 +140,32 @@ class _ContactsState extends State<Contacts>
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> _sendnotification(
|
||||||
|
String destinataire, String messageText) async {
|
||||||
|
if (destinataire.isEmpty || currentUser == null) return;
|
||||||
|
|
||||||
|
final url =
|
||||||
|
Uri.parse("https://nexuschat.derickexm.be/users/send_notifications");
|
||||||
|
final body = jsonEncode({
|
||||||
|
'destinataire': destinataire,
|
||||||
|
'type': 'text',
|
||||||
|
'contenu': messageText,
|
||||||
|
'owner': currentUser
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
final response = await http.post(url,
|
||||||
|
headers: {'Content-Type': 'application/json'}, body: body);
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
print("✅ Notification envoyée.");
|
||||||
|
} else {
|
||||||
|
print("❌ Erreur envoi notification: ${response.body}");
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
print("❌ Exception envoi notification: $e");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> _envoyerDemandeContact(String destinataire) async {
|
Future<void> _envoyerDemandeContact(String destinataire) async {
|
||||||
if (destinataire == currentUser) {
|
if (destinataire == currentUser) {
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
@@ -173,6 +205,8 @@ class _ContactsState extends State<Contacts>
|
|||||||
ScaffoldMessenger.of(context).showSnackBar(
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
SnackBar(content: Text("Demande envoyée à $destinataire")),
|
SnackBar(content: Text("Demande envoyée à $destinataire")),
|
||||||
);
|
);
|
||||||
|
await _sendnotification(
|
||||||
|
destinataire, "$currentUser vous a envoyé une demande de contact.");
|
||||||
await _loadDemandes();
|
await _loadDemandes();
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -380,7 +414,21 @@ class _ContactsState extends State<Contacts>
|
|||||||
Expanded(
|
Expanded(
|
||||||
child: _filteredUsers.isEmpty
|
child: _filteredUsers.isEmpty
|
||||||
? Center(child: Text("Aucun utilisateur trouvé"))
|
? Center(child: Text("Aucun utilisateur trouvé"))
|
||||||
: ListView.builder(
|
: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
if (_searchController.text.isEmpty)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(
|
||||||
|
horizontal: 16.0, vertical: 8.0),
|
||||||
|
child: Text(
|
||||||
|
"Personnes que tu pourrais connaître",
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 16, fontWeight: FontWeight.bold),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Expanded(
|
||||||
|
child: ListView.builder(
|
||||||
itemCount: _filteredUsers.length,
|
itemCount: _filteredUsers.length,
|
||||||
itemBuilder: (context, index) {
|
itemBuilder: (context, index) {
|
||||||
final user = _filteredUsers[index]['username'];
|
final user = _filteredUsers[index]['username'];
|
||||||
@@ -403,7 +451,8 @@ class _ContactsState extends State<Contacts>
|
|||||||
|
|
||||||
if (etat == "aucune_relation") {
|
if (etat == "aucune_relation") {
|
||||||
label = "Envoyer demande";
|
label = "Envoyer demande";
|
||||||
action = () => _envoyerDemandeContact(user);
|
action =
|
||||||
|
() => _envoyerDemandeContact(user);
|
||||||
} else if (etat == "pending_envoyee" ||
|
} else if (etat == "pending_envoyee" ||
|
||||||
etat == "pending_recue") {
|
etat == "pending_recue") {
|
||||||
label = "Demande en attente";
|
label = "Demande en attente";
|
||||||
@@ -432,6 +481,9 @@ class _ContactsState extends State<Contacts>
|
|||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|||||||
108
nexuschat/lib/forgotpassword.dart
Normal file
108
nexuschat/lib/forgotpassword.dart
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
// ignore_for_file: use_super_parameters
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
|
||||||
|
class ForgotPasswordScreen extends StatefulWidget {
|
||||||
|
const ForgotPasswordScreen({Key? key}) : super(key: key);
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<ForgotPasswordScreen> createState() => _ForgotPasswordScreenState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ForgotPasswordScreenState extends State<ForgotPasswordScreen> {
|
||||||
|
final _formKey = GlobalKey<FormState>();
|
||||||
|
final _emailController = TextEditingController();
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_emailController.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _resetPassword(BuildContext context, String email) async {
|
||||||
|
final url = Uri.parse(
|
||||||
|
'https://nexuschat.derickexm.be/email/change_password?email=$email');
|
||||||
|
try {
|
||||||
|
final response = await http.post(
|
||||||
|
url,
|
||||||
|
headers: {'Accept': 'application/json'},
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
_showErrorDialog(context, "Email de vérification envoyé avec succès!");
|
||||||
|
} else {
|
||||||
|
_showErrorDialog(context,
|
||||||
|
"Impossible d'envoyer l'email de vérification. (${response.statusCode})");
|
||||||
|
print("Réponse serveur : ${response.body}");
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
_showErrorDialog(context, "Erreur de connexion à l'API.");
|
||||||
|
print("Erreur d'envoi email : $e");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _showErrorDialog(BuildContext context, String message) {
|
||||||
|
showDialog(
|
||||||
|
context: context,
|
||||||
|
builder: (BuildContext context) {
|
||||||
|
return AlertDialog(
|
||||||
|
title: const Text(''),
|
||||||
|
content: Text(message),
|
||||||
|
actions: <Widget>[
|
||||||
|
TextButton(
|
||||||
|
child: const Text('Fermer'),
|
||||||
|
onPressed: () {
|
||||||
|
Navigator.of(context).pop();
|
||||||
|
},
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Scaffold(
|
||||||
|
appBar: AppBar(
|
||||||
|
title: const Text('rénitialisation de mot de passe'),
|
||||||
|
),
|
||||||
|
body: Padding(
|
||||||
|
padding: const EdgeInsets.all(16.0),
|
||||||
|
child: Form(
|
||||||
|
key: _formKey,
|
||||||
|
child: Column(
|
||||||
|
children: [
|
||||||
|
TextFormField(
|
||||||
|
controller: _emailController,
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: 'Email',
|
||||||
|
prefixIcon: Icon(Icons.email),
|
||||||
|
),
|
||||||
|
validator: (value) {
|
||||||
|
if (value == null || value.isEmpty) {
|
||||||
|
return 'Entrer votre email';
|
||||||
|
}
|
||||||
|
if (!value.contains('@')) {
|
||||||
|
return 'Erreur : entrer un email valide';
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
},
|
||||||
|
),
|
||||||
|
const SizedBox(height: 20),
|
||||||
|
ElevatedButton(
|
||||||
|
onPressed: () {
|
||||||
|
if (_formKey.currentState!.validate()) {
|
||||||
|
_resetPassword(context, _emailController.text);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
child: const Text('Rénitialiser votre mot de passe'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:nexuschat/forgotpassword.dart';
|
||||||
import 'package:nexuschat/inscription.dart';
|
import 'package:nexuschat/inscription.dart';
|
||||||
import 'package:shared_preferences/shared_preferences.dart';
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
import 'menu.dart';
|
import 'menu.dart';
|
||||||
@@ -93,6 +94,42 @@ class Login extends StatelessWidget {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> _ForgotPassword(String email, String password) async {
|
||||||
|
final url =
|
||||||
|
Uri.parse('https://nexuschat.derickexm.be/users/check_credentials');
|
||||||
|
|
||||||
|
final body = jsonEncode({
|
||||||
|
'email': email,
|
||||||
|
'password': password,
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
final response = await http.post(
|
||||||
|
url,
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: body,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
print("Connexion réussie");
|
||||||
|
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.setString('user_email', email);
|
||||||
|
|
||||||
|
Navigator.pushReplacement(
|
||||||
|
context, MaterialPageRoute(builder: (context) => Menu()));
|
||||||
|
await sendAttemptLogin(email);
|
||||||
|
} else {
|
||||||
|
_showErrorDialog(
|
||||||
|
context, "Nom d'utilisateur ou mot de passe incorrect");
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
_showErrorDialog(context, "Impossible de se connecter à l'API");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
body: Center(
|
body: Center(
|
||||||
child: Padding(
|
child: Padding(
|
||||||
@@ -184,6 +221,19 @@ class Login extends StatelessWidget {
|
|||||||
child: const Text("S'inscrire"),
|
child: const Text("S'inscrire"),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
TextButton(
|
||||||
|
onPressed: () {
|
||||||
|
// Tu pourras plus tard rediriger vers une page dédiée
|
||||||
|
Navigator.push(
|
||||||
|
context,
|
||||||
|
MaterialPageRoute(
|
||||||
|
builder: (context) => ForgotPasswordScreen()));
|
||||||
|
},
|
||||||
|
child: const Text(
|
||||||
|
"Mot de passe oublié ?",
|
||||||
|
style: TextStyle(color: Colors.red),
|
||||||
|
),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -4,8 +4,12 @@ import 'package:flutter/material.dart';
|
|||||||
import 'package:nexuschat/menu.dart';
|
import 'package:nexuschat/menu.dart';
|
||||||
import 'package:shared_preferences/shared_preferences.dart';
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
import 'login.dart';
|
import 'login.dart';
|
||||||
|
import 'package:intl/date_symbol_data_local.dart';
|
||||||
|
|
||||||
|
void main() async {
|
||||||
|
WidgetsFlutterBinding.ensureInitialized();
|
||||||
|
await initializeDateFormatting('fr_FR', null);
|
||||||
|
|
||||||
void main() {
|
|
||||||
runApp(const MyApp());
|
runApp(const MyApp());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:nexuschat/notifications.dart';
|
||||||
import 'package:nexuschat/profil.dart';
|
import 'package:nexuschat/profil.dart';
|
||||||
import 'settings.dart';
|
import 'settings.dart';
|
||||||
import 'listechat.dart';
|
import 'listechat.dart';
|
||||||
@@ -24,6 +25,7 @@ class _MenuState extends State<Menu> {
|
|||||||
|
|
||||||
_widgetOptions = <Widget>[
|
_widgetOptions = <Widget>[
|
||||||
Listechat(),
|
Listechat(),
|
||||||
|
Notif(),
|
||||||
Setting(),
|
Setting(),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -112,6 +114,10 @@ class _MenuState extends State<Menu> {
|
|||||||
icon: Icon(Icons.chat),
|
icon: Icon(Icons.chat),
|
||||||
label: "Chat",
|
label: "Chat",
|
||||||
),
|
),
|
||||||
|
BottomNavigationBarItem(
|
||||||
|
icon: Icon(Icons.notifications),
|
||||||
|
label: "Notifications",
|
||||||
|
),
|
||||||
BottomNavigationBarItem(
|
BottomNavigationBarItem(
|
||||||
icon: Icon(Icons.settings),
|
icon: Icon(Icons.settings),
|
||||||
label: "Paramètres",
|
label: "Paramètres",
|
||||||
|
|||||||
327
nexuschat/lib/notifications.dart
Normal file
327
nexuschat/lib/notifications.dart
Normal file
@@ -0,0 +1,327 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:dio/dio.dart';
|
||||||
|
import 'dart:convert';
|
||||||
|
import 'package:intl/intl.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:nexuschat/profil.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
|
class Notif extends StatefulWidget {
|
||||||
|
const Notif({
|
||||||
|
Key? key,
|
||||||
|
}) : super(key: key);
|
||||||
|
|
||||||
|
@override
|
||||||
|
_NotifState createState() => _NotifState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _NotifState extends State<Notif> {
|
||||||
|
String? username;
|
||||||
|
String? userId;
|
||||||
|
Map<String, dynamic>? _lastNotification;
|
||||||
|
bool isUsernameReady = false;
|
||||||
|
late SharedPreferences prefs;
|
||||||
|
int? selectedNotificationId;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_initializeNotifications();
|
||||||
|
_initPrefs();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _initPrefs() async {
|
||||||
|
prefs = await SharedPreferences.getInstance();
|
||||||
|
final email = prefs.getString('user_email') ?? '';
|
||||||
|
|
||||||
|
if (email.isNotEmpty) {
|
||||||
|
await _getUsername(email);
|
||||||
|
} else {
|
||||||
|
print("❌ Aucun email trouvé dans les préférences.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _deleteNotification(String notificationId) async {
|
||||||
|
final url =
|
||||||
|
Uri.parse('https://nexuschat.derickexm.be/users/delete_notifications/');
|
||||||
|
|
||||||
|
try {
|
||||||
|
final response = await http.post(
|
||||||
|
url,
|
||||||
|
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
|
||||||
|
body: {'id': notificationId},
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
if (mounted) {
|
||||||
|
setState(() {});
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Notification supprimée')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
print('Erreur lors de la suppression: ${response.body}');
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Échec de suppression de la notification')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
print('Erreur lors de la suppression: $e');
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Erreur lors de la suppression')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<bool> deleteAllNotifications() async {
|
||||||
|
final url = Uri.parse(
|
||||||
|
'https://nexuschat.derickexm.be/users/delete_all_notifications/');
|
||||||
|
|
||||||
|
try {
|
||||||
|
var formData = FormData.fromMap({
|
||||||
|
'destinataire': username,
|
||||||
|
});
|
||||||
|
|
||||||
|
final response = await Dio().post(
|
||||||
|
url.toString(),
|
||||||
|
data: formData,
|
||||||
|
options: Options(
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/x-www-form-urlencoded',
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
final data = response.data;
|
||||||
|
print('Successfully deleted ${data['count']} notifications');
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
print('Failed to delete notifications: ${response.statusCode}');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
print('Error when deleting all notifications: $e');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _getUsername(String email) async {
|
||||||
|
final url = Uri.parse(
|
||||||
|
'https://nexuschat.derickexm.be/users/get_username/?email=$email');
|
||||||
|
try {
|
||||||
|
final response =
|
||||||
|
await http.get(url, headers: {'Accept': 'application/json'});
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
final data = jsonDecode(response.body);
|
||||||
|
if (mounted) {
|
||||||
|
setState(() {
|
||||||
|
username = data['username'];
|
||||||
|
prefs.setString('username', username!);
|
||||||
|
isUsernameReady = true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
print("❌ Impossible de récupérer le nom d'utilisateur");
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
print("❌ Erreur de connexion à l'API : $e");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _initializeNotifications() {}
|
||||||
|
|
||||||
|
Future<List<Map<String, dynamic>>> fetchNotifications(
|
||||||
|
String? username) async {
|
||||||
|
if (username == null || username.isEmpty) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
final response = await http.get(Uri.parse(
|
||||||
|
'https://nexuschat.derickexm.be/users/get_notifications?username=$username'));
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
final decoded = jsonDecode(response.body);
|
||||||
|
final List notifications = decoded['notifications'];
|
||||||
|
return notifications.cast<Map<String, dynamic>>();
|
||||||
|
} else {
|
||||||
|
throw Exception('Erreur de chargement des notifications');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<bool> _showConfirmationDialog(BuildContext context) async {
|
||||||
|
return await showDialog<bool>(
|
||||||
|
context: context,
|
||||||
|
builder: (context) {
|
||||||
|
return AlertDialog(
|
||||||
|
title: Text('Confirmation'),
|
||||||
|
content: Text(
|
||||||
|
'Voulez-vous vraiment supprimer toutes les notifications ?'),
|
||||||
|
actions: [
|
||||||
|
TextButton(
|
||||||
|
onPressed: () {
|
||||||
|
Navigator.pop(context, false);
|
||||||
|
},
|
||||||
|
child: Text('Annuler'),
|
||||||
|
),
|
||||||
|
TextButton(
|
||||||
|
onPressed: () {
|
||||||
|
Navigator.pop(context, true);
|
||||||
|
},
|
||||||
|
child: Text('Supprimer'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
},
|
||||||
|
) ??
|
||||||
|
false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Scaffold(
|
||||||
|
appBar: AppBar(
|
||||||
|
title: Text('Notifications'),
|
||||||
|
actions: [
|
||||||
|
IconButton(
|
||||||
|
icon: Icon(Icons.delete_sweep),
|
||||||
|
tooltip: 'Supprimer toutes les notifications',
|
||||||
|
onPressed: () async {
|
||||||
|
bool confirm = await _showConfirmationDialog(context);
|
||||||
|
if (confirm) {
|
||||||
|
bool success = await deleteAllNotifications();
|
||||||
|
if (success) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text(
|
||||||
|
'Toutes les notifications ont été supprimées')),
|
||||||
|
);
|
||||||
|
if (mounted) {
|
||||||
|
setState(() {});
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content:
|
||||||
|
Text('Échec de la suppression des notifications')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
body: isUsernameReady
|
||||||
|
? FutureBuilder<List<Map<String, dynamic>>>(
|
||||||
|
future: fetchNotifications(username),
|
||||||
|
builder: (context, snapshot) {
|
||||||
|
if (snapshot.connectionState == ConnectionState.waiting) {
|
||||||
|
return Center(child: CircularProgressIndicator());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (snapshot.hasError) {
|
||||||
|
return Center(
|
||||||
|
child: Text('Erreur: ${snapshot.error}'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
final notifications = snapshot.data ?? [];
|
||||||
|
|
||||||
|
if (notifications.isEmpty) {
|
||||||
|
return Center(
|
||||||
|
child: Text('Aucune notification pour le moment'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return ListView.builder(
|
||||||
|
itemCount: notifications.length,
|
||||||
|
itemBuilder: (context, index) {
|
||||||
|
final notification = notifications[index];
|
||||||
|
final username = notification['owner'] ?? 'inconnu';
|
||||||
|
|
||||||
|
final message = notification['contenu'] ?? 'Pas de contenu';
|
||||||
|
|
||||||
|
final timestamp = notification.containsKey('date_creation')
|
||||||
|
? DateTime.parse(notification['date_creation'])
|
||||||
|
: DateTime.now();
|
||||||
|
|
||||||
|
var formattedTimestamp =
|
||||||
|
DateFormat('dd MMM yyyy, HH:mm').format(timestamp);
|
||||||
|
|
||||||
|
return Container(
|
||||||
|
decoration: BoxDecoration(),
|
||||||
|
margin:
|
||||||
|
EdgeInsets.symmetric(vertical: 4.0, horizontal: 8.0),
|
||||||
|
child: ListTile(
|
||||||
|
trailing: IconButton(
|
||||||
|
icon: Icon(Icons.delete),
|
||||||
|
onPressed: () async {
|
||||||
|
await _deleteNotification(
|
||||||
|
notification['id'].toString());
|
||||||
|
if (mounted) {
|
||||||
|
setState(() {});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
),
|
||||||
|
leading: CircleAvatar(
|
||||||
|
child: Icon(
|
||||||
|
Icons.notifications,
|
||||||
|
size: 30,
|
||||||
|
color: Colors.black,
|
||||||
|
),
|
||||||
|
backgroundColor: Colors.white38,
|
||||||
|
),
|
||||||
|
title: Text(
|
||||||
|
username ?? '',
|
||||||
|
style: TextStyle(fontWeight: FontWeight.bold),
|
||||||
|
),
|
||||||
|
subtitle: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
message,
|
||||||
|
style: TextStyle(fontWeight: FontWeight.bold),
|
||||||
|
),
|
||||||
|
SizedBox(height: 4.0),
|
||||||
|
Text(
|
||||||
|
formattedTimestamp,
|
||||||
|
style:
|
||||||
|
TextStyle(fontSize: 12, color: Colors.grey),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
onTap: () {
|
||||||
|
setState(() {
|
||||||
|
selectedNotificationId = notification['id'];
|
||||||
|
print(
|
||||||
|
"Notification sélectionnée : $selectedNotificationId");
|
||||||
|
});
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
},
|
||||||
|
)
|
||||||
|
: Center(child: CircularProgressIndicator()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _showNotification(
|
||||||
|
BuildContext context, Map<String, dynamic>? notificationData) async {
|
||||||
|
var source =
|
||||||
|
notificationData != null && notificationData.containsKey('type')
|
||||||
|
? notificationData['type']
|
||||||
|
: "divers";
|
||||||
|
var message =
|
||||||
|
notificationData != null && notificationData.containsKey('contenu')
|
||||||
|
? notificationData['contenu']
|
||||||
|
: "Pas de message";
|
||||||
|
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text("🔔 $source : $message"),
|
||||||
|
duration: Duration(seconds: 3),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -402,15 +402,6 @@ class _ProfilState extends State<Profil> {
|
|||||||
child: const Text("Envoyer l'email de vérification"),
|
child: const Text("Envoyer l'email de vérification"),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 20),
|
const SizedBox(height: 20),
|
||||||
const Text("Statut",
|
|
||||||
style:
|
|
||||||
TextStyle(fontWeight: FontWeight.bold, fontSize: 20)),
|
|
||||||
const SizedBox(height: 3),
|
|
||||||
Text(
|
|
||||||
"Dernière activité : Non spécifié",
|
|
||||||
style: const TextStyle(fontSize: 20),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 10),
|
|
||||||
ElevatedButton(
|
ElevatedButton(
|
||||||
onPressed: () {
|
onPressed: () {
|
||||||
showDialog(
|
showDialog(
|
||||||
|
|||||||
@@ -97,6 +97,22 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.0.8"
|
version: "1.0.8"
|
||||||
|
dio:
|
||||||
|
dependency: "direct main"
|
||||||
|
description:
|
||||||
|
name: dio
|
||||||
|
sha256: "253a18bbd4851fecba42f7343a1df3a9a4c1d31a2c1b37e221086b4fa8c8dbc9"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "5.8.0+1"
|
||||||
|
dio_web_adapter:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: dio_web_adapter
|
||||||
|
sha256: "7586e476d70caecaf1686d21eee7247ea43ef5c345eab9e0cc3583ff13378d78"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.1.1"
|
||||||
fake_async:
|
fake_async:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ dependencies:
|
|||||||
# Use with the CupertinoIcons class for iOS style icons.
|
# Use with the CupertinoIcons class for iOS style icons.
|
||||||
cupertino_icons: ^1.0.8
|
cupertino_icons: ^1.0.8
|
||||||
|
|
||||||
|
|
||||||
flutter_giphy_picker: ^1.0.5
|
flutter_giphy_picker: ^1.0.5
|
||||||
http: ^1.4.0
|
http: ^1.4.0
|
||||||
adaptive_theme: ^3.6.0
|
adaptive_theme: ^3.6.0
|
||||||
@@ -44,6 +45,8 @@ dependencies:
|
|||||||
file_picker: ^5.0.0
|
file_picker: ^5.0.0
|
||||||
image: ^3.0.1
|
image: ^3.0.1
|
||||||
shared_preferences: ^2.2.2
|
shared_preferences: ^2.2.2
|
||||||
|
dio: ^5.8.0+1
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user