From 3b9a39407d9d9433095e78369112606912969cc3 Mon Sep 17 00:00:00 2001 From: Lucas Delanier Date: Wed, 16 Aug 2023 01:21:54 +0200 Subject: [PATCH] historic page --- .../lib/components/historic_component.dart | 122 +++++++++--------- .../justMUSIC/lib/services/MusicService.dart | 19 +-- .../justMUSIC/lib/services/PostService.dart | 38 ++---- .../lib/view_model/MusicViewModel.dart | 107 ++++++--------- 4 files changed, 116 insertions(+), 170 deletions(-) diff --git a/Sources/justMUSIC/lib/components/historic_component.dart b/Sources/justMUSIC/lib/components/historic_component.dart index f8cc9a3..db18e71 100644 --- a/Sources/justMUSIC/lib/components/historic_component.dart +++ b/Sources/justMUSIC/lib/components/historic_component.dart @@ -26,73 +26,71 @@ class _HistoricComponentState extends State { } getHistoric() {} - List> historic = [ - Tuple2(1, MyApp.postViewModel.bestPosts.first.music), - Tuple2(3, MyApp.postViewModel.bestPosts.first.music), - Tuple2(11, MyApp.postViewModel.bestPosts.first.music) - ]; @override Widget build(BuildContext context) { return FutureBuilder( - future: , - builder: (context, snapshot){ - if(snapshot.hasData){ - return Wrap( - spacing: 14, - runSpacing: 14, - children: List.generate(getNumberOfDaysInMonth(widget.year, widget.month), (index) { - Tuple2? checkCapsule; - for (var element in historic) { - if (element.item1 == index + 1) { - checkCapsule = element; - } - } - if ((widget.year > DateTime.now().year || widget.month > DateTime.now().month) || - (widget.year == DateTime.now().year && - widget.month == DateTime.now().month && - index > DateTime.now().day)) { - return Container( - decoration: BoxDecoration( - gradient: LinearGradient(colors: [ - Color(0xFF1E1E1E).withOpacity(0.7), - Color(0xFF1E1E1E).withOpacity(0), - ], begin: Alignment.topCenter, end: Alignment.bottomCenter), - borderRadius: BorderRadius.circular(5)), - height: 60, - width: 60, - ); - } - if (checkCapsule != null) { - return Container( - decoration: BoxDecoration( - image: DecorationImage(image: NetworkImage((checkCapsule.item2.cover)!)), - borderRadius: BorderRadius.circular(5)), - height: 60, - width: 60, - ); - } else { - return Container( - color: bgColor, - height: 60, - width: 60, - child: Center( - child: Text( - (index + 1).toString(), - style: GoogleFonts.plusJakartaSans(color: Colors.white, fontSize: 22, fontWeight: FontWeight.w800), - ), - ), - ); - } + future: MyApp.musicViewModel + .getHistoryCapsulesMonthWhitIdUser(MyApp.userViewModel.userCurrent.id, widget.month, widget.year), + builder: (context, snapshot) { + if (snapshot.hasData) { + return Wrap( + spacing: 14, + runSpacing: 14, + children: List.generate(getNumberOfDaysInMonth(widget.year, widget.month), (index) { + Tuple2? checkCapsule; + if (snapshot.data != null) { + for (var element in snapshot.data!) { + if (element.item1 == index + 1) { + checkCapsule = element; + } + } + } - // Generate widgets - }), - ); - } - else{ - return CupertinoActivityIndicator(); - } + if ((widget.year > DateTime.now().year || widget.month > DateTime.now().month) || + (widget.year == DateTime.now().year && + widget.month == DateTime.now().month && + index > DateTime.now().day)) { + return Container( + decoration: BoxDecoration( + gradient: LinearGradient(colors: [ + Color(0xFF1E1E1E).withOpacity(0.7), + Color(0xFF1E1E1E).withOpacity(0), + ], begin: Alignment.topCenter, end: Alignment.bottomCenter), + borderRadius: BorderRadius.circular(5)), + height: 60, + width: 60, + ); + } + if (checkCapsule != null) { + return Container( + decoration: BoxDecoration( + image: DecorationImage(image: NetworkImage((checkCapsule.item2.cover)!)), + borderRadius: BorderRadius.circular(5)), + height: 60, + width: 60, + ); + } else { + return Container( + color: bgColor, + height: 60, + width: 60, + child: Center( + child: Text( + (index + 1).toString(), + style: + GoogleFonts.plusJakartaSans(color: Colors.white, fontSize: 22, fontWeight: FontWeight.w800), + ), + ), + ); + } - }); + // Generate widgets + }), + ); + } else { + return CupertinoActivityIndicator(); + } + }); } } diff --git a/Sources/justMUSIC/lib/services/MusicService.dart b/Sources/justMUSIC/lib/services/MusicService.dart index 8d4f4f6..d1b80b6 100644 --- a/Sources/justMUSIC/lib/services/MusicService.dart +++ b/Sources/justMUSIC/lib/services/MusicService.dart @@ -5,8 +5,7 @@ import '../main.dart'; class MusicService { Future getFavoriteMusicsByUserId(String id) async { - var response = - await FirebaseFirestore.instance.collection("users").doc(id).get(); + var response = await FirebaseFirestore.instance.collection("users").doc(id).get(); if (response.exists) { var musicFavorite = response.get("musics_likes"); return List.from(musicFavorite); @@ -16,9 +15,7 @@ class MusicService { } deleteFavoriteMusic(String id) async { - var userRef = await FirebaseFirestore.instance - .collection("users") - .doc(MyApp.userViewModel.userCurrent.id); + var userRef = await FirebaseFirestore.instance.collection("users").doc(MyApp.userViewModel.userCurrent.id); var response = await userRef.get(); List musicFavorite = List.from(response.get("musics_likes")); @@ -31,9 +28,7 @@ class MusicService { } Future addOrDeleteFavoriteMusic(String id) async { - var userRef = await FirebaseFirestore.instance - .collection("users") - .doc(MyApp.userViewModel.userCurrent.id); + var userRef = await FirebaseFirestore.instance.collection("users").doc(MyApp.userViewModel.userCurrent.id); var response = await userRef.get(); List musicFavorite = List.from(response.get("musics_likes")); @@ -48,9 +43,8 @@ class MusicService { } } - Future>> getHistoryCapsulesMonthWhitIdUser( - String idUser, int month, int year) async { - List> capsules = []; + Future>> getHistoryCapsulesMonthWhitIdUser(String idUser, int month, int year) async { + List> capsules = []; var querySnapshot = await FirebaseFirestore.instance .collection('posts') @@ -61,8 +55,7 @@ class MusicService { .get(); for (var document in querySnapshot.docs) { - capsules.add(Tuple2(document.data()['date'].toDate().day.toString(), - document.data()['idMusic'])); + capsules.add(Tuple2(document.data()['date'].toDate().day, document.data()['song_id'])); } return capsules; diff --git a/Sources/justMUSIC/lib/services/PostService.dart b/Sources/justMUSIC/lib/services/PostService.dart index 3eb1819..17e2645 100644 --- a/Sources/justMUSIC/lib/services/PostService.dart +++ b/Sources/justMUSIC/lib/services/PostService.dart @@ -7,8 +7,7 @@ import 'package:firebase_storage/firebase_storage.dart'; import '../main.dart'; class PostService { - createPost(String? description, String idMusic, File? image, - Tuple2? location) async { + createPost(String? description, String idMusic, File? image, Tuple2? location) async { var id = MyApp.userViewModel.userCurrent.id; final post = { "user_id": id, @@ -42,14 +41,11 @@ class PostService { deletePost() {} - Future>>> getPopularPosts( - {int limit = 10, int offset = 0}) async { + Future>>> getPopularPosts({int limit = 10, int offset = 0}) async { DateTime twentyFourHoursAgo = DateTime.now().subtract(Duration(hours: 24)); - Timestamp twentyFourHoursAgoTimestamp = - Timestamp.fromDate(twentyFourHoursAgo); + Timestamp twentyFourHoursAgoTimestamp = Timestamp.fromDate(twentyFourHoursAgo); - QuerySnapshot> response = await FirebaseFirestore - .instance + QuerySnapshot> response = await FirebaseFirestore.instance .collection("posts") .where("date", isGreaterThan: twentyFourHoursAgoTimestamp) .limit(limit) @@ -67,8 +63,7 @@ class PostService { return Timestamp.fromDate(twentyFourHoursAgo); } - Future>>> getPostsFriends( - {int limit = 10, int offset = 0}) async { + Future>>> getPostsFriends({int limit = 10, int offset = 0}) async { var timestamp = _getTwentyFourHoursAgoTimestamp(); var response = await FirebaseFirestore.instance .collection("posts") @@ -84,17 +79,12 @@ class PostService { Future getAvailable(String idUser) async { DateTime today = DateTime.now(); - QuerySnapshot> response = await FirebaseFirestore - .instance - .collection("posts") - .where("user_id", isEqualTo: idUser) - .get(); + QuerySnapshot> response = + await FirebaseFirestore.instance.collection("posts").where("user_id", isEqualTo: idUser).get(); bool isTodayAvailable = response.docs.any((doc) { DateTime date = doc["date"].toDate(); // Assuming the field name is "date" - return date.day == today.day && - date.month == today.month && - date.year == today.year; + return date.day == today.day && date.month == today.month && date.year == today.year; }); return !isTodayAvailable; @@ -105,15 +95,11 @@ class PostService { DateTime sevenDaysAgo = DateTime.now().subtract(Duration(days: 6)); - QuerySnapshot> response = await FirebaseFirestore - .instance - .collection("posts") - .where("user_id", isEqualTo: id) - .get(); + QuerySnapshot> response = + await FirebaseFirestore.instance.collection("posts").where("user_id", isEqualTo: id).get(); - List?> postList = response.docs - .map((DocumentSnapshot> doc) => doc.data()) - .toList(); + List?> postList = + response.docs.map((DocumentSnapshot> doc) => doc.data()).toList(); for (int i = 0; i < 7; i++) { DateTime date = sevenDaysAgo.add(Duration(days: i)); diff --git a/Sources/justMUSIC/lib/view_model/MusicViewModel.dart b/Sources/justMUSIC/lib/view_model/MusicViewModel.dart index 1e2c531..e5fedd8 100644 --- a/Sources/justMUSIC/lib/view_model/MusicViewModel.dart +++ b/Sources/justMUSIC/lib/view_model/MusicViewModel.dart @@ -28,8 +28,7 @@ class MusicViewModel { return _getMusicFromResponse(responseData); } else { - throw Exception( - 'Error retrieving music information : ${response.statusCode} ${response.reasonPhrase}'); + throw Exception('Error retrieving music information : ${response.statusCode} ${response.reasonPhrase}'); } } @@ -49,15 +48,12 @@ class MusicViewModel { artists); } - Future> getMusicsWithName(String name, - {int limit = 20, int offset = 0, String market = "FR"}) async { + Future> getMusicsWithName(String name, {int limit = 20, int offset = 0, String market = "FR"}) async { var accessToken = await _token.getAccessToken(); - var response = await http.get( - Uri.parse( - '$API_URL/search?q=track%3A$name&type=track&market=fr&limit=$limit&offset=$offset'), - headers: { - 'Authorization': 'Bearer $accessToken', - }); + var response = await http + .get(Uri.parse('$API_URL/search?q=track%3A$name&type=track&market=fr&limit=$limit&offset=$offset'), headers: { + 'Authorization': 'Bearer $accessToken', + }); if (response.statusCode == 200) { Map responseData = jsonDecode(response.body); @@ -65,20 +61,17 @@ class MusicViewModel { return _getMusicFromResponse(track); })); } else { - throw Exception( - 'Error while retrieving music : ${response.statusCode} ${response.reasonPhrase}'); + throw Exception('Error while retrieving music : ${response.statusCode} ${response.reasonPhrase}'); } } Future> getMusicsWithArtistName(String name, {int limit = 20, int offset = 0, String market = "FR"}) async { var accessToken = await _token.getAccessToken(); - var response = await http.get( - Uri.parse( - '$API_URL/search?q=artist%3A$name&type=track&market=fr&limit=$limit&offset=$offset'), - headers: { - 'Authorization': 'Bearer $accessToken', - }); + var response = await http + .get(Uri.parse('$API_URL/search?q=artist%3A$name&type=track&market=fr&limit=$limit&offset=$offset'), headers: { + 'Authorization': 'Bearer $accessToken', + }); if (response.statusCode == 200) { Map responseData = jsonDecode(response.body); @@ -86,24 +79,19 @@ class MusicViewModel { return _getMusicFromResponse(track); })); } else { - throw Exception( - 'Error while retrieving music : ${response.statusCode} ${response.reasonPhrase}'); + throw Exception('Error while retrieving music : ${response.statusCode} ${response.reasonPhrase}'); } } Future getArtistWithName(String name, {String market = "FR"}) async { var accessToken = await _token.getAccessToken(); - var response = await http.get( - Uri.parse( - '$API_URL/search?q=artist%3A$name&type=artist&market=$market'), - headers: { - 'Authorization': 'Bearer $accessToken', - }); + var response = await http.get(Uri.parse('$API_URL/search?q=artist%3A$name&type=artist&market=$market'), headers: { + 'Authorization': 'Bearer $accessToken', + }); if (response.statusCode == 200) { final responseData = jsonDecode(response.body); - List artists = - List.from(responseData['artists']['items'].map((artist) { + List artists = List.from(responseData['artists']['items'].map((artist) { String image = ''; if (!artist['images'].isEmpty) { image = artist['images'][0]['url']; @@ -119,25 +107,21 @@ class MusicViewModel { throw Exception('Artist not found : ${name}'); } else { - throw Exception( - 'Error retrieving artist information : ${response.statusCode} ${response.reasonPhrase}'); + throw Exception('Error retrieving artist information : ${response.statusCode} ${response.reasonPhrase}'); } } - Future> getArtistsWithName(String name, - {int limit = 20, int offset = 0, String market = "FR"}) async { + Future> getArtistsWithName(String name, {int limit = 20, int offset = 0, String market = "FR"}) async { var accessToken = await _token.getAccessToken(); var response = await http.get( - Uri.parse( - '$API_URL/search?q=artist%3A$name&type=artist&market=$market&limit=$limit&offset=$offset'), + Uri.parse('$API_URL/search?q=artist%3A$name&type=artist&market=$market&limit=$limit&offset=$offset'), headers: { 'Authorization': 'Bearer $accessToken', }); if (response.statusCode == 200) { final responseData = jsonDecode(response.body); - List artists = - List.from(responseData['artists']['items'].map((artist) { + List artists = List.from(responseData['artists']['items'].map((artist) { String image = ''; if (!artist['images'].isEmpty) { image = artist['images'][0]['url']; @@ -147,19 +131,15 @@ class MusicViewModel { return artists; } else { - throw Exception( - 'Error while retrieving artist : ${response.statusCode} ${response.reasonPhrase}'); + throw Exception('Error while retrieving artist : ${response.statusCode} ${response.reasonPhrase}'); } } - Future> getTopMusicsWithArtistId(String id, - {String market = "FR"}) async { + Future> getTopMusicsWithArtistId(String id, {String market = "FR"}) async { var accessToken = await _token.getAccessToken(); - var response = await http.get( - Uri.parse('$API_URL/artists/$id/top-tracks?market=$market'), - headers: { - 'Authorization': 'Bearer $accessToken', - }); + var response = await http.get(Uri.parse('$API_URL/artists/$id/top-tracks?market=$market'), headers: { + 'Authorization': 'Bearer $accessToken', + }); if (response.statusCode == 200) { Map responseData = jsonDecode(response.body); @@ -167,16 +147,13 @@ class MusicViewModel { return _getMusicFromResponse(track); })); } else { - throw Exception( - 'Error while retrieving music : ${response.statusCode} ${response.reasonPhrase}'); + throw Exception('Error while retrieving music : ${response.statusCode} ${response.reasonPhrase}'); } } - Future> getMusicsWithPlaylistId(String id, - {String market = "FR"}) async { + Future> getMusicsWithPlaylistId(String id, {String market = "FR"}) async { var accessToken = await _token.getAccessToken(); - var response = await http - .get(Uri.parse('$API_URL/playlists/$id?market=$market'), headers: { + var response = await http.get(Uri.parse('$API_URL/playlists/$id?market=$market'), headers: { 'Authorization': 'Bearer $accessToken', }); @@ -192,13 +169,11 @@ class MusicViewModel { return musics; } else { - throw Exception( - 'Error while retrieving music : ${response.statusCode} ${response.reasonPhrase}'); + throw Exception('Error while retrieving music : ${response.statusCode} ${response.reasonPhrase}'); } } - Future> getMusicsWithIds(List ids, - {String market = "FR"}) async { + Future> getMusicsWithIds(List ids, {String market = "FR"}) async { var accessToken = await _token.getAccessToken(); String url = API_URL + '/tracks?market=$market&ids='; @@ -216,8 +191,7 @@ class MusicViewModel { return _getMusicFromResponse(track); })); } else { - throw Exception( - 'Error while retrieving music : ${response.statusCode} ${response.reasonPhrase}'); + throw Exception('Error while retrieving music : ${response.statusCode} ${response.reasonPhrase}'); } } @@ -227,12 +201,10 @@ class MusicViewModel { List musics = []; Artist artist = await getArtistWithName(name, market: market); musics.addAll(await getTopMusicsWithArtistId(artist.id)); - musics.addAll(await getMusicsWithName(name, - limit: limit, offset: offset, market: market)); + musics.addAll(await getMusicsWithName(name, limit: limit, offset: offset, market: market)); return musics; } catch (e) { - return await getMusicsWithName(name, - limit: limit, offset: offset, market: market); + return await getMusicsWithName(name, limit: limit, offset: offset, market: market); } } @@ -255,21 +227,18 @@ class MusicViewModel { } } - Future>> getHistoryCapsulesMonthWhitIdUser( - String idUser, int month, int year) async { + Future>> getHistoryCapsulesMonthWhitIdUser(String idUser, int month, int year) async { try { - List> capsules = []; - var capsulesData = await _musicService.getHistoryCapsulesMonthWhitIdUser( - idUser, month, year); + List> capsules = []; + var capsulesData = await _musicService.getHistoryCapsulesMonthWhitIdUser(idUser, month, year); - var musics = await getMusicsWithIds( - capsulesData.map((capsule) => capsule.item2).toList()); + var musics = await getMusicsWithIds(capsulesData.map((capsule) => capsule.item2).toList()); for (var capsule in capsulesData) { var music = musics.firstWhere((music) => music.id == capsule.item2); + print(capsule.item1); capsules.add(Tuple2(capsule.item1, music)); } - return capsules; } catch (e) { print(e);