forked from monkeytypegame/monkeytype
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.js
More file actions
553 lines (517 loc) · 13.2 KB
/
db.js
File metadata and controls
553 lines (517 loc) · 13.2 KB
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
import { loadTags } from "./result-filters";
import * as AccountButton from "./account-button";
import * as Notifications from "./notifications";
import axiosInstance from "./axios-instance";
import * as TodayTracker from "./today-tracker";
let dbSnapshot = null;
export function updateName(uid, name) {
//TODO update
axiosInstance.post("/updateName", {
name: name,
});
}
export function getSnapshot() {
return dbSnapshot;
}
export function setSnapshot(newSnapshot) {
try {
delete newSnapshot.banned;
} catch {}
try {
delete newSnapshot.verified;
} catch {}
dbSnapshot = newSnapshot;
}
export async function initSnapshot() {
//send api request with token that returns tags, presets, and data needed for snap
let defaultSnap = {
results: undefined,
personalBests: {},
name: undefined,
presets: [],
tags: [],
favouriteThemes: [],
banned: undefined,
verified: undefined,
emailVerified: undefined,
lbMemory: {
time15: {
global: null,
daily: null,
},
time60: {
global: null,
daily: null,
},
},
globalStats: {
time: 0,
started: 0,
completed: 0,
},
};
let snap = defaultSnap;
try {
if (firebase.auth().currentUser == null) return false;
let userData = await axiosInstance.get("/user");
userData = userData.data;
snap.name = userData.name;
snap.personalBests = userData.personalBests;
snap.banned = userData.banned;
snap.verified = userData.verified;
snap.discordId = userData.discordId;
snap.globalStats = {
time: userData.timeTyping,
started: userData.startedTests,
completed: userData.completedTests,
};
snap.favouriteThemes =
userData.favouriteThemes === undefined ? [] : userData.favouriteThemes;
try {
if (userData.lbMemory.time15 !== undefined) {
snap.lbMemory.time15 = userData.lbMemory.time15;
}
if (userData.lbMemory.time60 !== undefined) {
snap.lbMemory.time60 = userData.lbMemory.time60;
}
} catch {}
let configData = await axiosInstance.get("/config");
configData = configData.data;
if (configData) {
snap.config = configData.config;
}
let tagsData = await axiosInstance.get("/user/tags");
snap.tags = tagsData.data;
snap.tags = snap.tags.sort((a, b) => {
if (a.name > b.name) {
return 1;
} else if (a.name < b.name) {
return -1;
} else {
return 0;
}
});
let presetsData = await axiosInstance.get("/presets");
snap.presets = presetsData.data;
snap.presets = snap.presets.sort((a, b) => {
if (a.name > b.name) {
return 1;
} else if (a.name < b.name) {
return -1;
} else {
return 0;
}
});
dbSnapshot = snap;
loadTags(dbSnapshot.tags);
return dbSnapshot;
} catch (e) {
dbSnapshot = defaultSnap;
throw e;
}
}
export async function getUserResults() {
let user = firebase.auth().currentUser;
if (user == null) return false;
if (dbSnapshot === null) return false;
if (dbSnapshot.results !== undefined) {
return true;
} else {
try {
let results = await axiosInstance.get("/results");
results.data.forEach((result) => {
if (result.bailedOut === undefined) result.bailedOut = false;
if (result.blindMode === undefined) result.blindMode = false;
if (result.difficulty === undefined) result.difficulty = "normal";
if (result.funbox === undefined) result.funbox = "none";
if (result.language === undefined) result.language = "english";
if (result.numbers === undefined) result.numbers = false;
if (result.punctuation === undefined) result.punctuation = false;
});
results.data = results.data.sort((a, b) => {
return a.timestamp < b.timestamp;
});
dbSnapshot.results = results.data;
await TodayTracker.addAllFromToday();
return true;
} catch (e) {
Notifications.add("Error getting results", -1);
return false;
}
}
/*
try {
return await db
.collection(`users/${user.uid}/results/`)
.orderBy("timestamp", "desc")
.limit(1000)
.get()
.then(async (data) => {
dbSnapshot.results = [];
data.docs.forEach((doc) => {
let result = doc.data();
result.id = doc.id;
//this should be done server-side
if (result.bailedOut === undefined) result.bailedOut = false;
if (result.blindMode === undefined) result.blindMode = false;
if (result.difficulty === undefined) result.difficulty = "normal";
if (result.funbox === undefined) result.funbox = "none";
if (result.language === undefined) result.language = "english";
if (result.numbers === undefined) result.numbers = false;
if (result.punctuation === undefined) result.punctuation = false;
dbSnapshot.results.push(result);
});
await TodayTracker.addAllFromToday();
return true;
})
.catch((e) => {
throw e;
});
} catch (e) {
console.error(e);
return false;
}
}
*/
}
export async function getUserHighestWpm(
mode,
mode2,
punctuation,
language,
difficulty
) {
function cont() {
let topWpm = 0;
dbSnapshot.results.forEach((result) => {
if (
result.mode == mode &&
result.mode2 == mode2 &&
result.punctuation == punctuation &&
result.language == language &&
result.difficulty == difficulty
) {
if (result.wpm > topWpm) {
topWpm = result.wpm;
}
}
});
return topWpm;
}
let retval;
if (dbSnapshot == null || dbSnapshot.results === undefined) {
retval = 0;
} else {
retval = cont();
}
return retval;
}
export async function getUserAverageWpm10(
mode,
mode2,
punctuation,
language,
difficulty
) {
function cont() {
let wpmSum = 0;
let count = 0;
let last10Wpm = 0;
let last10Count = 0;
// You have to use every so you can break out of the loop
dbSnapshot.results.every((result) => {
if (
result.mode == mode &&
result.punctuation == punctuation &&
result.language == language &&
result.difficulty == difficulty
) {
// Continue if the mode2 doesn't match unless it's a quote.
if (result.mode2 != mode2 && mode != "quote") {
return true;
}
// Grab the most recent 10 wpm's for the current mode.
if (last10Count < 10) {
last10Wpm += result.wpm;
last10Count++;
}
// Check mode2 matches and append, for quotes this is the quote id.
if (result.mode2 == mode2) {
wpmSum += result.wpm;
count++;
if (count >= 10) {
// Break out of every loop since we a maximum of the last 10 wpm results.
return false;
}
}
}
return true;
});
// Return the last 10 average wpm for quote if the current quote id has never been completed before by the user.
if (count == 0 && mode == "quote") {
return Math.round(last10Wpm / last10Count);
}
// Return the average wpm of the last 10 completions for the targeted test mode.
return Math.round(wpmSum / count);
}
let retval = 0;
if (dbSnapshot == null) return retval;
var dbSnapshotValid = await getUserResults();
if (dbSnapshotValid === false) {
return retval;
}
retval = cont();
return retval;
}
export async function getLocalPB(
mode,
mode2,
punctuation,
language,
difficulty
) {
function cont() {
let ret = 0;
try {
dbSnapshot.personalBests[mode][mode2].forEach((pb) => {
if (
pb.punctuation == punctuation &&
pb.difficulty == difficulty &&
pb.language == language
) {
ret = pb.wpm;
}
});
return ret;
} catch (e) {
return ret;
}
}
let retval;
if (dbSnapshot == null) {
retval = 0;
} else {
retval = cont();
}
return retval;
}
export async function saveLocalPB(
mode,
mode2,
punctuation,
language,
difficulty,
wpm,
acc,
raw,
consistency
) {
if (mode == "quote") return;
function cont() {
try {
let found = false;
if (dbSnapshot.personalBests[mode][mode2] === undefined) {
dbSnapshot.personalBests[mode][mode2] = [];
}
dbSnapshot.personalBests[mode][mode2].forEach((pb) => {
if (
pb.punctuation == punctuation &&
pb.difficulty == difficulty &&
pb.language == language
) {
found = true;
pb.wpm = wpm;
pb.acc = acc;
pb.raw = raw;
pb.timestamp = Date.now();
pb.consistency = consistency;
}
});
if (!found) {
//nothing found
dbSnapshot.personalBests[mode][mode2].push({
language: language,
difficulty: difficulty,
punctuation: punctuation,
wpm: wpm,
acc: acc,
raw: raw,
timestamp: Date.now(),
consistency: consistency,
});
}
} catch (e) {
//that mode or mode2 is not found
dbSnapshot.personalBests = {};
dbSnapshot.personalBests[mode] = {};
dbSnapshot.personalBests[mode][mode2] = [
{
language: language,
difficulty: difficulty,
punctuation: punctuation,
wpm: wpm,
acc: acc,
raw: raw,
timestamp: Date.now(),
consistency: consistency,
},
];
}
}
if (dbSnapshot != null) {
cont();
}
}
export async function getLocalTagPB(
tagId,
mode,
mode2,
punctuation,
language,
difficulty
) {
function cont() {
let ret = 0;
let filteredtag = dbSnapshot.tags.filter((t) => t._id === tagId)[0];
try {
filteredtag.personalBests[mode][mode2].forEach((pb) => {
if (
pb.punctuation == punctuation &&
pb.difficulty == difficulty &&
pb.language == language
) {
ret = pb.wpm;
}
});
} catch (e) {
console.log(e);
}
return ret;
}
let retval;
if (dbSnapshot == null) {
retval = 0;
} else {
retval = cont();
}
return retval;
}
export async function saveLocalTagPB(
tagId,
mode,
mode2,
punctuation,
language,
difficulty,
wpm,
acc,
raw,
consistency
) {
if (mode == "quote") return;
function cont() {
let filteredtag = dbSnapshot.tags.filter((t) => t._id === tagId)[0];
try {
let found = false;
if (filteredtag.personalBests[mode][mode2] === undefined) {
filteredtag.personalBests[mode][mode2] = [];
}
filteredtag.personalBests[mode][mode2].forEach((pb) => {
if (
pb.punctuation == punctuation &&
pb.difficulty == difficulty &&
pb.language == language
) {
found = true;
pb.wpm = wpm;
pb.acc = acc;
pb.raw = raw;
pb.timestamp = Date.now();
pb.consistency = consistency;
}
});
if (!found) {
//nothing found
filteredtag.personalBests[mode][mode2].push({
language: language,
difficulty: difficulty,
punctuation: punctuation,
wpm: wpm,
acc: acc,
raw: raw,
timestamp: Date.now(),
consistency: consistency,
});
}
} catch (e) {
//that mode or mode2 is not found
filteredtag.personalBests = {};
filteredtag.personalBests[mode] = {};
filteredtag.personalBests[mode][mode2] = [
{
language: language,
difficulty: difficulty,
punctuation: punctuation,
wpm: wpm,
acc: acc,
raw: raw,
timestamp: Date.now(),
consistency: consistency,
},
];
}
}
if (dbSnapshot != null) {
cont();
}
}
export function updateLbMemory(mode, mode2, type, value) {
//could dbSnapshot just be used here instead of getSnapshot()
getSnapshot().lbMemory[mode + mode2][type] = value;
}
export async function saveConfig(config) {
if (firebase.auth().currentUser !== null) {
AccountButton.loading(true);
let response;
try {
response = await axiosInstance.post("/config/save", { config });
} catch (e) {
AccountButton.loading(false);
let msg = e?.response?.data?.message ?? e.message;
Notifications.add("Failed to save config: " + msg, -1);
return;
}
AccountButton.loading(false);
}
}
// export async function DB.getLocalTagPB(tagId) {
// function cont() {
// let ret = 0;
// try {
// ret = dbSnapshot.tags.filter((t) => t.id === tagId)[0].pb;
// if (ret == undefined) {
// ret = 0;
// }
// return ret;
// } catch (e) {
// return ret;
// }
// }
// let retval;
// if (dbSnapshot != null) {
// retval = cont();
// }
// return retval;
// }
// export async functio(tagId, wpm) {
// function cont() {
// dbSnapshot.tags.forEach((tag) => {
// if (tag._id === tagId) {
// tag.pb = wpm;
// }
// });
// }
// if (dbSnapshot != null) {
// cont();
// }
// }