challenges_utils.dart 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import 'package:cloud_firestore/cloud_firestore.dart';
  2. import 'dart:math';
  3. class ChallengesUtils {
  4. static Future<DocumentSnapshot<Map<String, dynamic>>> getChallenge() async {
  5. Future<DocumentSnapshot<Map<String, dynamic>>> challenge;
  6. if(await shouldGenerateChallenge()){
  7. challenge = generateChallenge();
  8. } else {
  9. final user = FirebaseFirestore.instance
  10. .collection('Users')
  11. .doc('tlmysIvwTBaoZKWqBofx');
  12. challenge = user.get().then((value) => value.get('weekly_place').get());
  13. }
  14. return challenge;
  15. }
  16. static Future<bool> shouldGenerateChallenge() async {
  17. final user = FirebaseFirestore.instance
  18. .collection('Users')
  19. .doc('tlmysIvwTBaoZKWqBofx');
  20. DateTime now = DateTime.now();
  21. int secondsSinceEpoch = now.millisecondsSinceEpoch ~/ 1000;
  22. bool shouldGenerate = await user.get().then((value) {
  23. final dif = secondsSinceEpoch - value.get('last_challenge_date').seconds;
  24. return dif / 3600 / 24 > 7;
  25. });
  26. return Future.value(shouldGenerate);
  27. }
  28. static Future<DocumentSnapshot<Map<String, dynamic>>> generateChallenge() {
  29. final user = FirebaseFirestore.instance
  30. .collection('Users')
  31. .doc('tlmysIvwTBaoZKWqBofx');
  32. return user.get().then((value) {
  33. double lat = 0.0144927536231884;
  34. double lon = 0.0181818181818182;
  35. double userLat = value.get('address').latitude;
  36. double userLon = value.get('address').longitude;
  37. double lowerLat = userLat - (lat * 5);
  38. double lowerLon = userLon - (lon * 5);
  39. double upperLat = userLat + (lat * 5);
  40. double upperLon = userLon + (lon * 5);
  41. GeoPoint lesserGeoPoint = GeoPoint(lowerLat, lowerLon);
  42. GeoPoint greaterGeoPoint = GeoPoint(upperLat, upperLon);
  43. return FirebaseFirestore.instance
  44. .collection('Places')
  45. .where('location', isGreaterThan: lesserGeoPoint)
  46. .where('location', isLessThan: greaterGeoPoint)
  47. .get()
  48. .then((snapshot) {
  49. int numOfPlaces = snapshot.docs.length;
  50. String id = snapshot.docs[Random().nextInt(numOfPlaces)].id;
  51. print('updating');
  52. user.update({
  53. 'weekly_place':
  54. FirebaseFirestore.instance.collection('Places').doc(id),
  55. 'last_challenge_date': Timestamp.now(),
  56. });
  57. return FirebaseFirestore.instance.collection('Places').doc(id).get();
  58. });
  59. });
  60. }
  61. }