Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix some bug and improved fetcher #6

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 57 additions & 56 deletions fetcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const axios = require('axios');
const cheerio = require('cheerio');
const mongoose = require('mongoose');
const moment = require('moment');

require('dotenv').config();

// Function to extract users from HTML
Expand Down Expand Up @@ -60,92 +61,92 @@ async function fetchCSESData() {

// Function to update MongoDB
async function updateMongoDB(users) {
if (!users || Object.keys(users).length === 0) {
if (!users) {
console.log('No user data to update');
return false;
}

const session = await mongoose.startSession();
let client;
try {
session.startTransaction();

const uri = process.env.MONGODB_URI;
if (!uri) {
throw new Error('MongoDB URI not found in environment variables');
}

if (!mongoose.connection.readyState) {
await mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true
});
}

const collection = mongoose.connection.collection('CSES');
const todayDate = moment().format('DD/MM/YYYY');
const yesterdayDate = moment().subtract(1, 'days').format('DD/MM/YYYY');

const operations = [];
for (const [user, tasks] of Object.entries(users)) {
const document = await collection.findOne({ username: user }, { session });
const document = await collection.findOne({ username: user });

if (document) {
const prevSolved = document.solved?.[yesterdayDate] || 0;
const currentStreak = document.streak || 0;

let newStreak = 0;
if (tasks > prevSolved) {
newStreak = currentStreak + 1;
let streak = parseInt(document.streak || 0);
const prevSolved = document.solved?.[yesterdayDate];
let currSolved = prevSolved ;

if (prevSolved !== undefined && prevSolved < tasks) {
streak = document.prevStreak + 1;
currSolved = tasks;
} else {
streak = 0;
}

operations.push({
updateOne: {
filter: { username: user },
update: {
$set: {
[`solved.${todayDate}`]: tasks,
streak: newStreak,
questionSolved: tasks,
lastUpdated: new Date()
}
}
}
});
} else {
operations.push({
insertOne: {
document: {
username: user,
solved: { [todayDate]: tasks },
streak: 0,
document.solved = document.solved || {};
document.solved[todayDate] = currSolved ?? tasks;

await collection.updateOne(
{ username: user },
{
$set: {
solved: document.solved,
streak: streak,
questionSolved: tasks,
lastUpdated: new Date()
prevStreak: document.streak || 0
}
}
});
);
} else {
const data = {
username: user,
solved: { [todayDate]: tasks },
streak: 0,
questionSolved: tasks,
prevStreak: 0
};
await collection.insertOne(data);
}
}

if (operations.length > 0) {
await collection.bulkWrite(operations, { session });
console.log(`Updated ${operations.length} users`);
}

await session.commitTransaction();
return true;
} catch (error) {
await session.abortTransaction();
console.error('Error updating MongoDB:', error);
throw error;
} finally {
await session.endSession();
console.error('Error updating MongoDB:', error.message);
return false;
}
}

// Main function to fetch and update data
async function updateLeaderboard() {
console.log('Starting leaderboard update:', new Date().toISOString());
try {
console.log('Starting leaderboard update...');
const users = await fetchCSESData();

if (!users || Object.keys(users).length === 0) {
throw new Error('No user data received from CSES');
if (users) {
const success = await updateMongoDB(users);
console.log('Update completed:', success ? 'successful' : 'failed');
return success;
} else {
console.log('No user data fetched');
return false;
}

await updateMongoDB(users);
console.log('Leaderboard update completed successfully');
return true;
} catch (error) {
console.error('Error updating leaderboard:', error);
throw error;
console.error('Error in updateLeaderboard:', error.message);
return false;
}
}

Expand Down
Binary file added images/profile.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
52 changes: 52 additions & 0 deletions index.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Rubik:ital,wght@0,300..900;1,300..900&family=Source+Code+Pro:ital,wght@0,200..900;1,200..900&display=swap" rel="stylesheet">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Leaderboard</title>
<link rel="stylesheet" href="leaderboard.css">
</head>
<body>
<div class="leaderboard">
<h1 class="leaderboard-title">Leaderboard</h1>
<table class="leaderboard-table">
<thead>
<tr>
<th>Rank</th>
<th>Name</th>
<th>Activity</th>
<th>Streak</th>
<th>Question Solved</th>
</tr>
</thead>
<tbody>


<% for (let index = 0; index < data.length; index++) { %>
<tr>
<td>#<%= index +1 %></td>
<td><%= data[index].name %></td>
<td>
<div class="activity-grid">
<% data[index].timeline.forEach(element => { %>
<% if(element) { %>
<div class="active"></div>
<% } else { %>
<div></div>
<% } %>
<% }); %>
</div>
</td>
<td><%= data[index].streak %></td>
<td><%= data[index].questionSolved %></td>

</tr>
<% } %>
</tbody>
</table>
</div>
</body>
</html>
Loading