added functions to check for pb and tag pb. rewrote pb check

This commit is contained in:
Jack 2021-06-08 23:49:54 +01:00
parent 30b1ac269b
commit ed01fcac53
4 changed files with 561 additions and 375 deletions

View file

@ -1,5 +1,7 @@
const MonkeyError = require("../handlers/error");
const { mongoDB } = require("../init/mongodb");
const { checkAndUpdatePb } = require("../handlers/pb");
class UsersDAO {
static async addUser(name, email, uid) {
return await mongoDB()
@ -79,6 +81,90 @@ class UsersDAO {
{ $pull: { tags: { personalBests } } }
);
}
static async checkIfPb(
uid,
mode,
mode2,
acc,
consistency,
difficulty,
language,
punctuation,
raw,
wpm
) {
const user = await mongoDB().collection("users").findOne({ uid });
if (!user) throw new MonkeyError(404, "User not found");
let pb = checkAndUpdatePb(
user.personalBests,
mode,
mode2,
acc,
consistency,
difficulty,
language,
punctuation,
raw,
wpm
);
if (pb.isPb) {
await mongoDB()
.collection("users")
.updateOne({ uid }, { $set: { personalBests: pb.obj } });
return true;
} else {
return false;
}
}
static async checkIfTagPb(
uid,
tags,
mode,
mode2,
acc,
consistency,
difficulty,
language,
punctuation,
raw,
wpm
) {
const user = await mongoDB().collection("users").findOne({ uid });
if (!user) throw new MonkeyError(404, "User not found");
if (user.tags === undefined || user.tags.length === 0) {
return [];
}
let ret = [];
tags.forEach(async (tag) => {
let tagpb = checkAndUpdatePb(
tag.personalBests,
mode,
mode2,
acc,
consistency,
difficulty,
language,
punctuation,
raw,
wpm
);
if (tagpb.isPb) {
ret.push(tag._id);
await mongoDB()
.collection("users")
.updateOne({ uid }, { $set: { tags: { personalBests: tagpb.obj } } });
}
});
return ret;
}
}
module.exports = UsersDAO;

View file

@ -1,119 +1,104 @@
module.exports = {
check(result, userdata) {
let pbs = null;
if (result.mode == "quote") {
return false;
}
if (result.funbox !== "none") {
return false;
}
/*
pbs = userdata?.personalBests;
if(pbs === undefined){
//userdao set personal best
return true;
}
// try {
// pbs = userdata.personalBests;
// if (pbs === undefined) {
// throw new Error("pb is undefined");
// }
// } catch (e) {
// User.findOne({ uid: userdata.uid }, (err, user) => {
// user.personalBests = {
// [result.mode]: {
// [result.mode2]: [
// {
// language: result.language,
// difficulty: result.difficulty,
// punctuation: result.punctuation,
// wpm: result.wpm,
// acc: result.acc,
// raw: result.rawWpm,
// timestamp: Date.now(),
// consistency: result.consistency,
// },
// ],
// },
// };
// }).then(() => {
// return true;
// });
// }
obj structure
let toUpdate = false;
let found = false;
try {
if (pbs[result.mode][result.mode2] === undefined) {
pbs[result.mode][result.mode2] = [];
}
pbs[result.mode][result.mode2].forEach((pb) => {
if (
pb.punctuation === result.punctuation &&
pb.difficulty === result.difficulty &&
pb.language === result.language
) {
//entry like this already exists, compare wpm
found = true;
if (pb.wpm < result.wpm) {
//new pb
pb.wpm = result.wpm;
pb.acc = result.acc;
pb.raw = result.rawWpm;
pb.timestamp = Date.now();
pb.consistency = result.consistency;
toUpdate = true;
} else {
//no pb
return false;
}
}
});
//checked all pbs, nothing found - meaning this is a new pb
if (!found) {
pbs[result.mode][result.mode2] = [
{
language: result.language,
difficulty: result.difficulty,
punctuation: result.punctuation,
wpm: result.wpm,
acc: result.acc,
raw: result.rawWpm,
timestamp: Date.now(),
consistency: result.consistency,
},
];
toUpdate = true;
}
} catch (e) {
// console.log(e);
pbs[result.mode] = {};
pbs[result.mode][result.mode2] = [
{
language: result.language,
difficulty: result.difficulty,
punctuation: result.punctuation,
wpm: result.wpm,
acc: result.acc,
raw: result.rawWpm,
timestamp: Date.now(),
consistency: result.consistency,
},
];
toUpdate = true;
}
if (toUpdate) {
// User.findOne({ uid: userdata.uid }, (err, user) => {
// user.personalBests = pbs;
// user.save();
// });
//userdao update the whole personalBests parameter with pbs object
return true;
} else {
return false;
time: {
10: [ - this is a list because there can be
different personal bests for different difficulties, languages and punctuation
{
acc,
consistency,
difficulty,
language,
punctuation,
raw,
timestamp,
wpm
}
]
},
words: {
10: [
{}
]
},
zen: {
zen: [
{}
]
},
custom: {
custom: {
[]
}
}
}
*/
module.exports = {
checkAndUpdatePb(
obj,
mode,
mode2,
acc,
consistency,
difficulty,
language,
punctuation,
raw,
wpm
) {
//verify structure first
if (obj === undefined) obj = {};
if (obj[mode] === undefined) obj[mode] = {};
if (obj[mode][mode2] === undefined) obj[mode][mode2] = [];
let isPb = false;
let found = false;
//find a pb
obj[mode][mode2].forEach((pb) => {
//check if we should compare first
if (
pb.difficulty === difficulty &&
pb.language === language &&
pb.punctuation === punctuation
) {
found = true;
//compare
if (pb.wpm < wpm) {
//update
isPb = true;
pb.acc = acc;
pb.consistency = consistency;
pb.raw = raw;
pb.wpm = wpm;
pb.timestamp = Date.now();
}
}
});
//if not found push a new one
if (!found) {
isPb = true;
obj[mode][mode2].push({
acc,
consistency,
difficulty,
language,
punctuation,
raw,
wpm,
timestamp: Date.now(),
});
}
return {
isPb,
obj,
};
},
};

119
backend/handlers/pb_old.js Normal file
View file

@ -0,0 +1,119 @@
// module.exports = {
// check(result, userdata) {
// let pbs = null;
// if (result.mode == "quote") {
// return false;
// }
// if (result.funbox !== "none") {
// return false;
// }
// pbs = userdata?.personalBests;
// if(pbs === undefined){
// //userdao set personal best
// return true;
// }
// // try {
// // pbs = userdata.personalBests;
// // if (pbs === undefined) {
// // throw new Error("pb is undefined");
// // }
// // } catch (e) {
// // User.findOne({ uid: userdata.uid }, (err, user) => {
// // user.personalBests = {
// // [result.mode]: {
// // [result.mode2]: [
// // {
// // language: result.language,
// // difficulty: result.difficulty,
// // punctuation: result.punctuation,
// // wpm: result.wpm,
// // acc: result.acc,
// // raw: result.rawWpm,
// // timestamp: Date.now(),
// // consistency: result.consistency,
// // },
// // ],
// // },
// // };
// // }).then(() => {
// // return true;
// // });
// // }
// let toUpdate = false;
// let found = false;
// try {
// if (pbs[result.mode][result.mode2] === undefined) {
// pbs[result.mode][result.mode2] = [];
// }
// pbs[result.mode][result.mode2].forEach((pb) => {
// if (
// pb.punctuation === result.punctuation &&
// pb.difficulty === result.difficulty &&
// pb.language === result.language
// ) {
// //entry like this already exists, compare wpm
// found = true;
// if (pb.wpm < result.wpm) {
// //new pb
// pb.wpm = result.wpm;
// pb.acc = result.acc;
// pb.raw = result.rawWpm;
// pb.timestamp = Date.now();
// pb.consistency = result.consistency;
// toUpdate = true;
// } else {
// //no pb
// return false;
// }
// }
// });
// //checked all pbs, nothing found - meaning this is a new pb
// if (!found) {
// pbs[result.mode][result.mode2] = [
// {
// language: result.language,
// difficulty: result.difficulty,
// punctuation: result.punctuation,
// wpm: result.wpm,
// acc: result.acc,
// raw: result.rawWpm,
// timestamp: Date.now(),
// consistency: result.consistency,
// },
// ];
// toUpdate = true;
// }
// } catch (e) {
// // console.log(e);
// pbs[result.mode] = {};
// pbs[result.mode][result.mode2] = [
// {
// language: result.language,
// difficulty: result.difficulty,
// punctuation: result.punctuation,
// wpm: result.wpm,
// acc: result.acc,
// raw: result.rawWpm,
// timestamp: Date.now(),
// consistency: result.consistency,
// },
// ];
// toUpdate = true;
// }
// if (toUpdate) {
// // User.findOne({ uid: userdata.uid }, (err, user) => {
// // user.personalBests = pbs;
// // user.save();
// // });
// //userdao update the whole personalBests parameter with pbs object
// return true;
// } else {
// return false;
// }
// }
// }

View file

@ -1,267 +1,263 @@
// async function checkIfTagPB(obj, userdata) {
// //function returns a list of tag ids where a pb was set //i think
// if (obj.tags.length === 0) {
// return [];
// }
// if (obj.mode === "quote") {
// return [];
// }
// let dbtags = []; //tags from database: include entire document: name, id, pbs
// let restags = obj.tags; //result tags
// try {
// let snap;
// await User.findOne({ uid: userdata.uid }, (err, user) => {
// snap = user.tags;
// });
// snap.forEach((doc) => {
// //if (restags.includes(doc._id)) {
// //if (restags.indexOf((doc._id).toString()) > -1) {
// if (restags.includes(doc._id.toString())) {
// //not sure what this is supposed to do
// /*
// let data = doc.data();
// data.id = doc.id;
// dbtags.push(data);
// */
// dbtags.push(doc);
// }
// });
// } catch {
// return [];
// }
// let ret = [];
// for (let i = 0; i < dbtags.length; i++) {
// let pbs = null;
// try {
// pbs = dbtags[i].personalBests;
// if (pbs === undefined || pbs === {}) {
// throw new Error("pb is undefined");
// }
// } catch (e) {
// //if pb is undefined, create a new personalBests field with only specified value
// await User.findOne({ uid: userdata.uid }, (err, user) => {
// //it might be more convenient if tags was an object with ids as the keys
// //find tag index in tags list
// // save that tags personal bests as object
// let j = user.tags.findIndex((tag) => {
// return tag._id.toString() == dbtags[i]._id.toString();
// });
// user.tags[j].personalBests = {
// [obj.mode]: {
// [obj.mode2]: [
// {
// language: obj.language,
// difficulty: obj.difficulty,
// punctuation: obj.punctuation,
// wpm: obj.wpm,
// acc: obj.acc,
// raw: obj.rawWpm,
// timestamp: Date.now(),
// consistency: obj.consistency,
// },
// ],
// },
// };
// pbs = user.tags[j].personalBests;
// user.save();
// }).then((updatedUser) => {
// ret.push(dbtags[i]._id.toString());
// });
// continue;
// }
// let toUpdate = false;
// let found = false;
// try {
// if (pbs[obj.mode] === undefined) {
// pbs[obj.mode] = { [obj.mode2]: [] };
// } else if (pbs[obj.mode][obj.mode2] === undefined) {
// pbs[obj.mode][obj.mode2] = [];
// }
// pbs[obj.mode][obj.mode2].forEach((pb) => {
// if (
// pb.punctuation === obj.punctuation &&
// pb.difficulty === obj.difficulty &&
// pb.language === obj.language
// ) {
// //entry like this already exists, compare wpm
// found = true;
// if (pb.wpm < obj.wpm) {
// //replace old pb with new obj
// pb.wpm = obj.wpm;
// pb.acc = obj.acc;
// pb.raw = obj.rawWpm;
// pb.timestamp = Date.now();
// pb.consistency = obj.consistency;
// toUpdate = true;
// } else {
// //no pb
// return false;
// }
// }
// });
// //checked all pbs, nothing found - meaning this is a new pb
// if (!found) {
// console.log("Semi-new pb");
// //push this pb to array
// pbs[obj.mode][obj.mode2].push({
// language: obj.language,
// difficulty: obj.difficulty,
// punctuation: obj.punctuation,
// wpm: obj.wpm,
// acc: obj.acc,
// raw: obj.rawWpm,
// timestamp: Date.now(),
// consistency: obj.consistency,
// });
// toUpdate = true;
// }
// } catch (e) {
// // console.log(e);
// console.log("Catch pb");
// console.log(e);
// pbs[obj.mode] = {};
// pbs[obj.mode][obj.mode2] = [
// {
// language: obj.language,
// difficulty: obj.difficulty,
// punctuation: obj.punctuation,
// wpm: obj.wpm,
// acc: obj.acc,
// raw: obj.rawWpm,
// timestamp: Date.now(),
// consistency: obj.consistency,
// },
// ];
// toUpdate = true;
// }
async function checkIfTagPB(obj, userdata) {
//function returns a list of tag ids where a pb was set //i think
if (obj.tags.length === 0) {
return [];
}
if (obj.mode === "quote") {
return [];
}
let dbtags = []; //tags from database: include entire document: name, id, pbs
let restags = obj.tags; //result tags
try {
let snap;
await User.findOne({ uid: userdata.uid }, (err, user) => {
snap = user.tags;
});
snap.forEach((doc) => {
//if (restags.includes(doc._id)) {
//if (restags.indexOf((doc._id).toString()) > -1) {
if (restags.includes(doc._id.toString())) {
//not sure what this is supposed to do
/*
let data = doc.data();
data.id = doc.id;
dbtags.push(data);
*/
dbtags.push(doc);
}
});
} catch {
return [];
}
let ret = [];
for (let i = 0; i < dbtags.length; i++) {
let pbs = null;
try {
pbs = dbtags[i].personalBests;
if (pbs === undefined || pbs === {}) {
throw new Error("pb is undefined");
}
} catch (e) {
//if pb is undefined, create a new personalBests field with only specified value
await User.findOne({ uid: userdata.uid }, (err, user) => {
//it might be more convenient if tags was an object with ids as the keys
//find tag index in tags list
// save that tags personal bests as object
let j = user.tags.findIndex((tag) => {
return tag._id.toString() == dbtags[i]._id.toString();
});
user.tags[j].personalBests = {
[obj.mode]: {
[obj.mode2]: [
{
language: obj.language,
difficulty: obj.difficulty,
punctuation: obj.punctuation,
wpm: obj.wpm,
acc: obj.acc,
raw: obj.rawWpm,
timestamp: Date.now(),
consistency: obj.consistency,
},
],
},
};
pbs = user.tags[j].personalBests;
user.save();
}).then((updatedUser) => {
ret.push(dbtags[i]._id.toString());
});
continue;
}
let toUpdate = false;
let found = false;
try {
if (pbs[obj.mode] === undefined) {
pbs[obj.mode] = { [obj.mode2]: [] };
} else if (pbs[obj.mode][obj.mode2] === undefined) {
pbs[obj.mode][obj.mode2] = [];
}
pbs[obj.mode][obj.mode2].forEach((pb) => {
if (
pb.punctuation === obj.punctuation &&
pb.difficulty === obj.difficulty &&
pb.language === obj.language
) {
//entry like this already exists, compare wpm
found = true;
if (pb.wpm < obj.wpm) {
//replace old pb with new obj
pb.wpm = obj.wpm;
pb.acc = obj.acc;
pb.raw = obj.rawWpm;
pb.timestamp = Date.now();
pb.consistency = obj.consistency;
toUpdate = true;
} else {
//no pb
return false;
}
}
});
//checked all pbs, nothing found - meaning this is a new pb
if (!found) {
console.log("Semi-new pb");
//push this pb to array
pbs[obj.mode][obj.mode2].push({
language: obj.language,
difficulty: obj.difficulty,
punctuation: obj.punctuation,
wpm: obj.wpm,
acc: obj.acc,
raw: obj.rawWpm,
timestamp: Date.now(),
consistency: obj.consistency,
});
toUpdate = true;
}
} catch (e) {
// console.log(e);
console.log("Catch pb");
console.log(e);
pbs[obj.mode] = {};
pbs[obj.mode][obj.mode2] = [
{
language: obj.language,
difficulty: obj.difficulty,
punctuation: obj.punctuation,
wpm: obj.wpm,
acc: obj.acc,
raw: obj.rawWpm,
timestamp: Date.now(),
consistency: obj.consistency,
},
];
toUpdate = true;
}
if (toUpdate) {
//push working pb array to user tags pbs
await User.findOne({ uid: userdata.uid }, (err, user) => {
for (let j = 0; j < user.tags.length; j++) {
if (user.tags[j]._id.toString() === dbtags[i]._id.toString()) {
user.tags[j].personalBests = pbs;
}
}
user.save();
});
ret.push(dbtags[i]._id.toString());
}
}
console.log(ret);
return ret;
}
app.post("/clearTagPb", authenticateToken, (req, res) => {
User.findOne({ uid: req.uid }, (err, user) => {
for (let i = 0; i < user.tags.length; i++) {
if (user.tags[i]._id.toString() === req.body.tagid.toString()) {
user.tags[i].personalBests = {};
user.save();
res.send({ resultCode: 1 });
return;
}
}
}).catch((e) => {
console.error(`error deleting tag pb for user ${req.uid}: ${e.message}`);
res.send({
resultCode: -999,
message: e.message,
});
});
res.sendStatus(200);
});
// if (toUpdate) {
// //push working pb array to user tags pbs
// await User.findOne({ uid: userdata.uid }, (err, user) => {
// for (let j = 0; j < user.tags.length; j++) {
// if (user.tags[j]._id.toString() === dbtags[i]._id.toString()) {
// user.tags[j].personalBests = pbs;
// }
// }
// user.save();
// });
// ret.push(dbtags[i]._id.toString());
// }
// }
// console.log(ret);
// return ret;
// }
// app.post("/clearTagPb", authenticateToken, (req, res) => {
// User.findOne({ uid: req.uid }, (err, user) => {
// for (let i = 0; i < user.tags.length; i++) {
// if (user.tags[i]._id.toString() === req.body.tagid.toString()) {
// user.tags[i].personalBests = {};
// user.save();
// res.send({ resultCode: 1 });
// return;
// }
// }
// }).catch((e) => {
// console.error(`error deleting tag pb for user ${req.uid}: ${e.message}`);
// res.send({
// resultCode: -999,
// message: e.message,
// });
// });
// res.sendStatus(200);
// });
//could use /tags/add instead
app.post("/addTag", authenticateToken, (req, res) => {
try {
if (!isTagPresetNameValid(req.body.tagName)) return { resultCode: -1 };
User.findOne({ uid: req.uid }, (err, user) => {
if (err) res.status(500).send({ error: err });
if (user.tags.includes(req.body.tagName)) {
return { resultCode: -999, message: "Duplicate tag" };
}
const tagObj = { name: req.body.tagName };
user.tags.push(tagObj);
user.save();
})
.then(() => {
console.log(`user ${req.uid} created a tag: ${req.body.tagName}`);
let newTagId;
User.findOne({ uid: req.uid }, (err, user) => {
newTagId = user.tags[user.tags.length - 1]._id;
}).then(() => {
res.json({
resultCode: 1,
id: newTagId,
});
});
})
.catch((e) => {
console.error(
`error while creating tag for user ${req.uid}: ${e.message}`
);
res.json({ resultCode: -999, message: e.message });
});
} catch (e) {
console.error(`error adding tag for ${req.uid} - ${e}`);
res.json({ resultCode: -999, message: e.message });
}
});
// app.post("/addTag", authenticateToken, (req, res) => {
// try {
// if (!isTagPresetNameValid(req.body.tagName)) return { resultCode: -1 };
// User.findOne({ uid: req.uid }, (err, user) => {
// if (err) res.status(500).send({ error: err });
// if (user.tags.includes(req.body.tagName)) {
// return { resultCode: -999, message: "Duplicate tag" };
// }
// const tagObj = { name: req.body.tagName };
// user.tags.push(tagObj);
// user.save();
// })
// .then(() => {
// console.log(`user ${req.uid} created a tag: ${req.body.tagName}`);
// let newTagId;
// User.findOne({ uid: req.uid }, (err, user) => {
// newTagId = user.tags[user.tags.length - 1]._id;
// }).then(() => {
// res.json({
// resultCode: 1,
// id: newTagId,
// });
// });
// })
// .catch((e) => {
// console.error(
// `error while creating tag for user ${req.uid}: ${e.message}`
// );
// res.json({ resultCode: -999, message: e.message });
// });
// } catch (e) {
// console.error(`error adding tag for ${req.uid} - ${e}`);
// res.json({ resultCode: -999, message: e.message });
// }
// });
app.post("/editTag", authenticateToken, (req, res) => {
try {
if (!isTagPresetNameValid(req.body.tagName)) return { resultCode: -1 };
User.findOne({ uid: req.uid }, (err, user) => {
if (err) res.status(500).send({ error: err });
for (var i = 0; i < user.tags.length; i++) {
if (user.tags[i]._id == req.body.tagId) {
user.tags[i].name = req.body.tagName;
}
}
user.save();
})
.then((updatedUser) => {
console.log(`user ${req.uid} updated a tag: ${req.body.tagName}`);
res.json({ resultCode: 1 });
})
.catch((e) => {
console.error(
`error while updating tag for user ${req.uid}: ${e.message}`
);
res.json({ resultCode: -999, message: e.message });
});
} catch (e) {
console.error(`error updating tag for ${req.uid} - ${e}`);
res.json({ resultCode: -999, message: e.message });
}
});
// app.post("/editTag", authenticateToken, (req, res) => {
// try {
// if (!isTagPresetNameValid(req.body.tagName)) return { resultCode: -1 };
// User.findOne({ uid: req.uid }, (err, user) => {
// if (err) res.status(500).send({ error: err });
// for (var i = 0; i < user.tags.length; i++) {
// if (user.tags[i]._id == req.body.tagId) {
// user.tags[i].name = req.body.tagName;
// }
// }
// user.save();
// })
// .then((updatedUser) => {
// console.log(`user ${req.uid} updated a tag: ${req.body.tagName}`);
// res.json({ resultCode: 1 });
// })
// .catch((e) => {
// console.error(
// `error while updating tag for user ${req.uid}: ${e.message}`
// );
// res.json({ resultCode: -999, message: e.message });
// });
// } catch (e) {
// console.error(`error updating tag for ${req.uid} - ${e}`);
// res.json({ resultCode: -999, message: e.message });
// }
// });
app.post("/removeTag", authenticateToken, (req, res) => {
try {
User.findOne({ uid: req.uid }, (err, user) => {
if (err) res.status(500).send({ error: err });
for (var i = 0; i < user.tags.length; i++) {
if (user.tags[i]._id == req.body.tagId) {
user.tags.splice(i, 1);
}
}
user.save();
})
.then((updatedUser) => {
console.log(`user ${req.uid} deleted a tag`);
res.json({ resultCode: 1 });
})
.catch((e) => {
console.error(`error deleting tag for user ${req.uid}: ${e.message}`);
res.json({ resultCode: -999 });
});
} catch (e) {
console.error(`error deleting tag for ${req.uid} - ${e}`);
res.json({ resultCode: -999 });
}
});
// app.post("/removeTag", authenticateToken, (req, res) => {
// try {
// User.findOne({ uid: req.uid }, (err, user) => {
// if (err) res.status(500).send({ error: err });
// for (var i = 0; i < user.tags.length; i++) {
// if (user.tags[i]._id == req.body.tagId) {
// user.tags.splice(i, 1);
// }
// }
// user.save();
// })
// .then((updatedUser) => {
// console.log(`user ${req.uid} deleted a tag`);
// res.json({ resultCode: 1 });
// })
// .catch((e) => {
// console.error(`error deleting tag for user ${req.uid}: ${e.message}`);
// res.json({ resultCode: -999 });
// });
// } catch (e) {
// console.error(`error deleting tag for ${req.uid} - ${e}`);
// res.json({ resultCode: -999 });
// }
// });