Add files via upload

This commit is contained in:
Richard Gingrich
2024-08-06 15:53:05 -06:00
committed by GitHub
commit 5ca105d4f2
21 changed files with 4428 additions and 0 deletions

45
api/controllers/chats.js Normal file
View File

@@ -0,0 +1,45 @@
const chats = require("../models/chat");
const _ = require('lodash');
module.exports.saveMessage = async (req, res) => {
try{
const {senderId, receiverId, message} = req.body;
if(!senderId) return res.type('json').status(400).send("Sender id was not provided.");
if(!receiverId) return res.type('json').status(400).send("Receiver id was not provided.");
if(!message) return res.type('json').status(400).send("Message was not provided");
const newChat = new chats({
senderId:senderId,
receiverId:receiverId,
message:message
});
await newChat.save();
return res.type('json').status(201).send(newChat);
}catch(err) {
return res.type('json').status(500).send(err.toString());
}
};
module.exports.retrieveMessages = async (req, res) => {
try{
const {senderId, receiverId} = req.body;
if(!senderId) return res.type('json').status(400).send("Sender id was not provided.");
if(!receiverId) return res.type('json').status(400).send("Receiver id was not provided.");
const messages = [];
const cursor = chats.find({$or : [{$and:[{senderId:senderId}, {receiverId:receiverId}]}, {$and:[{senderId:receiverId}, {receiverId:senderId}]}]}).sort("timestamp").cursor();
for (let message = await cursor.next(); message != null; message = await cursor.next()) {
messages.push({senderId:message.senderId, receiverId:message.receiverId, message:message.message});
}
return res.type('json').status(200).send(messages);
}catch(err) {
return res.type('json').status(500).send(err.toString());
}
}

View File

@@ -0,0 +1,45 @@
const commendation = require("../models/commendation");
const user = require("../models/user");
module.exports.saveCommendation = async (req, res) => {
try{
const {commenderId, commendedId, score} = req.body;
if(!commenderId) return res.type('json').status(400).send("Commender id was not provided.");
if(!commendedId) return res.type('json').status(400).send("Commended id was not provided.");
if(!score) return res.type('json').status(400).send("Score was not provided.");
if(score <= 0 || score > 10) return res.type('json').status(400).send("Score must be >= 1 and <= 10");
// Make sure the person is not commending again
let foundCommendation = await commendation.findOne({$and: [{commendedId:commendedId}, {commenderId:commenderId}]}).exec();
if(foundCommendation) return res.type('json').status(400).send("You have already commended this user.");
// Compute average reputation of commended person
let totalReputation = score, totalNumOfCommends = 1, newReputation = 0;
const cursor = commendation.find({commendedId:commendedId}).cursor();
for (let commendation = await cursor.next(); commendation != null; commendation = await cursor.next()) {
totalReputation += commendation.score;
totalNumOfCommends += 1;
}
newReputation = Math.round(totalReputation/totalNumOfCommends);
// Save New Commendation
await new commendation({
commendedId: commendedId,
commenderId: commenderId,
score: score
}).save();
// Update users reputation
const updatedUser = await user.findOneAndUpdate({_id: commendedId},
{reputation:newReputation},
{returnOriginal: false});
if(!updatedUser) return res.type('json').status(400).send("Commended user reputation could not be updated.");
return res.type('json').status(200).send();
}catch(err) {
return res.type('json').status(500).send(err.toString());
}
};

View File

@@ -0,0 +1,61 @@
const filter = require("../models/filter");
const _ = require('lodash');
module.exports.retrieve = async (req, res) => {
try{
const userId = req.params.userId;
// Basic Validation
if(!userId) return res.type('json').status(400).send('The user id is missing');
// Check if the filters exist
var searchedFilters = await filter.findOne({userId:userId}).exec();
if (!searchedFilters){
return res.type('json').status(404).send("Filters for specified user were not found.");
}else{
return res.type('json').status(200).send(searchedFilters);
}
}catch(err) {
return res.type('json').status(500).send(err.toString());
}
}
module.exports.upsert = async(req, res) => {
try{
const {userId, filters} = req.body;
// Basic Validation
if(!userId) return res.type('json').status(400).send('The user id is missing');
// Check if the filters exist
var searchedFilters = await filter.findOne({userId:userId}).exec();
if(searchedFilters){ // Update the filters
if(!filters) return res.type('json').status(400).send('The filters are is missing');
const updatedFilters = await filter.findOneAndUpdate({userId:userId},
{...filters},
{returnOriginal: false});
return res.type('json').status(200).send(updatedFilters);
}else{ // Insert new filters [with default values]
const newFilters = new filter({
userId: userId,
});
await newFilters.save();
return res.type('json').status(201).send(newFilters);
}
}catch(err) {
return res.type('json').status(500).send(err.toString());
}
}

View File

@@ -0,0 +1,29 @@
const matching = require("../models/matching");
const user = require("../models/user");
const _ = require('lodash');
module.exports.retrieveMatchHistory = async (req, res) => {
try{
const userId = req.params.userId;
// Basic Validation
if(!userId) return res.type('json').status(400).send('The user id is missing');
// Check if the filters exist
const userList = [];
const cursor = matching.find({ $or:[ {'firstUser': userId}, {'secondUser': userId} ]}).sort('timestamp').cursor();
for (let match = await cursor.next(); match != null; match = await cursor.next()) {
if(match.firstUser !== userId){
userList.push(await user.findOne({_id:match.firstUser}).exec());
}else if(match.secondUser !== userId){
userList.push(await user.findOne({_id:match.secondUser}).exec());
}
}
return res.type('json').status(200).send(userList);
}catch(err) {
return res.type('json').status(500).send(err.toString());
}
}

188
api/controllers/users.js Normal file
View File

@@ -0,0 +1,188 @@
const bcrypt = require('bcrypt');
const user = require("../models/user");
const _ = require('lodash');
const axios = require('axios');
module.exports.registerUser = async (req, res) => {
try{
const{displayName, gameName, tagLine, email, password, avatarImage} = req.body;
// Validation of body variables
if(!gameName) return res.type('json').status(404).send('The game name is missing');
if(!tagLine) return res.type('json').status(404).send('The tag line is missing');
if(!email) return res.type('json').status(404).send('The email is missing');
if(!password) return res.type('json').status(404).send('The password is missing');
let searchedUser = await user.findOne({gameName:gameName, tagLine:tagLine}).exec();
if(searchedUser) return res.type('json').status(400).send("Game name and tagline combination already in use.");
// Getting user's extra info from riot's api
const baseUrl1 = process.env.RIOT_BASE_URL1;
const fullUrl1 = `${baseUrl1}${gameName}\\${tagLine}`
let response = await axios.get(fullUrl1);
var extraData = response.data.data;
// Getting user's rank from riot's api
const baseUrl2 = process.env.RIOT_BASE_URL2;
const fullUrl2 = `${baseUrl2}${extraData.region}\\${gameName}\\${tagLine}`;
let response2 = await axios.get(fullUrl2);
let rank = parseRank(response2.data.data.currenttierpatched);
const newUser = new user({
riotId: extraData.puuid,
displayName: !displayName?gameName:displayName,
gameName: gameName,
tagLine: tagLine,
email: email,
password: await bcrypt.hash(password, await bcrypt.genSalt(10)),
avatarImage: avatarImage,
rank: [rank.rankType, rank.rankLevel],
accountLevel: extraData.account_level,
region: toRegionNo(extraData.region)
});
await newUser.save();
return res.type('json').status(201).send( _.pick(newUser, ['_id', 'riotId', 'displayName', 'gameName','tagLine', 'email', 'avatarImage', 'rank', 'accountLevel', 'region', 'age', 'gender', 'reputation', 'playerType', 'aboutMe']));
}catch(err){
return res.type('json').status(500).send(err.toString());
}
}
module.exports.loginUser = async (req, res) => {
try{
const {email, password} = req.body;
if(!email) return res.type('json').status(404).send('The username is missing');
if(!password) return res.type('json').status(404).send('The password is missing');
// Check if the username exists
var searchedUser = await user.findOne({email:email}).select("+password").exec();
if (!searchedUser){
return res.type('json').status(404).send("User was not found.");
}else{
// Check if the passwords match
const isPasswordValid = await bcrypt.compare(password, searchedUser.password);
if(!isPasswordValid){
return res.type('json').status(404).send("The password is incorrect.");
}
return res.type('json').status(200).send(_.pick(searchedUser, ['_id', 'riotId', 'displayName', 'gameName','tagLine','email', 'avatarImage', 'rank', 'accountLevel', 'region', 'age', 'gender', 'reputation', 'playerType', 'aboutMe']));
}
}catch(err) {
return res.type('json').status(500).send(err.toString());
}
};
module.exports.updateUser = async (req, res) => {
try{
const updateDTO = req.body;
if(!updateDTO.userId) return res.type('json').status(400).send('A user id must be provided');
// Check if the username exists
var searchedUser = await user.findOne({_id:updateDTO.userId}).exec();
if (!searchedUser){
return res.type('json').status(404).send("User to update was not found.");
}else{
let updateParams = _.pick(updateDTO, ['displayName', 'age', 'gender', 'playerType', 'aboutMe', 'avatarImage']);
const updatedUser = await user.findOneAndUpdate({_id:updateDTO.userId},
{...updateParams},
{returnOriginal: false});
return res.type('json').status(200).send(updatedUser);
}
}catch(err) {
return res.type('json').status(500).send(err.toString());
}
};
// Implement end-point to retrieve a user by ID (we only have login)
module.exports.findUser = async (req, res) => {
try{
const userId = req.params.userId;
if(!userId) return res.type('json').status(400).send('Invalid user id provided.');
// Find the user
var searchedUser = await user.findOne({_id:userId}).exec();
if (!searchedUser){
return res.type('json').status(404).send("User was not found.");
}else{
return res.type('json').status(200).send(_.pick(searchedUser, ['_id', 'riotId', 'displayName', 'gameName','tagLine','email', 'avatarImage', 'rank', 'accountLevel', 'region', 'age', 'gender', 'reputation', 'playerType', 'aboutMe']));
}
}catch(err) {
return res.type('json').status(500).send(err.toString());
}
};
/* Helper Functions */
function toRegionNo(region){
let res = -1;
switch(region){
case 'na':
res = 0;
break;
case 'eu':
res = 1;
break;
case 'ap':
res = 2;
break;
case 'kr':
res = 3;
break;
}
return res;
}
function parseRank(rank){
let rankName = rank.substring(0, rank.indexOf(" "));
let rankType = -1;
let rankLevel = rank.substring(rank.indexOf(" ") + 1) * 1;
switch(rankName.toLowerCase()){
case 'iron':
rankType = 1;
break;
case 'bronze':
rankType = 2;
break;
case 'silver':
rankType = 3;
break;
case 'gold':
rankType = 4;
break;
case 'platinum':
rankType = 5;
break;
case 'diamond':
rankType = 6;
break;
case 'ascendant':
rankType = 7;
break;
case 'immortal':
rankType = 8;
break;
case 'radiant':
rankType = 9;
break;
}
return {rankType: rankType, rankLevel: rankLevel};
}