-
Notifications
You must be signed in to change notification settings - Fork 26
/
Database.js
1959 lines (1675 loc) · 71.7 KB
/
Database.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @author Pim de Witte (pimdewitte.me/pimdewitte95@gmail.com). Copyright MSF UK 2016.
*
* Database is the main class for communicating with firebase and AsyncStorage.
*/
import React from "react";
import {Platform, Dimensions, NetInfo, AsyncStorage} from "react-native";
import firebase from "firebase";
var ConnectionManager = require('./ConnectionManager');
var AuthManager = require('./AuthManager');
let _ = require('underscore');
var CryptoJS = require("crypto-js");
var RNFS = require('react-native-fs');
const config = require("../../config.json");
console.log(RNFS.DocumentDirectoryPath);
firebase.initializeApp(config.firebaseConfig);
var PushNotification = require('react-native-push-notification');
PushNotification.configure({
// (optional) Called when Token is generated (iOS and Android)
onRegister: function (token) {
console.log('TOKEN:', token);
},
// (required) Called when a remote or local notification is opened or received
onNotification: function (notification) {
console.log('NOTIFICATION:', notification);
},
// ANDROID ONLY: (optional) GCM Sender ID.
senderID: config.senderID,
// IOS ONLY (optional): default: all - Permissions to register.
permissions: {
alert: true,
badge: true,
sound: true
},
// Should the initial notification be popped automatically
// default: true
popInitialNotification: false,
/**
* IOS ONLY: (optional) default: true
* - Specified if permissions will requested or not,
* - if not, you must call PushNotificationsHandler.requestPermissions() later
*/
requestPermissions: true,
});
var levels = {
1: {
badge: require('./views/badges/1.png'),
title: "Square One",
description: "You're off to a great start! As soon as you finish this tutorial, you'll be able to join real projects and start making a difference.",
expRequired: 1
},
2: {
badge: require('./views/badges/2.png'),
title: "Welcome to the team!",
description: "You can now call yourself a mapper. Be proud! As you move forward, your work will impact the lives of actual people. Isn't that great?",
expRequired: 3
},
3: {
badge: require('./views/badges/3.png'),
title: "Tilting the Scale",
description: "With every image you classify, you help weight the odds in favor of vulnerable communities.",
expRequired: 10
},
4: {
badge: require('./views/badges/4.png'),
title: "Another Rung on the Latitude",
description: "Hand over hand, foot over foot, and, uh, finger over finger, pace yourself and keep up the good work!",
expRequired: 50
},
5: {
badge: require('./views/badges/5.png'),
title: "Off the Charts",
description: "It's a great big world out there. Stick with your team and chart the uncharted!",
expRequired: 100
},
6: {
badge: require('./views/badges/6.png'),
title: "Making the Grade",
description: "Everytime the app pings the server, a mapper gets their wings. Okay, okay, not every time, but this time one did and it's you! Keep playing for more opportunities to impact lives, as well as shinier badges and nerdier map puns.",
expRequired: 250
},
7: {
badge: require('./views/badges/7.png'),
title: "Getting the GISt of It",
description: "It's the gist, and you got it!",
expRequired: 400
},
8: {
badge: require('./views/badges/8.png'),
title: "Bearing Forward",
description: "Always forward, never back! Just keep swiping, you've a knack!",
expRequired: 550
},
9: {
badge: require('./views/badges/9.png'),
title: "A Coordinated Effort",
description: "Thousands of little taps by users like you add up to pinpoint people in need. Thanks for making an effort!",
expRequired: 800
},
10: {
badge: require('./views/badges/10.png'),
title: "The Best Laid Planimetrics",
description: "Plans often go awry, but it's less likely with an accurate planimetric map!",
expRequired: 1100
},
11: {
badge: require('./views/badges/11.png'),
title: "With Sincere Graticule",
description: "In the words of Aesop, 'Graticule is a line from global poles.'",
expRequired: 1500
},
12: {
badge: require('./views/badges/12.png'),
title: "To the Highest Degree",
description: "Hmm... that's actually the North Pole, and there aren't many people to map up there! Nevertheless, we appreciate your enthusiasm - to the highest degree.",
expRequired: 2000
},
13: {
badge: require('./views/badges/13.png'),
title: "A Geodesy of Discovery",
description: "You are Geodesseus and your adventure is truly epic. You're battling the dragons that live off the edge of the map!",
expRequired: 2300
},
14: {
badge: require('./views/badges/14.png'),
title: "Good Homolosine, Homeslice!",
description: "Way to go, Waterman! Let's take it to the Dymaxion. You're really putting your Ekhert into this.",
expRequired: 3000
},
15: {
badge: require('./views/badges/15.png'),
title: "Gotta Catch 'Emollweide",
description: "My eyes will travel across the land... searching far and wiiiiide... each image tile, to understand... the feature that's inside! MAPSWIPE!",
expRequired: 4100
},
16: {
badge: require('./views/badges/16.png'),
title: "Mercators Gonna Mercate",
description: "It's the most popular projection in school, but don't let that distort your perception. If you need to compare areas areas far from the equator, you'd better keep on walking.",
expRequired: 5600
},
17: {
badge: require('./views/badges/17.png'),
title: "Quick as a Winkel",
description: "A tripel threat that can't sing, dance, or act? Luckily, you don't need to maintain a classy image to classify one quickly!",
expRequired: 7400
},
18: {
badge: require('./views/badges/18.png'),
title: "Tissot's Bag of Tricks",
description: "+5 Health, +15 Coordination, +10 Intelligence, -10 Charisma",
expRequired: 9200
},
19: {
badge: require('./views/badges/19.png'),
title: "In Hannu Light",
description: "Sometimes you just have to Punt your work. With MapSwipe, you can procrastinate productively.",
expRequired: 9700
},
20: {
badge: require('./views/badges/20.png'),
title: "It's All Well and Gudrid",
description: "Thanks for your dedicated use. Mappers like you keep MapSwipe from whithering on the Vineland.",
expRequired: 10600
},
21: {
badge: require('./views/badges/21.png'),
title: "Building Manco Capacity",
description: "MapSwipe users don't make ex-Cuscos, they make results!",
expRequired: 12000
},
22: {
badge: require('./views/badges/22.png'),
title: "A Bright Xu Fu-ture",
description: "It's no Penglai, you're making a difference pixel by pixelixer!",
expRequired: 13800
},
23: {
badge: require('./views/badges/23.png'),
title: "Footloose and Bungaree",
description: "I like to think I write koalaty puns, but I'm having some trouble making one out of Australia.",
expRequired: 16000
},
24: {
badge: require('./views/badges/24.png'),
title: "Stick to Jemison",
description: "Judging by how many tiles you've tapped now, you Mae really Carol about Jemison. Thanks for making space in your day to help out!",
expRequired: 18500
},
25: {
badge: require('./views/badges/25.png'),
title: "No Man is a Null Island",
description: "No woman either, for that matter. Be involved in mankind!",
expRequired: 19250
},
26: {
badge: require('./views/badges/26.png'),
title: "Just Tagging Along",
description: "The more the merrier, we say! Let's tag everything! k=you, and v=very generous with your time, thanks!",
expRequired: 21000
},
27: {
badge: require('./views/badges/27.png'),
title: "Plate Carreer Advancement",
description: "Everyone starts at the Bottomly of the corporate ladder. The Keyes is to choose a job you [Werner], and you'll never work a day in your life.",
expRequired: 23200
},
28: {
badge: require('./views/badges/28.png'),
title: "Kicking Over the Traces",
description: "Open source projects may buck tradition, and some can stirrup a lot of emotion, but don't let neigh-saying rein you in. You're whinnying in my book!",
expRequired: 26300
},
29: {
badge: require('./views/badges/29.png'),
title: "Totally JOSM",
description: "People say kids these days overuse JOSM. If everything is JOSM, they say, then nothing is JOSM. But we're going to say it anyway! We think you're totally JOSM!",
expRequired: 30300
},
30: {
badge: require('./views/badges/30.png'),
title: "Late Night Double Feature",
description: "Doctor X will map a feature, as will Brad and Janet. I believe Anne Francis will be attending the mapathon as well. I wanna go! Do you?",
expRequired: 34250
},
31: {
badge: require('./views/badges/31.png'),
title: "The Lay of the Landsat",
description: "You've laid your eyes on a lot of land and it's fair to say you are *quite* the expert in staring at the ground now!",
expRequired: 35000
},
32: {
badge: require('./views/badges/32.png'),
title: "Flying above the Radar",
description: "Like a falcon on the wing, or a lost helium balloon, you're cruising along and no one can bring you down now. Keep soaring!",
expRequired: 37000
},
33: {
badge: require('./views/badges/33.png'),
title: "A MetOp with Destiny",
description: "Was it something cosmic that brought you to MapSwipe? Were you chosen by fate to lend your hands to people in need? Those questions are completely beyond the scope of this app! However you got here, we're just glad you did.",
expRequired: 39800
},
34: {
badge: require('./views/badges/34.png'),
title: "Reach for the Navstars",
description: "You have checked an astronomical number of tiles. Congratulations on this stellar accomplishment!",
expRequired: 43500
},
35: {
badge: require('./views/badges/35.png'),
title: "LEO, King of the Jungle",
description: "The lion is the king of the jungle, and you are the king of this hill of badges. Really, it's more of a mountain now. You are so close to the top, don't stop!",
expRequired: 48000
},
36: {
badge: require('./views/badges/36.png'),
title: "SSO... ISS this it?",
description: "You've reached the end of the first batch of badges, and you've made a truly impressive contribution to this project. We are so grateful! But the answer is... no! There's more to map, and we'd love your help.",
expRequired: 52700
}
}
var database = firebase.database();
const INTERVALS = {}
const projectsRef = database.ref("projects");
const groupsRef = database.ref("groups");
const resultsRef = database.ref("results");
var myUserRef;
const announcementRef = database.ref("announcement");
var store = require('react-native-simple-store');
var con = new ConnectionManager();
var auth = new AuthManager(firebase);
auth.addListeners();
module.exports = {
/**
* Variable to access internal functions through promises.
*/
dbParent: this,
/**
* Stores all the tasks that still need pushing to the database
*/
taskResults: [],
groupCompletes: [],
/**
* Returns the connection manager
* @returns {ConnectionManager|exports|module.exports}
*/
getConnectionManager() {
return con;
},
/**
* Returns the auth manager
* @returns {AuthManager|exports|module.exports}
*/
getAuth() {
return auth;
},
/**
* Syncs all the objects in memory with the remote database and returns any unreported objects for later re-sync
* @returns {Promise}
*
* Reject triggers an error popup, resolve triggers a success
*/
syncAndDeIndex: function () {
var parent = this;
return new Promise(function (resolve, reject) {
// syncAndStatus always attempts to report ALL objects. Therefore, we only have to listen for the errors to re-pupulate the stores.
parent.syncAndStatus().then(results => {
console.log("i can haz results");
var errorCount = results.task.error.length;
var successCount = results.task.success.length;
parent.updateContributions(successCount);
store
.save('taskResults', {
// initialize the
tasks: results.task.error
}).then(status => {
store
.save('groupCompletes', {
// initialize the
groups: results.group.error
}).then(status => {
if (errorCount > successCount) {
// more errors than successes... nope
reject({
errorCount: errorCount,
successCount: successCount
});
} else {
resolve({
errorCount: errorCount,
successCount: successCount
});
}
})
})
});
});
},
/**
* Syncs and returns the status to syncAndDeIndex
* @returns {Promise}
*/
syncAndStatus: function () {
return new Promise(function (resolve, reject) {
var completeCount = 0;
var resolveTypes = {
task: {
success: [],
error: []
},
group: {
success: [],
error: []
}
}
/**
* Resolver function that resolves when all async actions have reported back their result (either success or error). The response will be resolved.
* @param status
* @param obj
*/
var checkResolve = function (status, type, obj) {
resolveTypes[type][status].push(obj);
completeCount--;
console.log("count: " + completeCount);
if (completeCount == 0) {
console.log("All data points reported. Resolving promise");
resolve(resolveTypes);
}
}
if (con.isOnline()) {
// get the current task results in memory that have not been synced yet
store.get('taskResults').then(result => {
if (result !== null) {
for (var i = 0; i < result.tasks.length; i++) {
var task = result.tasks[i];
if (task.device !== undefined) {
console.log("Attempting to sync task " + task.id);
var taskRef = database.ref("results/" + task.id);
// increase the amount of actions that need to happen for completion
completeCount++;
(function (task) { // capturing the group in a closure so that the callbacks use the right task variable
taskRef.child(auth.getUser().uid).set({
data: task
}).then(function (data) {
checkResolve('success', 'task', task);
}).catch(data => {
checkResolve('error', 'task', task);
});
})(task);
}
}
}
});
// sync the group complete count with firebase (The completed count is used to sort groups so that they can always be returned properly)
store.get('groupCompletes').then(result => {
if (result !== null) {
console.log("completes:");
for (var i = 0; i < result.groups.length; i++) {
var group = result.groups[i];
if (group.groupId !== undefined) {
completeCount += 1; // need 2 callbacks form groups, 1 for local sync, 1 for remote
console.log("Attempting to sync group " + group.groupId + " in project" + group.projectId);
var groupRef = groupsRef.child(group.projectId + "").child(group.groupId);
(function (group) { // capturing the group in a closure
groupRef.transaction(function (group) {
if (group) {
group.completedCount = group.completedCount + 1;
}
return group;
}).then(function (data) {
return checkResolve('success', 'group', group);
}).catch(function (error) {
checkResolve('error', 'group', group);
});
})(group);
}
}
}
});
} else {
console.log("We're offline, not reporting rn");
resolve(resolveTypes);
}
});
},
tasksReady: {},
taskLoop: null,
/**
* Delete a task to process from memory
* @param id
*/
deleteTask: function (id) {
console.log("deleting" + id);
delete this.tasksReady[id];
},
/**
* Adds a task (aka tile) that is ready for processing to the queue.
* Also, if new tasks are added while others are being processed, this is handled with the fact that it only removes objects from the array that were reported.
* @param task
*/
taskReadyForProcessing: function (task) {
var parent = this;
if (this.taskLoop === null) {
this.taskLoop = setInterval(function () {
console.log("processing tasks...");
//console.log(parent.tasksReady);
parent.processTasks(Object.keys(parent.tasksReady)).then(data => {
console.log("Processed tasks")
console.log(data);
data.forEach(function (task) {
delete parent.deleteTask(task);
});
}).catch(error => {
console.log("Task wasn't set ready for processing! Big alert!");
})
}, 5000);
}
this.tasksReady[task.id] = task;
},
/**
* Adds a task result that needs to be sent to firebase when a network is available
* @returns {Promise}
*
* Example task object: {id:"18-122222x-1222y", result: 1, device: deviceId}
*
*/
processTasks: function (tasks) {
var parent = this;
var tasksToProcess = tasks;
var taskArray = [];
tasksToProcess.forEach(function (task) {
taskArray.push(parent.tasksReady[task]);
});
return new Promise(function (resolve, reject) {
if (parent.taskQueryBusy === true) {
reject();
return;
}
parent.taskQueryBusy = true;
store.get('taskResults').then(result => {
if (result !== null && result !== undefined) {
taskArray.forEach(function (task) {
// check if it already contains a task with the current id
// if so, overwrite that task
//otherwise, push a new task
if (task.result === 0) {
// find the
}
var taskFound = false;
var toDelete = -1;
for (var i = 0; i < result.tasks.length; i++) {
if (result.tasks[i].id === task.id) {
if (task.result === 0) {
toDelete = i;
}
console.log(task);
result.tasks[i] = task;
taskFound = true;
}
}
if (toDelete !== -1) {
result.tasks.splice(toDelete, 1);
}
if (taskFound === false) {
console.log("pushing task to cache:" + task.id);
result.tasks.push(task);
}
});
store
.save('taskResults', {
// initialize the
tasks: result.tasks
}).then(status => {
// we've now stored the object and referenced it in the project
parent.taskQueryBusy = false;
resolve(tasksToProcess);
parent.taskQueryBusy = false;
})
} else {
// if the project store is not yet found, find it.
store
.save('taskResults', {
// initialize the
tasks: tasksToProcess
}).then(status => {
// we've now stored the object and referenced it in the project
parent.taskQueryBusy = false;
resolve(tasksToProcess); // simple, we resolved all of them.
})
.catch(error => {
parent.taskQueryBusy = false;
console.log("Couldn't store task");
});
}
});
});
},
/**
* These functions determine whether there is a level up that needs to be popped up.
*/
pendingLvlUp: -1,
getPendingLevelUp() {
return this.pendingLvlUp
},
setPendingLevelUp(val){
this.pendingLvlUp = val;
},
/**
* Updates the mapped distance of the user locally and in firebase
* @param addedDistance
*/
updateMappedDistance(addedDistance) {
var startedDistance = this.distance;
var parent = this;
console.log("updating mapped distance by:" + addedDistance);
store.get('currentUser').then(result => {
var currentDistance = -1;
var newDistance = -1;
if (result !== null && result !== undefined && result.distance !== undefined) {
currentDistance = result.distance;
newDistance = currentDistance + addedDistance;
console.log("checking lvl up");
if (parent.getLevelForExp(newDistance) > parent.getLevelForExp(currentDistance)) {
parent.pendingLvlUp = parent.getLevelForExp(newDistance);
}
store.update('currentUser', {
distance: newDistance
}).then(data => {
parent.refreshDistance();
});
// add the added distance in firebase (never override with local value bc it might reset)
if (con.isOnline()) {
myUserRef.transaction(function (user) {
if (user) {
user.distance = user.distance + addedDistance;
}
return user;
})
}
}
});
},
// the max level in the app
maxLevel: 36,
/**
* Returns the current level of the user
* @returns {*}
*/
getLevel() {
return this.getLevelForExp(this.distance);
},
/**
* Returns the entire level object, mainly for showing the badge
* @returns {*}
*/
getLevelObject() {
return levels[this.getLevel()];
},
/**
* Get a custom level object based on level (shown for level ups)
* @param customLevel
* @returns {*}
*/
getCustomLevelObject(customLevel) {
return levels[customLevel];
},
/**
* Get the tiles until the next level (divide by 6 for swipes)
* @returns {number}
*/
getTilesUntilNextLevel() {
var level = this.getLevel();
var checkAgainst = level + 1 > this.maxLevel ? this.maxLevel : level + 1;
return Math.ceil(((levels[checkAgainst].expRequired - levels[level].expRequired) / this.getSquareKilometersForZoomLevelPerTile(18)) / 6);
},
/**
* Get the level for the exp
* @param exp
* @returns {number}
*/
getLevelForExp(exp) {
try {
var toReturn = 1;
var parent = this;
Object.keys(levels).forEach(level => {
if (exp > levels[parent.maxLevel]) {
toReturn = parent.maxLevel
} else if (exp > levels[level].expRequired && exp < levels[parseInt(level) + 1].expRequired) {
toReturn = level;
}
});
if (toReturn > this.maxLevel) {
toReturn = this.maxLevel;
} else if (toReturn < 1) {
toReturn = 1;
}
} catch (err) {
console.log(err);
}
return toReturn;
},
/**
* Get the exp needed for a level
* @param lvl
* @returns {*}
*/
getExpForLevel(lvl) {
return levels[lvl].expRequired;
},
/**
* Get the percentage until the next level
* @returns {number}
*/
getToNextLevelPercentage() {
if (level == this.maxLevel) {
return 1;
}
var level = parseInt(this.getLevel());
var checkAgainst = level + 1;
var currentLevelExp = levels[level].expRequired;
var nextLevelExp = this.getExpForLevel(checkAgainst)
var myExp = this.distance;
var expToGainTotal = (nextLevelExp - currentLevelExp);
var expToGainForMe = (nextLevelExp - myExp)
var toReturn = 1 - (expToGainForMe / expToGainTotal);
return toReturn;
},
/**
* Get the amount of kilometers until the next level
* @returns {number}
*/
getKmTilNextLevel() {
if (level == this.maxLevel) {
return 1;
}
var level = parseInt(this.getLevel());
var checkAgainst = level + 1;
var currentLevelExp = levels[level].expRequired;
var nextLevelExp = this.getExpForLevel(checkAgainst);
var myExp = this.distance;
var expToGainTotal = (nextLevelExp - currentLevelExp);
var expToGainForMe = (nextLevelExp - myExp)
return expToGainForMe;
},
/**
* Calculate how much 1 tile is in square kilometers
* @param zoomLevel
* @returns {number}
*/
getSquareKilometersForZoomLevelPerTile(zoomLevel) {
if (zoomLevel === 23) {
return 2.29172838e-5;
} else if (zoomLevel === 22) {
return 9.11795814e-5;
} else if (zoomLevel == 21) {
return 0.000364718326;
} else if (zoomLevel == 20) {
return 0.00146082955;
} else if (zoomLevel == 19) {
return 0.00584331821;
} else if (zoomLevel == 18) {
return 0.0233732728;//(((0.5972 * 256) ^ 2) / (1000 ^ 2))
} else if (zoomLevel == 17) {
return 0.0934774368;
} else if (zoomLevel == 16) {
return 0.373941056;
} else if (zoomLevel == 15) {
return 1.4957016;
} else if (zoomLevel == 14) {
return 5.98280642;
} else if (zoomLevel == 13) {
return 23.9314761;
} else if (zoomLevel == 12) {
return 95.7254037;
}
},
/**
* Updates the contributions of the user
*/
updateContributions(addedContributions) {
var parent = this;
store.get('currentUser').then(result => {
var currentContributions = -1;
var newContributions = -1;
if (result !== null && result !== undefined && result.contributions !== undefined) {
currentContributions = result.contributions;
newContributions = currentContributions + addedContributions;
store.update('currentUser', {
contributions: newContributions
}).then(data => {
parent.refreshContributions();
});
// add the added contributions in firebase (never override with local value bc it might reset)
if (con.isOnline()) {
myUserRef.transaction(function (user) {
if (user) {
user.contributions = user.contributions + addedContributions;
}
return user;
})
}
}
});
},
/**
* Returns the firebase timestamp
* @returns {rf.TIMESTAMP|{[.sv]}|sf.TIMESTAMP}
*/
getTimestamp() {
return firebase.database.ServerValue.TIMESTAMP;
},
/**
* Adds a group complete to your local storage to later by synced
* @returns {Promise}
*/
addGroupComplete: function (project, group) {
var parent = this;
/**
* Add the distance of this map to your current level
*/
var projKey = 'project-' + project + "-group-" + group;
// this.addToIgnoreList(projKey);
store.get(projKey).then(result => {
if (result !== null && result !== undefined && result.group !== undefined) {
var distancePerTile = parent.getSquareKilometersForZoomLevelPerTile(result.group.zoomLevel);
console.log("Distance per tile was:" + distancePerTile);
console.log("group count was:" + result.group.count);
this.updateMappedDistance(Math.ceil(result.group.count * distancePerTile));
}
});
return new Promise(function (resolve, reject) {
var obj = {
groupId: group,
projectId: project
};
// remove the group from the cache
// add the group to the group completes object
store.get('groupCompletes').then(result => {
if (result !== null && result !== undefined) {
result.groups.push(obj);
store
.save('groupCompletes', {
// initialize the
groups: result.groups
}).then(status => {
// we've now stored the object and referenced it in the project
console.log("Storing groups");
console.log(obj);
parent.removeGroup(project, group).then(data => {
resolve();
var key = 'project-' + project + "-group-" + group;
parent.removeOfflineGroup(key);
});
})
} else {
// if the project store is not yet found, find it.
store
.save('groupCompletes', {
// initialize the
groups: [obj]
}).then(status => {
// we've now stored the object and referenced it in the project
console.log("Storing complete group");
console.log(obj);
parent.removeGroup(project, group).then(data => {
resolve();
});
})
.catch(error => {
console.log("Couldn't store group complete");
});
}
})
});
},
distance: -1,
/**
* After the user has his/her session, this will get the latest mapping data. If the local distance is greater, it'll update firebase and ues the local one
* If offline, it'll also use the local one
* If on firebase is larger, it'll use firebase's and turn yours to that one
*/
refreshDistance() {
var parent = this;
store.get("currentUser").then(data => {
if (data !== null && data !== undefined && data.distance !== undefined) {
// we have a valid local distance store
parent.distance = data.distance;
}
});
},
contributions: -1,
/**
* After the user has his/her session, this will get the latest mapping data. If the local contributions is greater, it'll update firebase and ues the local one
* If offline, it'll also use the local one
* If on firebase is larger, it'll use firebase's and turn yours to that one
*/
refreshContributions() {
var parent = this;
store.get("currentUser").then(data => {
if (data !== null && data !== undefined && data.contributions !== undefined) {
// we have a valid local distance store
parent.contributions = data.contributions;
}
});
},
/**
* Log out
*/
logOut() {
store.update('currentUser', {
distance: 0,
contributions: 0,
username: "",
}).then(data => {
auth.logOut();
});
},
getDistance() {
return this.distance
},
getContributions() {
return this.contributions
},
/**
* Gets the remote user object and compares it to the local one, updates any outdated values in both
* @param remoteObj
*/
compareAndUpdate() {
myUserRef = database.ref("/users/" + auth.getUser().uid);