Forráskód Böngészése

Merge branch 'push-notifications' of iwa-13/PhysiGo into main

Leo Sale 3 éve
szülő
commit
dd68773075

+ 5 - 2
app/lib/Services/AuthService.dart

@@ -2,18 +2,21 @@ import 'package:cloud_firestore/cloud_firestore.dart';
 import 'package:firebase_auth/firebase_auth.dart';
 import 'package:physigo/Services/DatabaseManager.dart';
 import 'package:physigo/Services/logged_in_user.dart';
+import 'package:location/location.dart';
 
 class AuthenticationServices {
   static final FirebaseAuth _auth = FirebaseAuth.instance;
   static LoggedInUser? user;
 
   //Register a user
-  static Future createNewUser(String address, bool anonymous, String birth, String name, String email, String password,
+  static Future createNewUser(bool anonymous, String birth, String name, String email, String password,
       String phone, String sharedID, String surname) async {
     try {
       UserCredential result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
       User? user = result.user;
-      await DatabaseManager("total_points").createUserData(address, anonymous, birth, DateTime.now(), DateTime.now(),
+      LocationData userLocation = await Location.instance.getLocation();
+      GeoPoint userGeoPoint = GeoPoint(userLocation.latitude!, userLocation.longitude!);
+      await DatabaseManager("total_points").createUserData(userGeoPoint, anonymous, birth, DateTime.now(), DateTime.utc(1970, 1, 1),
           email, name, phone, sharedID, surname, 0, DateTime.now(), 'null', user!.uid);
 
       return user;

+ 1 - 1
app/lib/Services/DatabaseManager.dart

@@ -10,7 +10,7 @@ class DatabaseManager {
 
   DatabaseManager(this.points);
 
-  Future<void> createUserData(String address,
+  Future<void> createUserData(GeoPoint address,
       bool anonymous,
       String birth_date,
       DateTime create_date,

+ 11 - 3
app/lib/Services/logged_in_user.dart

@@ -1,14 +1,20 @@
+import 'package:cloud_firestore/cloud_firestore.dart';
+
 class LoggedInUser {
   final String name;
   final num totalPoints;
-  final dynamic weeklyPlace;
+  dynamic weeklyPlace;
   final String sharedId;
+  final Timestamp lastChallengeDate;
+  final GeoPoint address;
 
-  const LoggedInUser({
+  LoggedInUser({
     required this.name,
     required this.totalPoints,
     required this.weeklyPlace,
     required this.sharedId,
+    required this.lastChallengeDate,
+    required this.address,
   });
 
   factory LoggedInUser.fromMap(Map<String, dynamic> map) {
@@ -16,7 +22,9 @@ class LoggedInUser {
       name: map["name"],
       totalPoints: map["total_points"],
       weeklyPlace: map["weekly_place"],
-      sharedId: map["shared_id"]
+      sharedId: map["shared_id"],
+      lastChallengeDate: map["last_challenge_date"],
+      address: map["address"],
     );
   }
 }

+ 2 - 12
app/lib/SignupPage.dart

@@ -7,7 +7,6 @@ TextEditingController _name = TextEditingController();
 TextEditingController _surname = TextEditingController();
 TextEditingController _mail = TextEditingController();
 TextEditingController _phoneNumber = TextEditingController();
-TextEditingController _address = TextEditingController();
 TextEditingController _username = TextEditingController();
 TextEditingController _passwd = TextEditingController();
 TextEditingController _passwd2 = TextEditingController();
@@ -198,13 +197,6 @@ class _SignupForm2 extends State<SignupForm2> {
             ),
           ),
           const SizedBox(height: 10),
-          TextFormField(
-            controller: _address,
-            decoration: InputDecoration(
-              hintText: 'Home Adress..',
-            ),
-          ),
-          const SizedBox(height: 10),
           Row(children: <Widget>[
             Text('Anonymous'),
             Checkbox(
@@ -304,7 +296,7 @@ class _SignupForm3 extends State<SignupForm3> {
 
   void createUser() async {
     dynamic result =
-        await AuthenticationServices.createNewUser(_address.text, anonymous, _dateString.toString(), _name.text, _mail.text, _passwd.text,
+        await AuthenticationServices.createNewUser(anonymous, _dateString.toString(), _name.text, _mail.text, _passwd.text,
             _phoneNumber.text, _username.text, _surname.text);
     if (result == null) {
       print('mail not valid');
@@ -312,8 +304,7 @@ class _SignupForm3 extends State<SignupForm3> {
       //print(result.toString());
       //[51.787378° N, 19.449455° E]
 
-      print('*****  address: ' + _address.text +
-          ' anonymous: ' + anonymous.toString() +
+      print(' anonymous: ' + anonymous.toString() +
           ' birthdate: ' + _dateString.toString() +
           ' createDate: ' + DateTime.now().toString()+
           ' last_challenge_data: ' + 'null'+
@@ -331,7 +322,6 @@ class _SignupForm3 extends State<SignupForm3> {
       _surname.clear();
       _mail.clear();
       _phoneNumber.clear();
-      _address.clear();
       _username.clear();
       _passwd.clear();
       _passwd2.clear();

+ 17 - 21
app/lib/challenges/challenges_utils.dart

@@ -1,50 +1,46 @@
 import 'package:cloud_firestore/cloud_firestore.dart';
+import 'package:firebase_auth/firebase_auth.dart';
 import 'package:geoflutterfire/geoflutterfire.dart';
 import 'dart:math';
 
+import '../Services/AuthService.dart';
+import '../Services/logged_in_user.dart';
+
 class ChallengesUtils {
   static final geo = Geoflutterfire();
   static final _firestore = FirebaseFirestore.instance;
 
-  static Future<DocumentSnapshot<Map<String, dynamic>>> getChallenge() async {
-    Future<DocumentSnapshot<Map<String, dynamic>>> challenge;
+  static generateChallengeIfNeeded() async {
     if (await shouldGenerateChallenge()) {
-      challenge = generateChallenge();
-    } else {
-      final user = _firestore.collection('Users').doc('tlmysIvwTBaoZKWqBofx');
-      challenge = user.get().then((value) => value.get('weekly_place').get());
+      generateChallenge();
     }
-    return challenge;
   }
 
   static Future<bool> shouldGenerateChallenge() async {
-    final user = _firestore.collection('Users').doc('tlmysIvwTBaoZKWqBofx');
+    LoggedInUser? user = await AuthenticationServices.getCurrentUser();
     DateTime now = DateTime.now();
     DateTime today = DateTime(now.year, now.month, now.day);
     DateTime lastMonday = today.subtract(Duration(days: today.weekday - 1));
     int secondsSinceEpoch = lastMonday.millisecondsSinceEpoch ~/ 1000;
-    bool shouldGenerate = await user.get().then((value) {
-      final dif = secondsSinceEpoch - value.get('last_challenge_date').seconds;
-      return dif / 3600 / 24 > 7;
-    });
-    return Future.value(shouldGenerate);
+    final dif = secondsSinceEpoch - user!.lastChallengeDate.seconds;
+    return Future.value(dif / 3600 / 24 > 7);
   }
 
-  static Future<DocumentSnapshot<Map<String, dynamic>>> generateChallenge() async {
-    final user = await _firestore.collection('Users').doc('tlmysIvwTBaoZKWqBofx').get();
+  static void generateChallenge() async {
+    LoggedInUser? user = await AuthenticationServices.getCurrentUser();
     Query<Map<String, dynamic>> places = _firestore.collection('Places');
-    double innerRadius = 3;
-    double outerRadius = 5;
+    double innerRadius = 1;
+    double outerRadius = 2.5;
     String randomPlaceID = '';
 
     Stream<List<DocumentSnapshot>> possiblePlaces = geo.collection(collectionRef: places).within(
-        center: geo.point(latitude: user.get('address').latitude, longitude: user.get('address').longitude),
+        center: geo.point(latitude: user!.address.latitude, longitude: user.address.longitude),
         radius: outerRadius,
         field: 'location',
         strictMode: true);
 
     Stream<List<DocumentSnapshot>> placesTooClose = geo.collection(collectionRef: places).within(
-        center: geo.point(latitude: user.get('address').latitude, longitude: user.get('address').longitude),
+        center: geo.point(latitude: user.address.latitude, longitude: user.address.longitude),
         radius: innerRadius,
         field: 'location',
         strictMode: true);
@@ -58,10 +54,10 @@ class ChallengesUtils {
     possiblePlacesList.retainWhere((element) => !ids.contains(element.id));
     int numOfPlaces = possiblePlacesList.length;
     randomPlaceID = possiblePlacesList[Random().nextInt(numOfPlaces)].id;
-    _firestore.collection('Users').doc('tlmysIvwTBaoZKWqBofx').update({
+    AuthenticationServices.user!.weeklyPlace = _firestore.collection('Places').doc(randomPlaceID);
+    _firestore.collection("profileInfo").doc(FirebaseAuth.instance.currentUser?.uid).update({
       'weekly_place': _firestore.collection('Places').doc(randomPlaceID),
       'last_challenge_date': Timestamp.now(),
     });
-    return _firestore.collection('Places').doc(randomPlaceID).get();
   }
 }

+ 3 - 0
app/lib/home/home_page.dart

@@ -3,6 +3,8 @@ import 'package:physigo/Services/AuthService.dart';
 import 'package:physigo/challenge/daily_challenge_page.dart';
 import 'package:physigo/challenge/weekly_challenge_page.dart';
 
+import '../challenges/challenges_utils.dart';
+
 class HomePage extends StatelessWidget {
   const HomePage({Key? key}) : super(key: key);
 
@@ -11,6 +13,7 @@ class HomePage extends StatelessWidget {
 
   @override
   Widget build(BuildContext context) {
+    ChallengesUtils.generateChallengeIfNeeded();
     return Padding(
       padding: const EdgeInsets.all(16.0),
       child: Column(

+ 0 - 2
app/lib/main.dart

@@ -7,7 +7,6 @@ import 'firebase_options.dart';
 import 'push_notifications_initializer.dart';
 import 'package:physigo/logIn.dart';
 import 'package:physigo/profilePage.dart';
-import 'package:physigo/ranking/ranking_page.dart';
 import 'package:physigo/SignupPage.dart';
 import 'package:physigo/menu/main_page.dart';
 import 'package:physigo/welcomeScreen.dart';
@@ -18,7 +17,6 @@ void main() async {
     options: DefaultFirebaseOptions.currentPlatform,
   );
   handleMessages();
-
   runApp(const PhysiGo());
 }
 

+ 21 - 0
app/pubspec.lock

@@ -303,6 +303,27 @@ packages:
       url: "https://pub.dartlang.org"
     source: hosted
     version: "1.0.1"
+  location:
+    dependency: "direct main"
+    description:
+      name: location
+      url: "https://pub.dartlang.org"
+    source: hosted
+    version: "4.4.0"
+  location_platform_interface:
+    dependency: transitive
+    description:
+      name: location_platform_interface
+      url: "https://pub.dartlang.org"
+    source: hosted
+    version: "2.3.0"
+  location_web:
+    dependency: transitive
+    description:
+      name: location_web
+      url: "https://pub.dartlang.org"
+    source: hosted
+    version: "3.1.1"
   matcher:
     dependency: transitive
     description:

+ 1 - 0
app/pubspec.yaml

@@ -50,6 +50,7 @@ dependencies:
   geolocator: ^8.2.1
   provider: ^6.0.1
   geoflutterfire: ^3.0.3
+  location: ^4.0.0
 
 dev_dependencies:
   flutter_test:

+ 60 - 0
serverless_functions/api/generate-challenge.ts

@@ -0,0 +1,60 @@
+import {VercelRequest, VercelResponse} from '@vercel/node';
+import {initializeApp, cert} from 'firebase-admin/app';
+import {getFirestore} from 'firebase-admin/firestore';
+import {firestore} from "firebase-admin";
+import Timestamp = firestore.Timestamp;
+
+
+export default async function generateChallenge(req: VercelRequest, res: VercelResponse) {
+    const type = req.query.type;
+    const serviceAccountStringified = Buffer.from(process.env.FIREBASE_SERVICE_ACCOUNT!, 'base64').toString('ascii');
+    const serviceAccount = JSON.parse(serviceAccountStringified);
+    initializeApp({
+        credential: cert(serviceAccount)
+    });
+
+    const firestore = getFirestore();
+    const challengeRef = type === 'daily' ? firestore.collection('DailyChallenges') :
+        firestore.collection('WeeklyChallenges');
+
+    if (type === 'daily') {
+        // @ts-ignore
+        const yesterday = new Date(new Date() - 1000 * 3600 * 22);
+
+        const todayChallenge = await challengeRef.where('date', '>', yesterday).get();
+
+        if (!todayChallenge.empty) {
+            res.json({
+                message: `challenge for ${new Date()} is already generated`,
+            })
+        }
+    } else if (type === 'weekly') {
+        // @ts-ignore
+        const weekAgo = new Date(new Date() - 1000 * 3600 * 24 * 7 - 3600);
+
+        const thisWeekChallenge = await challengeRef.where('date', '>', weekAgo).get();
+
+        if (!thisWeekChallenge.empty) {
+            res.json({
+                message: 'challenge for this week already exists',
+                date: new Date(),
+            });
+        }
+    }
+
+    const exercisesSnapshot = await firestore.collection('Exercises').get();
+    const exercises: FirebaseFirestore.DocumentData[] = [];
+    exercisesSnapshot.forEach((exercise) => {
+        exercises.push(firestore.collection('Exercises').doc(exercise.id));
+    });
+    const shuffled = exercises.sort(() => 0.5 - Math.random());
+    const selected = shuffled.slice(0, 3);
+    const bonus = exercises[Math.floor(Math.random() * exercises.length)];
+
+    const firestoreRes = await challengeRef.add({
+        date: Timestamp.fromDate(new Date()),
+        list_exercises: selected,
+        bonus_exercise: bonus,
+    });
+    res.json(firestoreRes);
+}

A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 2435 - 1
serverless_functions/package-lock.json


Nem az összes módosított fájl került megjelenítésre, mert túl sok fájl változott