From 5ef83b3340c984fc6df0cb123dfb244b24ba0267 Mon Sep 17 00:00:00 2001 From: emkartal1 Date: Thu, 3 Aug 2023 02:33:04 +0200 Subject: [PATCH] Add Function sendPushMessage and fix error UserService --- Sources/justMUSIC/lib/main.dart | 56 ++++++++++--------- Sources/justMUSIC/lib/model/User.dart | 11 +++- .../lib/model/mapper/UserMapper.dart | 1 + .../justMUSIC/lib/services/AuthService.dart | 10 ++++ .../lib/services/NotificationService.dart | 42 +++++++++----- .../justMUSIC/lib/services/PostService.dart | 2 +- .../justMUSIC/lib/services/UserService.dart | 27 +++++++-- .../lib/view_model/UserViewModel.dart | 29 ++++++++-- 8 files changed, 123 insertions(+), 55 deletions(-) diff --git a/Sources/justMUSIC/lib/main.dart b/Sources/justMUSIC/lib/main.dart index b9448c7..577a1d4 100644 --- a/Sources/justMUSIC/lib/main.dart +++ b/Sources/justMUSIC/lib/main.dart @@ -3,6 +3,7 @@ import 'package:audioplayers/audioplayers.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_core/firebase_core.dart'; +import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -16,7 +17,6 @@ import 'package:justmusic/screens/post_screen.dart'; import 'package:justmusic/screens/profile_screen.dart'; import 'package:justmusic/screens/registration_screen.dart'; import 'package:justmusic/screens/welcome_screen.dart'; -import 'package:justmusic/services/NotificationService.dart'; import 'package:justmusic/values/constants.dart'; import 'package:justmusic/view_model/MusicViewModel.dart'; import 'package:justmusic/view_model/PostViewModel.dart'; @@ -29,7 +29,7 @@ Future main() async { await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); - await NotificationService().initNotifications(); + await FirebaseMessaging.instance.requestPermission(sound: true); runApp(const MyApp()); } @@ -63,7 +63,8 @@ class _MyAppState extends State { print('User is currently signed out!'); return null; } else { - MyApp.userViewModel.userCurrent = (await (MyApp.userViewModel.getUser(user.uid)))!; + MyApp.userViewModel.userCurrent = + (await (MyApp.userViewModel.getUser(user.uid)))!; userCurrent = Stream.value(MyApp.userViewModel.userCurrent); print('User is signed in!'); } @@ -112,31 +113,32 @@ class _MyAppState extends State { ), home: FirebaseAuth.instance.currentUser != null ? StreamBuilder( - stream: userCurrent, - initialData: null, - builder: (context, snapshot) { - if (snapshot.hasData) { - print("hasdata"); + stream: userCurrent, + initialData: null, + builder: (context, snapshot) { + if (snapshot.hasData) { + print("hasdata"); - return AnimatedSwitcher( - duration: Duration(milliseconds: 1000), - transitionBuilder: (child, animation) { - return FadeTransition(opacity: animation, child: child); - }, - child: FeedScreen(), - ); - } else { - return Scaffold( - backgroundColor: bgColor, - body: Center( - child: Image( - image: AssetImage("assets/images/logo.png"), - width: 130, - ), - ), - ); - } - }) + return AnimatedSwitcher( + duration: Duration(milliseconds: 1000), + transitionBuilder: (child, animation) { + return FadeTransition( + opacity: animation, child: child); + }, + child: FeedScreen(), + ); + } else { + return Scaffold( + backgroundColor: bgColor, + body: Center( + child: Image( + image: AssetImage("assets/images/logo.png"), + width: 130, + ), + ), + ); + } + }) : WellcomeScreen()); }, designSize: Size(390, 844), diff --git a/Sources/justMUSIC/lib/model/User.dart b/Sources/justMUSIC/lib/model/User.dart index 2507da7..d88a05e 100644 --- a/Sources/justMUSIC/lib/model/User.dart +++ b/Sources/justMUSIC/lib/model/User.dart @@ -4,13 +4,14 @@ class User { String _uniquePseudo; String _mail; String _pp; + String _token; List _followers; int _capsules; List _followed; // Constructor - User(this._id, this._pseudo, this._uniquePseudo, this._mail, - this._pp, this._followers, this._capsules, this._followed); + User(this._id, this._pseudo, this._uniquePseudo, this._mail, this._pp, + this._token, this._followers, this._capsules, this._followed); //Getters and setters String get id => _id; @@ -39,6 +40,12 @@ class User { _pp = value; } + String get token => _token; + + set token(String value) { + _token = value; + } + int get capsules => _capsules; set capsules(int value) { diff --git a/Sources/justMUSIC/lib/model/mapper/UserMapper.dart b/Sources/justMUSIC/lib/model/mapper/UserMapper.dart index 7d4c6c1..7d0c5ab 100644 --- a/Sources/justMUSIC/lib/model/mapper/UserMapper.dart +++ b/Sources/justMUSIC/lib/model/mapper/UserMapper.dart @@ -10,6 +10,7 @@ class UserMapper { data?["unique_id"], data?["mail"], data?["picture"], + data?["token_notify"], List.from(data?["followers"] as List), data?["nbCapsules"] ?? 0, List.from(data?["followed"] as List)); diff --git a/Sources/justMUSIC/lib/services/AuthService.dart b/Sources/justMUSIC/lib/services/AuthService.dart index 818fddf..39ba6c2 100644 --- a/Sources/justMUSIC/lib/services/AuthService.dart +++ b/Sources/justMUSIC/lib/services/AuthService.dart @@ -1,15 +1,24 @@ import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; +import 'package:firebase_messaging/firebase_messaging.dart'; +import 'package:flutter/foundation.dart'; import '../main.dart'; class AuthService { register(String pseudo, String email, String password) async { try { + var token; final data = await FirebaseAuth.instance.createUserWithEmailAndPassword( email: email, password: password, ); + if (kIsWeb) { + token = "empty"; + } else { + token = await FirebaseMessaging.instance.getToken(); + } + String uniqueId = await generateUniqueId(pseudo); final user = { @@ -19,6 +28,7 @@ class AuthService { "followed": [], "nbCapsules": 0, "followers": [], + "token_notify": token, "picture": "https://firebasestorage.googleapis.com/v0/b/justmusic-435d5.appspot.com/o/justMusicDefaultImage.png?alt=media&token=020d0fcb-b7df-4d4d-b380-e99597293fcc" }; diff --git a/Sources/justMUSIC/lib/services/NotificationService.dart b/Sources/justMUSIC/lib/services/NotificationService.dart index 8582741..e37f2b3 100644 --- a/Sources/justMUSIC/lib/services/NotificationService.dart +++ b/Sources/justMUSIC/lib/services/NotificationService.dart @@ -1,18 +1,30 @@ -import 'package:firebase_messaging/firebase_messaging.dart'; +import 'dart:convert'; +import 'package:http/http.dart' as http; class NotificationService { - final _firebaseMessaging = FirebaseMessaging.instance; - - Future handleBackgroundMessage(RemoteMessage message) async { - print('Title: ${message.notification?.title}'); - print('Body: ${message.notification?.body}'); - print('Payload: ${message.data}'); - } - - Future initNotifications() async { - await _firebaseMessaging.requestPermission(); - final token = await _firebaseMessaging.getToken(); - print("Grrrpaw:"+token!); - //FirebaseMessaging.onBackgroundMessage(handleBackgroundMessage); + sendPushMessage(String token, String title, String body) async { + try { + await http.post(Uri.parse('https://fcm.googleapis.com/fcm/send'), + headers: { + 'Content-Type': 'application/json', + 'Authorization': 'key=' + }, + body: jsonEncode({ + 'priority': 'high', + 'data': { + 'click_action': 'FLUTTER_NOTIFICATION_CLICK', + 'status': 'done', + 'body': body, + 'title': title + }, + "notification": { + "title": title, + "body": body, + }, + "to": token, + })); + } catch (e) { + print("error push notification"); + } } -} \ No newline at end of file +} diff --git a/Sources/justMUSIC/lib/services/PostService.dart b/Sources/justMUSIC/lib/services/PostService.dart index 7e71ff4..4f86827 100644 --- a/Sources/justMUSIC/lib/services/PostService.dart +++ b/Sources/justMUSIC/lib/services/PostService.dart @@ -56,7 +56,7 @@ class PostService { .get(); var filteredPosts = response.docs.where((doc) { - String user = doc["user_id"]; // Assuming the field name is "date" + String user = doc["user_id"]; return user != MyApp.userViewModel.userCurrent.id; }).toList(); return filteredPosts; diff --git a/Sources/justMUSIC/lib/services/UserService.dart b/Sources/justMUSIC/lib/services/UserService.dart index 0a66793..b299f3d 100644 --- a/Sources/justMUSIC/lib/services/UserService.dart +++ b/Sources/justMUSIC/lib/services/UserService.dart @@ -3,11 +3,14 @@ import 'package:cloud_firestore/cloud_firestore.dart'; import '../main.dart'; class UserService { - Future>>> getUsersByIdUnique(String uniqueId) async { - QuerySnapshot> response = await FirebaseFirestore.instance + Future>>> getUsersByIdUnique( + String uniqueId) async { + QuerySnapshot> response = await FirebaseFirestore + .instance .collection("users") .where("unique_id", isGreaterThanOrEqualTo: uniqueId) - .where("unique_id", isLessThanOrEqualTo: uniqueId + "zzzzzzzzzzzzzzzzzzzzzzzzzzzz") + .where("unique_id", + isLessThanOrEqualTo: uniqueId + "zzzzzzzzzzzzzzzzzzzzzzzzzzzz") .limit(20) .get(); var users = response.docs.where((doc) { @@ -18,8 +21,20 @@ class UserService { return users; } + updateTokenNotify(String idUser, String token) { + FirebaseFirestore.instance + .collection('users') + .doc(idUser) + .update({'token_notify': token}).then((_) { + print("Mise à jour réussie !"); + }).catchError((error) { + print("Erreur lors de la mise à jour : $error"); + }); + } + addOrDeleteFriend(String id) async { - var userRef = MyApp.db.collection("users").doc(MyApp.userViewModel.userCurrent.id); + var userRef = + MyApp.db.collection("users").doc(MyApp.userViewModel.userCurrent.id); var actionUserRef = MyApp.db.collection("users").doc(id); if (MyApp.userViewModel.isFriend(id)) { @@ -28,7 +43,7 @@ class UserService { 'followed': FieldValue.arrayRemove([id]) }); transaction.update(actionUserRef, { - 'followers': FieldValue.arrayRemove([id]) + 'followers': FieldValue.arrayRemove([userRef.id]) }); }); MyApp.userViewModel.userCurrent.followed.remove(id); @@ -38,7 +53,7 @@ class UserService { 'followed': FieldValue.arrayUnion([id]) }); transaction.update(actionUserRef, { - 'followers': FieldValue.arrayUnion([id]) + 'followers': FieldValue.arrayUnion([userRef.id]) }); }); MyApp.userViewModel.userCurrent.followed.add(id); diff --git a/Sources/justMUSIC/lib/view_model/UserViewModel.dart b/Sources/justMUSIC/lib/view_model/UserViewModel.dart index 1817835..b3cf791 100644 --- a/Sources/justMUSIC/lib/view_model/UserViewModel.dart +++ b/Sources/justMUSIC/lib/view_model/UserViewModel.dart @@ -1,4 +1,6 @@ import 'package:firebase_auth/firebase_auth.dart' as firebase_auth; +import 'package:firebase_messaging/firebase_messaging.dart'; +import 'package:flutter/foundation.dart'; import 'package:justmusic/services/AuthService.dart'; import 'package:justmusic/services/UserService.dart'; @@ -27,8 +29,20 @@ class UserViewModel { login(String pseudo, String password) async { try { + var token; await authService.login(pseudo, password); - final user = await MyApp.db.collection("users").doc(firebase_auth.FirebaseAuth.instance.currentUser?.uid).get(); + final user = await MyApp.db + .collection("users") + .doc(firebase_auth.FirebaseAuth.instance.currentUser?.uid) + .get(); + if (!kIsWeb) { + token = await FirebaseMessaging.instance.getToken(); + if (MyApp.userViewModel.userCurrent.token != token) { + _userService.updateTokenNotify( + MyApp.userViewModel.userCurrent.id, token); + MyApp.userViewModel.userCurrent.token = token; + } + } User data = UserMapper.toModel(user); _userCurrent = data; } catch (e) { @@ -43,7 +57,10 @@ class UserViewModel { updateUserCurrent() async { try { - final user = await MyApp.db.collection("users").doc(firebase_auth.FirebaseAuth.instance.currentUser?.uid).get(); + final user = await MyApp.db + .collection("users") + .doc(firebase_auth.FirebaseAuth.instance.currentUser?.uid) + .get(); User data = UserMapper.toModel(user); _userCurrent = data; } catch (e) { @@ -58,7 +75,10 @@ class UserViewModel { try { await authService.register(pseudo.toLowerCase(), email, password); - final user = await MyApp.db.collection("users").doc(firebase_auth.FirebaseAuth.instance.currentUser?.uid).get(); + final user = await MyApp.db + .collection("users") + .doc(firebase_auth.FirebaseAuth.instance.currentUser?.uid) + .get(); User data = UserMapper.toModel(user); _userCurrent = data; } catch (e) { @@ -68,7 +88,8 @@ class UserViewModel { Future> getUsersByUniqueId(String uniqueId) async { try { - var response = await _userService.getUsersByIdUnique(uniqueId.toLowerCase()); + var response = + await _userService.getUsersByIdUnique(uniqueId.toLowerCase()); var users = response.map((value) { return UserMapper.toModel(value); }).toList();