Advertisement
mrblab

lib/services/firebase_service.dart

Dec 21st, 2023
300
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 11.00 KB | None | 0 0
  1. import 'package:cloud_firestore/cloud_firestore.dart';
  2. import 'package:firebase_auth/firebase_auth.dart';
  3. import 'package:flutter/material.dart';
  4. import 'package:quiz_app/models/question.dart';
  5. import 'package:quiz_app/models/quiz.dart';
  6. import '../models/category.dart';
  7. import '../models/sp_category.dart';
  8. import '../models/user.dart';
  9.  
  10. class FirebaseService {
  11.   FirebaseFirestore firestore = FirebaseFirestore.instance;
  12.  
  13.   Future<List<Category>> getCategories() async {
  14.     List<Category> data = [];
  15.     await firestore.collection('categories').orderBy('quiz_count', descending: true).get().then((QuerySnapshot? snapshot){
  16.       data = snapshot!.docs.map((e) => Category.fromFirestore(e)).toList();
  17.     });
  18.     return data;
  19.   }
  20.  
  21.   Future<List<Category>> getHomeCategories() async {
  22.     List<Category> data = [];
  23.     await firestore.collection('categories').orderBy('quiz_count', descending: true).limit(3).get().then((QuerySnapshot? snapshot){
  24.       data = snapshot!.docs.map((e) => Category.fromFirestore(e)).toList();
  25.     });
  26.     return data;
  27.   }
  28.  
  29.  
  30.   Future<List<Quiz>> getCategoryBasedQuizes(String selectedParentId) async {
  31.     List<Quiz> data = [];
  32.     await firestore.collection('quizes').where('parent_id', isEqualTo: selectedParentId).get().then((QuerySnapshot? snapshot){
  33.       data = snapshot!.docs.map((e) => Quiz.fromFirestore(e)).toList();
  34.     });
  35.     return data;
  36.   }
  37.  
  38.   Future<List<Quiz>> getCategoryBasedQuizesByLimit(String selectedParentId, int limit) async {
  39.     List<Quiz> data = [];
  40.     await firestore.collection('quizes').where('parent_id', isEqualTo: selectedParentId).limit(limit).get().then((QuerySnapshot? snapshot){
  41.       data = snapshot!.docs.map((e) => Quiz.fromFirestore(e)).toList();
  42.     });
  43.     return data;
  44.   }
  45.  
  46.   Future<List<Quiz>> getQuizes() async {
  47.     List<Quiz> data = [];
  48.     await firestore.collection('quizes').get().then((QuerySnapshot? snapshot){
  49.       data = snapshot!.docs.map((e) => Quiz.fromFirestore(e)).toList();
  50.     });
  51.     return data;
  52.   }
  53.  
  54.   Future<List<Category>> getFeaturedCategories() async {
  55.     List<Category> data = [];
  56.     await firestore
  57.         .collection('categories')
  58.         .where('featured', isEqualTo: true)
  59.         .limit(10)
  60.         .get()
  61.         .then((QuerySnapshot? snapshot) {
  62.       data = snapshot!.docs.map((e) => Category.fromFirestore(e)).toList();
  63.     });
  64.     return data;
  65.   }
  66.  
  67.   Future<List<Question>> getQuestions(String quizId) async {
  68.     List<Question> data = [];
  69.     await firestore.collection('questions').where('quiz_id', isEqualTo: quizId).orderBy('created_at', descending: false).get().then((QuerySnapshot? snapshot){
  70.       data = snapshot!.docs.map((e) => Question.fromFirestore(e)).toList();
  71.     });
  72.     return data;
  73.   }
  74.  
  75.   Future<List<Question>> getQuestionsforBookmark(List ids) async {
  76.     List<Question> data = [];
  77.     await firestore.collection('questions').where('id', whereIn: ids).orderBy('created_at', descending: false).get().then((QuerySnapshot? snapshot){
  78.       data = snapshot!.docs.map((e) => Question.fromFirestore(e)).toList();
  79.     });
  80.     return data;
  81.   }
  82.  
  83.   Future<List<Question>> getQuestionForSelfChallengeMode(String quizId, int questionAmount) async {
  84.     List<Question> data = [];
  85.     await firestore.collection('questions').where('quiz_id', isEqualTo: quizId).limit(questionAmount).get().then((QuerySnapshot? snapshot){
  86.       data = snapshot!.docs.map((e) => Question.fromFirestore(e)).toList();
  87.     });
  88.     return data;
  89.   }
  90.  
  91.   Future saveUserData(String id, String username, String email, String? avatarString, int initialReward) async {
  92.     return await firestore.collection('users').doc(id).set({
  93.       'id': id,
  94.       'email': email,
  95.       'name': username,
  96.       'avatar_string': avatarString,
  97.       'points': initialReward,
  98.       'disabled': false,
  99.       'created_at': DateTime.now(),
  100.     });
  101.   }
  102.  
  103.   Future<UserModel?> getUserData() async {
  104.     UserModel? user;
  105.     final String userId = FirebaseAuth.instance.currentUser!.uid;
  106.     final DocumentSnapshot snap = await firestore.collection('users').doc(userId).get();
  107.     if (snap.exists) {
  108.       user = UserModel.fromFirestore(snap);
  109.     }
  110.     return user;
  111.   }
  112.  
  113.   Future updateUserDataAfterAvatarSeclection(String userId, String avatarString) async {
  114.     return await firestore.collection('users').doc(userId).update({
  115.       'avatar_string': avatarString,
  116.       'updated_at': DateTime.now(),
  117.     });
  118.   }
  119.  
  120.   Future updateUserProfileOnEditScreen(String id, String name, String? avatarString, String? imageUrl) async {
  121.     return await firestore.collection('users').doc(id).update({
  122.       'name': name,
  123.       'avatar_string': avatarString,
  124.       'image_url': imageUrl,
  125.       'updated_at': DateTime.now(),
  126.     });
  127.   }
  128.  
  129.   Future<bool> checkUserExists(String userId) async {
  130.     DocumentSnapshot snap = await firestore.collection('users').doc(userId).get();
  131.     if (snap.exists) {
  132.       debugPrint('User Exists');
  133.       return true;
  134.     } else {
  135.       debugPrint('new user');
  136.       return false;
  137.     }
  138.   }
  139.  
  140.   Future<int> getTotalUsersCount() async {
  141.     const String fieldName = 'count';
  142.     final DocumentReference ref =
  143.         firestore.collection('item_count').doc('users_count');
  144.     DocumentSnapshot snap = await ref.get();
  145.     if (snap.exists == true) {
  146.       int itemCount = snap[fieldName] ?? 0;
  147.       return itemCount;
  148.     } else {
  149.       await ref.set({fieldName: 0});
  150.       return 0;
  151.     }
  152.   }
  153.  
  154.   Future increaseUserCount() async {
  155.     await getTotalUsersCount().then((int documentCount) async {
  156.       await firestore
  157.           .collection('item_count')
  158.           .doc('users_count')
  159.           .update({'count': documentCount + 1});
  160.     });
  161.   }
  162.  
  163.   Future decreaseUserCount() async {
  164.     await getTotalUsersCount().then((int documentCount) async {
  165.       await firestore
  166.           .collection('item_count')
  167.           .doc('users_count')
  168.           .update({'count': documentCount - 1});
  169.     });
  170.   }
  171.  
  172.   Future deleteUserDatafromDatabase(String userId) async {
  173.     await firestore.collection('users').doc(userId).delete();
  174.   }
  175.  
  176.   Future<int> getNewUserReward () async{
  177.     int reward = 0;
  178.     DocumentSnapshot snap = await firestore.collection('settings').doc('points').get();
  179.     if(snap.exists){
  180.       reward = snap.get('new_user_reward') ?? 0;
  181.     }else{
  182.       reward = 0;
  183.     }
  184.     return reward;
  185.   }
  186.  
  187.   Future<int> updateUserPointsByTransection (String userId, bool increment, int amount)async{
  188.     final docRef = firestore.collection("users").doc(userId);
  189.     int newPoints = 0;
  190.     await firestore.runTransaction((transaction) {
  191.       return transaction.get(docRef).then((snapshot) {
  192.         final UserModel userModel = UserModel.fromFirestore(snapshot);
  193.         final int getPoints = userModel.points ?? 0;
  194.         if(increment){
  195.           newPoints = getPoints + amount;
  196.         }else{
  197.           newPoints = getPoints - amount;
  198.         }
  199.         transaction.update(docRef, {"points": newPoints});
  200.       });
  201.     });
  202.     debugPrint('newPoints: $newPoints');
  203.     return newPoints;
  204.    
  205.   }
  206.  
  207.   Future updateUserPoints (String userId, int newPoints)async{
  208.     final docRef = firestore.collection("users").doc(userId);
  209.     return await docRef.update({
  210.       'points': newPoints
  211.     });
  212.    
  213.   }
  214.  
  215.  
  216.   Future updateUserStatToDatabase (String userId, int quizPlayed, int questionAnswered, int correctAns, int inCorrectAns) async{
  217.     final docRef = firestore.collection("users").doc(userId);
  218.     return await docRef.set({
  219.       'total_quiz_played': quizPlayed,
  220.       'question_ans_count': questionAnswered,
  221.       'correct_ans_count': correctAns,
  222.       'incorrect_ans_count': inCorrectAns
  223.     }, SetOptions(merge: true));
  224.   }
  225.  
  226.  
  227.   Future<List<UserModel>> getTopUsersData(int userAmout) async {
  228.     List<UserModel> data = [];
  229.     await firestore
  230.         .collection('users')
  231.         .orderBy('points', descending: true)
  232.         .limit(userAmout)
  233.         .get()
  234.         .then((QuerySnapshot? snapshot) {
  235.       data = snapshot!.docs.map((e) => UserModel.fromFirestore(e)).toList();
  236.     });
  237.     return data;
  238.   }
  239.  
  240.   Future updateUserPointHistory (String userId, String newString)async{
  241.     const String fieldName = 'points_history';
  242.     final docRef = firestore.collection("users").doc(userId);
  243.     await docRef.get().then((snapshot)async{
  244.       bool exists = snapshot.data()!.containsKey(fieldName);
  245.       List historyList = [];
  246.       if(exists){
  247.         historyList = snapshot.get(fieldName);
  248.         historyList.add(newString);
  249.       }else{
  250.         historyList.add(newString);
  251.       }
  252.       await docRef.update({
  253.         'points_history': FieldValue.arrayUnion(historyList)
  254.       });
  255.      
  256.     });
  257.   }
  258.  
  259.   Future<SpecialCategory> getSpecialCategories () async{
  260.     SpecialCategory specialCategory;
  261.     final DocumentReference ref = firestore.collection('settings').doc('special_categories');
  262.     DocumentSnapshot snapshot = await ref.get();
  263.     if(snapshot.exists){
  264.       specialCategory = SpecialCategory.fromFirestore(snapshot);
  265.     }else{
  266.       specialCategory = SpecialCategory(enabled: false, id1: null, id2: null);
  267.     }
  268.     return specialCategory;
  269.   }
  270.  
  271.   Future<Category> getCategory(String docId) async {
  272.     final DocumentSnapshot snap = await firestore.collection('categories').doc(docId).get();
  273.     Category category = Category.fromFirestore(snap);
  274.     return category;
  275.   }
  276.  
  277.   Future addToBookmark (String questionId) async{
  278.     const String fieldName = 'bookmarked_questions';
  279.     UserModel? userData = await getUserData();
  280.     List itemList = userData?.bookmarkedQuestions ?? [];
  281.     if(!itemList.contains(questionId)){
  282.       itemList.add(questionId);
  283.       await firestore.collection('users').doc(userData!.uid).update({
  284.         fieldName : FieldValue.arrayUnion(itemList)
  285.       });
  286.     }else{
  287.       debugPrint('Already available');
  288.     }
  289.   }
  290.  
  291.   Future removeFromBookmark (questionId) async{
  292.     final String userId = FirebaseAuth.instance.currentUser!.uid;
  293.     const String fieldName = 'bookmarked_questions';
  294.     await firestore.collection('users').doc(userId).update({
  295.         fieldName : FieldValue.arrayRemove([questionId])
  296.     }).catchError((e)=> debugPrint('error on deleting bookmarks'));
  297.   }
  298.  
  299.   Future<List> getBookmakedIds () async{
  300.     UserModel? userData = await getUserData();
  301.     List itemList = userData?.bookmarkedQuestions ?? [];
  302.     return itemList;
  303.    
  304.   }
  305.  
  306.   Future<List<Question>> getBookmakedQuestions () async{
  307.     List<Question> qList = [];
  308.     List ids = await getBookmakedIds();
  309.     if(ids.isNotEmpty){
  310.       qList = await getQuestionsforBookmark(ids);
  311.     }
  312.     return qList;  
  313.   }
  314.  
  315.   Future updateCompletedQuizzes (String quizId, UserModel user) async{
  316.     const String fieldName = 'completed_quizzes';
  317.     List itemList = user.completedQuizzes ?? [];
  318.     if(!itemList.contains(quizId)){
  319.       itemList.add(quizId);
  320.       await firestore.collection('users').doc(user.uid).update({
  321.         fieldName : FieldValue.arrayUnion(itemList)
  322.       });
  323.     }else{
  324.       debugPrint('Already available');
  325.     }
  326.   }
  327.  
  328.  
  329.  
  330.  
  331. }
  332.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement