This commit is contained in:
exmKrd
2025-06-13 08:22:17 +02:00
parent ef8d9ec59e
commit 863dfe6a0b
11 changed files with 1083 additions and 307 deletions

BIN
.DS_Store vendored

Binary file not shown.

View File

@@ -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 à lenvoi 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é à lAPI :");
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,198 +602,256 @@ class _ChatScreenState extends State<ChatScreen> {
), ),
title: Text(destinataire), title: Text(destinataire),
), ),
body: _isInitialLoading body: Stack(
? const Center(child: CircularProgressIndicator()) children: [
: Column( _isInitialLoading
children: [ ? const Center(child: CircularProgressIndicator())
Expanded( : Column(
child: ListView.builder( children: [
controller: _scrollController, Expanded(
itemCount: messages.length, child: ListView.builder(
itemBuilder: (context, index) { controller: _scrollController,
final message = messages[index]; itemCount: messages.length,
final isMe = message['sender'] == expediteur; itemBuilder: (context, index) {
final message = messages[index];
// Formatage de l'heure final isMe = message['sender'] == expediteur;
final time = return Container(
DateTime.tryParse(message['timestamp'] ?? ''); alignment: isMe
final formattedTime = time != null ? Alignment.centerRight
? "${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}" : Alignment.centerLeft,
: ''; margin: const EdgeInsets.symmetric(
vertical: 4, horizontal: 8),
return Container( child: Column(
alignment: crossAxisAlignment: isMe
isMe ? Alignment.centerRight : Alignment.centerLeft, ? CrossAxisAlignment.end
margin: const EdgeInsets.symmetric( : CrossAxisAlignment.start,
vertical: 4, horizontal: 8),
child: Column(
crossAxisAlignment: isMe
? CrossAxisAlignment.end
: CrossAxisAlignment.start,
children: [
Text(
message['sender'] ?? '',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 12,
color: Colors.grey[700],
),
),
Row(
mainAxisSize: MainAxisSize.min,
children: [ children: [
Flexible( Text(
child: GestureDetector( message['sender'] ?? '',
onLongPress: isMe style: TextStyle(
? () { fontWeight: FontWeight.bold,
showDialog( fontSize: 12,
context: context, color: Colors.grey[700],
builder: (BuildContext context) { ),
return AlertDialog( ),
title: Text( Row(
"Supprimer le message ?"), mainAxisSize: MainAxisSize.min,
actions: [ children: [
TextButton( Flexible(
child: Text("Annuler"), child: GestureDetector(
onPressed: () => onLongPress: isMe
Navigator.of(context) ? () {
.pop(), showDialog(
), context: context,
TextButton( builder:
child: Text("Supprimer"), (BuildContext context) {
onPressed: () { return AlertDialog(
Navigator.of(context) title: Text(
.pop(); "Supprimer le message ?"),
_supprimerMessage( actions: [
message); TextButton(
}, child:
), Text("Annuler"),
], onPressed: () =>
Navigator.of(
context)
.pop(),
),
TextButton(
child:
Text("Supprimer"),
onPressed: () {
Navigator.of(
context)
.pop();
_supprimerMessage(
message);
},
),
],
);
},
); );
}, }
); : null,
} child: Container(
: null, margin: const EdgeInsets.only(top: 2),
child: Container( padding: const EdgeInsets.all(10),
margin: const EdgeInsets.only(top: 2), decoration: BoxDecoration(
padding: const EdgeInsets.all(10), color: isMe
decoration: BoxDecoration( ? Colors.orange
color: isMe : Colors.grey[300],
? Colors.orange borderRadius:
: Colors.grey[300], BorderRadius.circular(10),
borderRadius: BorderRadius.circular(10), ),
child: message['type'] == 'gif'
? Image.network(
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(
color: isMe
? Colors.white
: Colors.black,
),
),
),
), ),
child: message['type'] == 'gif'
? Image.network(message['text'] ?? '')
: Text(
message['text'] ?? '',
style: TextStyle(
color: isMe
? Colors.white
: Colors.black,
),
),
), ),
],
),
Padding(
padding: const EdgeInsets.only(top: 2),
child: Builder(
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(
fontSize: 10,
color: Colors.grey[600]),
);
},
), ),
), ),
], ],
), ),
if (formattedTime.isNotEmpty) );
Padding( },
padding: const EdgeInsets.only(top: 2), ),
child: Text( ),
formattedTime, Padding(
style: TextStyle( padding: const EdgeInsets.all(8.0),
fontSize: 10, color: Colors.grey[600]), child: Column(
), mainAxisSize: MainAxisSize.min,
),
],
),
);
},
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [ children: [
Expanded( Row(
child: TextField( children: [
controller: _controller, Expanded(
focusNode: _focusNode, child: TextField(
style: TextStyle(fontSize: 16), controller: _controller,
cursorColor: Colors.orange, focusNode: _focusNode,
decoration: InputDecoration( style: TextStyle(fontSize: 16),
hintText: 'Entrez votre message...', cursorColor: Colors.orange,
border: OutlineInputBorder(), decoration: InputDecoration(
), hintText: 'Entrez votre message...',
minLines: 1, border: OutlineInputBorder(),
maxLines: 5, ),
keyboardType: TextInputType.multiline, minLines: 1,
textInputAction: TextInputAction.newline, maxLines: 5,
onChanged: (text) => _updateButtonState(), keyboardType: TextInputType.multiline,
onEditingComplete: () {}, textInputAction: TextInputAction.newline,
inputFormatters: [ onChanged: (text) => _updateButtonState(),
_EnterKeyFormatter( onEditingComplete: () {},
onEnter: () { inputFormatters: [
if (_controller.text.trim().isNotEmpty) { _EnterKeyFormatter(
sendMessage(_controller.text); onEnter: () {
_controller if (_controller.text
.clear(); // 👈 Ajout explicite du clear ici .trim()
} .isNotEmpty) {
}, sendMessage(_controller.text);
_controller.clear();
}
},
),
],
), ),
], ),
SizedBox(width: 5),
Container(
decoration: BoxDecoration(
color: Colors.orange.shade100,
borderRadius: BorderRadius.circular(12),
),
child: IconButton(
icon: Icon(Icons.gif_box,
color: Colors.deepOrange, size: 28),
onPressed: _selectGif,
tooltip: 'GIF',
),
),
SizedBox(width: 5),
Container(
decoration: BoxDecoration(
color: Colors.orange,
shape: BoxShape.circle,
),
child: IconButton(
icon: Icon(Icons.send, color: Colors.black),
onPressed: _isButtonEnabled
? () {
sendMessage(_controller.text);
_controller.clear();
_updateButtonState();
}
: null,
),
),
],
),
Padding(
padding: const EdgeInsets.only(bottom: 4, top: 2),
child: Text(
"🔒 Messages chiffrés de bout en bout",
style:
TextStyle(fontSize: 12, color: Colors.grey),
), ),
), ),
SizedBox(width: 8),
Container(
decoration: BoxDecoration(
color: Colors.orange.shade100, // plus doux
borderRadius: BorderRadius.circular(12),
),
child: IconButton(
icon: Icon(Icons.gif_box,
color: Colors.deepOrange, size: 28),
onPressed: _selectGif,
tooltip: 'GIF',
),
),
SizedBox(width: 5),
Container(
decoration: BoxDecoration(
color: Colors.orange,
shape: BoxShape.circle,
),
child: IconButton(
icon: Icon(Icons.send, color: Colors.black),
onPressed: _isButtonEnabled
? () {
sendMessage(_controller.text);
_controller.clear();
_updateButtonState();
}
: null,
),
),
SizedBox(width: 8),
], ],
), ),
Padding( ),
padding: const EdgeInsets.only(bottom: 4, top: 2), ],
child: Text(
"🔒 Messages chiffrés de bout en bout",
style: TextStyle(fontSize: 12, color: Colors.grey),
),
),
],
),
), ),
], if (_showScrollToBottom)
Positioned(
bottom: 100,
right: 16,
child: FloatingActionButton(
mini: true,
backgroundColor: Colors.orange,
child: Icon(Icons.arrow_downward),
onPressed: () => _scrollToBottom(force: true),
),
), ),
],
),
); );
} }
} }

View File

@@ -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(() {
_filteredUsers = _users if (query.isEmpty) {
.where((user) => user['username'].toLowerCase().contains(query)) _filteredUsers = [];
.toList(); } else {
_filteredUsers = _users
.where((user) => user['username'].toLowerCase().contains(query))
.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,54 +414,72 @@ 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(
itemCount: _filteredUsers.length, crossAxisAlignment: CrossAxisAlignment.start,
itemBuilder: (context, index) { children: [
final user = _filteredUsers[index]['username']; if (_searchController.text.isEmpty)
if (user == currentUser) return SizedBox(); 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,
itemBuilder: (context, index) {
final user = _filteredUsers[index]['username'];
if (user == currentUser) return SizedBox();
return FutureBuilder<String>( return FutureBuilder<String>(
future: _getEtatRelation(user), future: _getEtatRelation(user),
builder: (context, snapshot) { builder: (context, snapshot) {
String? etat = snapshot.data; String? etat = snapshot.data;
if (!snapshot.hasData) { if (!snapshot.hasData) {
return ListTile( return ListTile(
title: Text(user), title: Text(user),
subtitle: Text("Chargement..."), subtitle: Text("Chargement..."),
);
}
String label = "";
VoidCallback? action;
if (etat == "aucune_relation") {
label = "Envoyer demande";
action =
() => _envoyerDemandeContact(user);
} else if (etat == "pending_envoyee" ||
etat == "pending_recue") {
label = "Demande en attente";
action = null;
} else if (etat == "ami") {
return SizedBox(); // cacher les amis
} else {
label = "Erreur";
action = null;
}
return Card(
child: ListTile(
title: Text(user),
leading: Icon(Icons.person_outline),
trailing: ElevatedButton(
onPressed: action,
child: Text(label),
),
),
);
},
); );
} },
),
String label = ""; ),
VoidCallback? action; ],
if (etat == "aucune_relation") {
label = "Envoyer demande";
action = () => _envoyerDemandeContact(user);
} else if (etat == "pending_envoyee" ||
etat == "pending_recue") {
label = "Demande en attente";
action = null;
} else if (etat == "ami") {
return SizedBox(); // cacher les amis
} else {
label = "Erreur";
action = null;
}
return Card(
child: ListTile(
title: Text(user),
leading: Icon(Icons.person_outline),
trailing: ElevatedButton(
onPressed: action,
child: Text(label),
),
),
);
},
);
},
), ),
), ),
], ],

View 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'),
),
],
),
),
),
);
}
}

View File

@@ -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),
),
),
], ],
), ),
), ),

View File

@@ -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());
} }

View File

@@ -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",

View 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),
),
);
}
}

View File

@@ -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(

View File

@@ -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:

View File

@@ -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