Skip to content

Commit

Permalink
Remove useless logs + cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
codergautam committed Nov 17, 2024
1 parent 295b442 commit 5fd9a66
Show file tree
Hide file tree
Showing 16 changed files with 70 additions and 146 deletions.
18 changes: 9 additions & 9 deletions api/crazyAuth.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,15 @@ export default async function handler(req, res) {
const newUser = new User({ crazyGamesId: userId, username: finalUsername, secret });
await newUser.save();

try {
if (process.env.DISCORD_WEBHOOK) {
const hook = new Webhook(process.env.DISCORD_WEBHOOK);
hook.setUsername("WorldGuessr");
hook.send(`🎮 **${finalUsername}** has joined WorldGuessr from CrazyGames!`);
}
} catch (error) {
console.error('Error sending discord webhook', error);
}
// try {
// if (process.env.DISCORD_WEBHOOK) {
// const hook = new Webhook(process.env.DISCORD_WEBHOOK);
// hook.setUsername("WorldGuessr");
// hook.send(`🎮 **${finalUsername}** has joined WorldGuessr from CrazyGames!`);
// }
// } catch (error) {
// console.error('Error sending discord webhook', error);
// }

return res.status(200).json({ secret: newUser.secret, username: newUser.username });
}
3 changes: 0 additions & 3 deletions api/eloRank.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,9 @@ export default async function handler(req, res) {
return res.status(404).json({ message: 'User not found' });
}

console.time('get user rank', user.username);
const rank = (await User.countDocuments({ elo: { $gt: user.elo },
banned: false
}).cache(2000)) + 1;
console.timeEnd('get user rank', user.username);

// Return the user's elo and rank
return res.status(200).json({ elo: user.elo, rank, league: getLeague(user.elo),
Expand All @@ -48,7 +46,6 @@ export async function setElo(accountId, newElo, gameData) {
// gamedata -> {draw:true|false, winner: true|false}
try {

console.log('Setting elo', accountId, newElo, 'old elo', gameData.oldElo, 'gameData', gameData);

await User.updateOne({ _id: accountId }, { elo: newElo,
$inc: { duels_played: 1, duels_wins: gameData.winner ? 1 : 0, duels_losses: gameData.winner ? 0 : 1, duels_tied: gameData.draw ? 1 : 0,
Expand Down
3 changes: 0 additions & 3 deletions api/googleAuth.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,9 @@ export default async function handler(req, res) {
return res.status(400).json({ error: 'Invalid' });
}

console.time('findUser');
const userDb = await User.findOne({
secret,
}).select("secret username email staff canMakeClues supporter").cache(120);
console.timeEnd('findUser');
if (userDb) {
output = { secret: userDb.secret, username: userDb.username, email: userDb.email, staff: userDb.staff, canMakeClues: userDb.canMakeClues, supporter: userDb.supporter };
return res.status(200).json(output);
Expand Down Expand Up @@ -58,7 +56,6 @@ export default async function handler(req, res) {
const existingUser = await User.findOne({ email });
let secret = null;
if (!existingUser) {
console.log("User does not exist, creating a new user", email);
secret = createUUID();
const newUser = new User({ email, secret });
await newUser.save();
Expand Down
1 change: 0 additions & 1 deletion api/leaderboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ export default async function handler(req, res) {
}

const xp = req.query.mode === 'xp';
console.log('leaderboard', myUsername, pastDay, xp);

if(xp) {
try {
Expand Down
11 changes: 0 additions & 11 deletions api/map/mapHome.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,7 @@ export default async function handler(req, res) {
let user;

if(secret) {
console.time('findUser');
user = await User.findOne({ secret: secret });
console.timeEnd('findUser');
if(typeof secret !== 'string') {
return res.status(400).json({ message: 'Invalid input' });
}
Expand Down Expand Up @@ -83,7 +81,6 @@ export default async function handler(req, res) {
// find maps made by user
if(user) {
// created_at, slug, name, hearts,plays, description_short, map_creator_name, _id, in_review, official, accepted, reject_reason, resubmittable, locationsCnt
console.time('findMyMaps');
let myMaps = await Map.find({ created_by: user._id.toString() }).select({
created_at: 1,
slug: 1,
Expand Down Expand Up @@ -111,7 +108,6 @@ export default async function handler(req, res) {
if(!map.map_creator_name) {
owner = await User.findById(map.created_by);
// save map creator name
console.log('updating map creator name', map._id, owner.username, map.name);
map.map_creator_name = owner.username;
await map.save();

Expand All @@ -122,7 +118,6 @@ export default async function handler(req, res) {
}));
likedMapsSendable.sort((a,b) => b.created_at - a.created_at);
if(likedMapsSendable.length > 0) response.likedMaps = likedMapsSendable;
console.timeEnd('findMyMaps');
}

response.countryMaps = Object.values(officialCountryMaps).map((map) => ({
Expand Down Expand Up @@ -152,11 +147,8 @@ export default async function handler(req, res) {
// retrieve from db
let maps = [];
if(method === "recent") {
console.time('findRecentMaps');
maps = await Map.find({ accepted: true }).sort({ created_at: -1 }).limit(100);
console.timeEnd('findRecentMaps');
} else if(method === "popular") {
console.time('findPopularMaps');
maps = await Map.find({ accepted: true }) .select({
locationsCnt: { $size: "$data" },
created_at: 1,
Expand All @@ -176,18 +168,15 @@ export default async function handler(req, res) {
// sort and limit to 100
maps = maps.sort((a,b) => b.hearts - a.hearts).slice(0,100);

console.timeEnd('findPopularMaps');
} else if(method === "spotlight") {
maps = await Map.find({ accepted: true, spotlight: true }).limit(100).allowDiskUse(true);
console.log('spotlight maps', maps.length);
}

let sendableMaps = await Promise.all(maps.map(async (map) => {
let owner;
if(!map.map_creator_name && map.data) {
owner = await User.findById(map.created_by);
// save map creator name
console.log('updating map creator name', map._id, owner.username, map.name);
map.map_creator_name = owner.username;
await map.save();
} else {
Expand Down
1 change: 0 additions & 1 deletion api/map/publicData.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import msToTime from "../../components/msToTime.js";

export default async function handler(req, res) {
const slug = req.query.slug;
console.log("Getting map data for", slug);
const secret = await getServerSecret(req);
const session = {};
if(secret) {
Expand Down
4 changes: 0 additions & 4 deletions api/map/searchMap.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ export default async function searchMaps(req, res) {
}

let hearted_maps = user ? user.hearted_maps : null;
console.log('searching maps for query:', query);

// Validate the search query
if (!query || query.length < 3) {
Expand All @@ -36,7 +35,6 @@ export default async function searchMaps(req, res) {
query = query.replace(/[^a-zA-Z0-9\s]/g, '');

try {
console.time('searchMaps');
// Find maps that match the search query in either name, short description, or author name
let maps = await Map.find({
accepted: true,
Expand All @@ -58,7 +56,6 @@ export default async function searchMaps(req, res) {
owner = null;
}
// save map creator name
console.log('updating map creator name', map._id, owner.username, map.name);
map.map_creator_name = owner.username;
await map.save();
} else{
Expand All @@ -67,7 +64,6 @@ export default async function searchMaps(req, res) {

return sendableMap(map, owner, hearted_maps?hearted_maps.has(map._id.toString()):false, user?.staff, map.created_by === user?._id.toString());
}));
console.timeEnd('searchMaps');

res.status(200).json(sendableMaps);
} catch (error) {
Expand Down
2 changes: 0 additions & 2 deletions api/publicAccount.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,7 @@ export default async function handler(req, res) {

try {
// Find user by the provided token
console.time('findUser');
const user = id ? await User.findById(id).cache(120) : await User.findOne({ secret }).cache(120);
console.timeEnd('findUser');
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
Expand Down
18 changes: 9 additions & 9 deletions api/setName.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,15 @@ export default async function handler(req, res) {
user.username = username;
await user.save();

try {
if(process.env.DISCORD_WEBHOOK) {
const hook = new Webhook(process.env.DISCORD_WEBHOOK);
hook.setUsername("WorldGuessr");
hook.send(`🎉 **${username}** has joined WorldGuessr!`);
}
} catch (error) {
console.error('Discord webhook failed', error);
}
// try {
// if(process.env.DISCORD_WEBHOOK) {
// const hook = new Webhook(process.env.DISCORD_WEBHOOK);
// hook.setUsername("WorldGuessr");
// hook.send(`🎉 **${username}** has joined WorldGuessr!`);
// }
// } catch (error) {
// console.error('Discord webhook failed', error);
// }

res.status(200).json({ success: true });
} catch (error) {
Expand Down
2 changes: 1 addition & 1 deletion components/home.js
Original file line number Diff line number Diff line change
Expand Up @@ -1977,7 +1977,7 @@ setTimeout(() => {

<Navbar maintenance={maintenance} inCrazyGames={inCrazyGames} loading={loading} onFriendsPress={()=>setFriendsModal(true)} loginQueued={loginQueued} setLoginQueued={setLoginQueued} inGame={multiplayerState?.inGame || screen === "singleplayer"} openAccountModal={() => setAccountModalOpen(true)} session={session} reloadBtnPressed={reloadBtnPressed} backBtnPressed={backBtnPressed} setGameOptionsModalShown={setGameOptionsModalShown} onNavbarPress={() => onNavbarLogoPress()} gameOptions={gameOptions} screen={screen} multiplayerState={multiplayerState} shown={!multiplayerState?.gameData?.public && !leagueModal} />
{/* ELO/League button */}
{screen === "home" && !mapModal && session && session?.token?.secret && !inCrazyGames && !session?.token?.supporter && (
{screen === "home" && !mapModal && session && session?.token?.secret && (
<button className="gameBtn leagueBtn" onClick={()=>{setLeagueModal(true)}} style={{backgroundColor: eloData?.league?.color }}>
{ !eloData ? '...' : animatedEloDisplay } ELO {eloData?.league?.emoji}
</button>
Expand Down
88 changes: 18 additions & 70 deletions cron.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,73 +13,24 @@ import cityGen from './serverUtils/cityGen.js';

configDotenv();

let dbEnabled = false;
if (!process.env.MONGODB) {
console.log("[MISSING-ENV WARN] MONGODB env variable not set".yellow);
dbEnabled = false;
} else {
// Connect to MongoDB
if (mongoose.connection.readyState !== 1) {
try {
await mongoose.connect(process.env.MONGODB);
console.log('[INFO] Database Connected');
dbEnabled = true;
} catch (error) {
console.error('[ERROR] Database connection failed!'.red, error.message);
console.log(error);
dbEnabled = false;
}
}
}

async function calculateRanks() {
if (!dbEnabled) return;
console.log('Calculating ranks');
console.time('Updated ranks');

const users = await User.find({ banned: false }).select('elo lastEloHistoryUpdate').sort({ elo: -1 });

// Prepare bulk operations
const bulkOps = [];

for (let i = 0; i < users.length; i++) {
const user = users[i];

// Prepare the update operation for the current user
if((Date.now() - user.lastEloHistoryUpdate > 24 * 60 * 60 * 1000)) {
bulkOps.push({
updateOne: {
filter: { _id: user._id },
update: {

$push: { elo_history: { elo: user.elo, time: Date.now() } },
$set: { lastEloHistoryUpdate: Date.now() },
$set: { elo_today: 0 },

},
},
});
}
}

// Execute bulk operations
if (bulkOps.length > 0) {
await User.bulkWrite(bulkOps);
}

console.timeEnd('Updated ranks');
console.log('bulkOps', bulkOps.length);
}

// Calculate ranks every 12 hours
// setInterval(calculateRanks, 60 * 60 * 1000 * 3);
function recursiveCalculateRanks() {
calculateRanks().then(() => {
setTimeout(recursiveCalculateRanks, 12 * 60 * 60 * 1000);
});
}
recursiveCalculateRanks();

// let dbEnabled = false;
// if (!process.env.MONGODB) {
// console.log("[MISSING-ENV WARN] MONGODB env variable not set".yellow);
// dbEnabled = false;
// } else {
// // Connect to MongoDB
// if (mongoose.connection.readyState !== 1) {
// try {
// await mongoose.connect(process.env.MONGODB);
// console.log('[INFO] Database Connected');
// dbEnabled = true;
// } catch (error) {
// console.error('[ERROR] Database connection failed!'.red, error.message);
// console.log(error);
// dbEnabled = false;
// }
// }
// }


let countryLocations = {};
Expand Down Expand Up @@ -134,9 +85,6 @@ const generateBalancedLocations = async () => {
}


// log average number of locatiosn per country
const total = Object.values(countryLocations).reduce((acc, val) => acc + val.length, 0);
console.log('Average locations per country:', total / countries.length);

} catch (error) {
console.error('Error generating locations', error);
Expand Down
9 changes: 9 additions & 0 deletions pages/leaderboard/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,15 @@ const Leaderboard = ({ }) => {
<br/>
</h2>
)}

{/* elo past day doesnt work, display message */}
{pastDay && useElo && (
<h2 style={{marginBottom: '2rem'}}>
ELO past day leaderboard is not working at the moment.
We are working on fixing it.
<br/>
</h2>
)}
<div className="leaderboard" id="leaderboard">


Expand Down
Loading

0 comments on commit 5fd9a66

Please sign in to comment.