Spaces:
Running
Running
File size: 13,044 Bytes
6854504 8a3694b 6854504 71405d9 8a3694b 71405d9 6854504 71405d9 8a3694b 71405d9 6854504 71405d9 8a3694b 71405d9 6854504 71405d9 8a3694b 71405d9 8a3694b 71405d9 8a3694b 6854504 8a3694b 6854504 8a3694b 6854504 8a3694b 6854504 8a3694b 6854504 | 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 | import express from "express";
import cors from "cors";
import dotenv from "dotenv";
import fs from "fs";
import path from "path";
import { MongoClient } from "mongodb";
// Load environment variables
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3001;
const ADMIN_PASSWORD = process.env.ACTIVITY_PASSWORD || process.env.ADMIN_PASSWORD || "admin123";
// Middleware
app.use(cors());
app.use(express.json());
// Database configuration
const MONGODB_URI = process.env.MONGODB_URI;
const DB_NAME = process.env.DB_NAME || "pranabesh_portfolio";
const DATA_DIR = path.join(process.cwd(), "data");
const FILE_DB_PATH = path.join(DATA_DIR, "db.json");
let dbClient = null;
let useMongo = false;
// Initialize database connection
async function initDb() {
if (MONGODB_URI) {
try {
dbClient = new MongoClient(MONGODB_URI);
await dbClient.connect();
useMongo = true;
console.log("π Connected successfully to MongoDB Atlas database");
} catch (err) {
console.error("β Failed to connect to MongoDB, falling back to local file storage:", err);
}
}
if (!useMongo) {
try {
if (!fs.existsSync(DATA_DIR)) {
fs.mkdirSync(DATA_DIR, { recursive: true });
}
if (!fs.existsSync(FILE_DB_PATH)) {
const initialData = {
highscores: {},
activity: {
moodId: "coding",
updatedAt: new Date().toISOString()
}
};
fs.writeFileSync(FILE_DB_PATH, JSON.stringify(initialData, null, 2));
}
console.log(`π Using local JSON file storage at ${FILE_DB_PATH}`);
} catch (err) {
console.error("β Error setting up local JSON file database:", err);
}
}
}
// DB Helpers for Highscores
async function getHighScores() {
if (useMongo) {
try {
const db = dbClient.db(DB_NAME);
const collection = db.collection("highscores");
const list = await collection.find({}).toArray();
const scores = {};
list.forEach((item) => {
scores[item.gameKey] = {
score: item.score,
player: item.player,
timestamp: item.timestamp
};
});
return scores;
} catch (err) {
console.error("Error reading highscores from MongoDB:", err);
return {};
}
} else {
try {
const raw = fs.readFileSync(FILE_DB_PATH, "utf-8");
const data = JSON.parse(raw);
return data.highscores || {};
} catch (err) {
console.error("Error reading local highscores:", err);
return {};
}
}
}
async function updateHighScore(gameKey, score, player, lowerIsBetter) {
const timestamp = Date.now();
if (useMongo) {
const db = dbClient.db(DB_NAME);
const collection = db.collection("highscores");
const existing = await collection.findOne({ gameKey });
let isBetter = false;
if (!existing) {
isBetter = true;
} else {
isBetter = lowerIsBetter ? (score < existing.score) : (score > existing.score);
}
if (isBetter) {
const updatedRecord = { score, player, timestamp };
await collection.updateOne(
{ gameKey },
{ $set: updatedRecord },
{ upsert: true }
);
return { isUpdated: true, record: updatedRecord };
}
return { isUpdated: false, record: existing };
} else {
const raw = fs.readFileSync(FILE_DB_PATH, "utf-8");
const data = JSON.parse(raw);
const existing = data.highscores[gameKey];
let isBetter = false;
if (!existing) {
isBetter = true;
} else {
isBetter = lowerIsBetter ? (score < existing.score) : (score > existing.score);
}
if (isBetter) {
const updatedRecord = { score, player, timestamp };
data.highscores[gameKey] = updatedRecord;
fs.writeFileSync(FILE_DB_PATH, JSON.stringify(data, null, 2));
return { isUpdated: true, record: updatedRecord };
}
return { isUpdated: false, record: existing };
}
}
const MOOD_LABELS = {
coding: "CODING",
coffee: "CAFFEINATING",
eating: "REGAINING HP",
sleeping: "SLEEP MODE",
thinking: "BRAINSTORMING",
music: "LOW-FI VIBES",
gaming: "GRINDING",
bug: "BUG HUNTING",
rocket: "DEPLOYING",
chill: "CHILLING",
fire: "ON FIRE",
bash: "SH_MODE",
reading: "LD_LEARNING",
writing: "ARCHITECTING",
search: "RESEARCHING",
battery: "RECHARGING",
cloud: "IN THE CLOUD",
heart: "OPTIMISTIC",
success: "ACHIEVING",
lock: "SECURE"
};
// Generates exactly 500 tech developer statuses
function getGeneratedStatuses() {
const actions = [
{ text: "Debugging", mood: "bug" },
{ text: "Refactoring", mood: "coding" },
{ text: "Compiling", mood: "bash" },
{ text: "Optimizing", mood: "fire" },
{ text: "Squashing", mood: "bug" },
{ text: "Reviewing", mood: "reading" },
{ text: "Architecting", mood: "writing" },
{ text: "Tuning", mood: "battery" },
{ text: "Monitoring", mood: "lock" },
{ text: "Deploying", mood: "rocket" },
{ text: "Rewriting", mood: "coding" },
{ text: "Analyzing", mood: "search" },
{ text: "Diagnosing", mood: "thinking" },
{ text: "Fixing", mood: "bug" },
{ text: "Tracing", mood: "search" },
{ text: "Testing", mood: "success" },
{ text: "Securing", mood: "lock" },
{ text: "Scaling", mood: "cloud" },
{ text: "Patching", mood: "rocket" },
{ text: "Mocking", mood: "coding" }
];
const subjects = [
"null pointers",
"memory leaks",
"legacy spaghetti",
"Docker containers",
"Kubernetes pods",
"SQL injections",
"CORS policies",
"Git merge conflicts",
"500 Internal Errors",
"flaky unit tests",
"API specifications",
"CSS flexbox centering",
"TypeScript type errors",
"WebSocket handlers",
"out of memory crashes",
"CI/CD pipelines",
"Redis cache misses",
"expired JWT tokens",
"infinite loops",
"YAML configurations",
"microservices mesh",
"garbage collection runs",
"DNS resolution failures",
"Webpack configurations",
"auth middleware"
];
const contexts = [
"in production",
"at 3:00 AM",
"fueled by espresso",
"in slow motion",
"for the final release",
"to hit five nines",
"without any comments",
"using stack overflow",
"like a 10x developer",
"inside Docker container",
"locally on my machine",
"on Cloudflare edge",
"while listening to lo-fi",
"to prevent page collapse",
"for a client demo",
"without dev testing",
"using experimental flags",
"hoping it doesn't break",
"with fingers crossed",
"under extreme pressure"
];
const list = [];
// Create 500 distinct combinations
for (let i = 0; i < 500; i++) {
const actionIdx = (i * 7) % actions.length;
const subjectIdx = (i * 13) % subjects.length;
const contextIdx = (i * 17) % contexts.length;
const action = actions[actionIdx];
const subject = subjects[subjectIdx];
const context = contexts[contextIdx];
list.push({
label: `${action.text} ${subject} ${context}`.toUpperCase(),
moodId: action.mood
});
}
// Pre-seed high quality overrides
const staticStatuses = [
{ label: "CAFFEINATING HARD", moodId: "coffee" },
{ label: "SIP OF HOT ESPRESSO", moodId: "coffee" },
{ label: "REGAINING HP (RAMEN)", moodId: "eating" },
{ label: "RELOADING CARBS", moodId: "eating" },
{ label: "SLEEP MODE ENABLED", moodId: "sleeping" },
{ label: "DREAMING OF SYNTAX", moodId: "sleeping" },
{ label: "BRAINSTORMING V2", moodId: "thinking" },
{ label: "THINKING IN BINARY", moodId: "thinking" },
{ label: "LOW-FI MUSIC VIBES", moodId: "music" },
{ label: "SYNTHWAVE PLAYLIST", moodId: "music" },
{ label: "GAMING (GRINDING)", moodId: "gaming" },
{ label: "CLEARING SIDE QUESTS", moodId: "gaming" },
{ label: "CHILLING BY THE POOL", moodId: "chill" },
{ label: "DOING ABSOLUTELY NOTHING", moodId: "chill" },
{ label: "ON FIRE (1000 WPM)", moodId: "fire" },
{ label: "UNSTOPPABLE CODING", moodId: "fire" },
{ label: "READING RFC SPECS", moodId: "reading" },
{ label: "LEARNING RUST GEMS", moodId: "reading" },
{ label: "SECURE NODE NETWORKS", moodId: "lock" },
{ label: "ROTATING TLS CERTIFICATES", moodId: "lock" }
];
staticStatuses.forEach((status, idx) => {
const targetIdx = (idx * 23) % 500;
list[targetIdx] = status;
});
return list;
}
const generatedStatuses = getGeneratedStatuses();
// DB Helpers for Current Activity
async function getActivity() {
let activeMoodId = null;
let activeLabel = null;
let updatedAt = null;
if (useMongo) {
try {
const db = dbClient.db(DB_NAME);
const collection = db.collection("activity");
const doc = await collection.findOne({ key: "current" });
if (doc) {
activeMoodId = doc.moodId;
activeLabel = doc.label;
updatedAt = doc.updatedAt;
}
} catch (err) {
console.error("Error reading activity from MongoDB:", err);
}
} else {
try {
const raw = fs.readFileSync(FILE_DB_PATH, "utf-8");
const data = JSON.parse(raw);
if (data.activity) {
activeMoodId = data.activity.moodId;
activeLabel = data.activity.label;
updatedAt = data.activity.updatedAt;
}
} catch (err) {
console.error("Error reading local activity:", err);
}
}
// 30 minute manual override decay check (1800000ms)
const DECAY_MS = 30 * 60 * 1000;
const isExpired = updatedAt && (Date.now() - new Date(updatedAt).getTime() > DECAY_MS);
// If no manual override is set, if set to "auto", or if manual status has expired (>30 mins)
if (!activeMoodId || activeMoodId === "auto" || isExpired) {
// Rotate every 30 minutes (1800000ms)
const seed = Math.floor(Date.now() / 1800000);
const index = seed % generatedStatuses.length;
const status = generatedStatuses[index];
activeMoodId = status.moodId;
activeLabel = status.label;
updatedAt = new Date(seed * 1800000).toISOString();
}
return { moodId: activeMoodId, label: activeLabel, updatedAt };
}
async function updateActivity(moodId) {
const updatedAt = new Date().toISOString();
const label = MOOD_LABELS[moodId] || "AUTO ROTATE";
if (useMongo) {
const db = dbClient.db(DB_NAME);
const collection = db.collection("activity");
await collection.updateOne(
{ key: "current" },
{ $set: { moodId, label, updatedAt } },
{ upsert: true }
);
} else {
const raw = fs.readFileSync(FILE_DB_PATH, "utf-8");
const data = JSON.parse(raw);
data.activity = { moodId, label, updatedAt };
fs.writeFileSync(FILE_DB_PATH, JSON.stringify(data, null, 2));
}
return { moodId, label, updatedAt };
}
// API Routes
// 1. Highscores
app.get("/api/highscores", async (req, res) => {
try {
const scores = await getHighScores();
res.json(scores);
} catch (err) {
console.error("Error in GET /api/highscores:", err);
res.status(500).json({ error: "Failed to retrieve highscores" });
}
});
app.post("/api/highscores", async (req, res) => {
try {
const { gameKey, score, player, lowerIsBetter } = req.body;
if (!gameKey || score === undefined || !player) {
return res.status(400).json({ error: "Missing required fields (gameKey, score, player)" });
}
const cleanPlayer = String(player).substring(0, 3).toUpperCase();
const parsedScore = Number(score);
if (isNaN(parsedScore)) {
return res.status(400).json({ error: "Score must be a valid number" });
}
const result = await updateHighScore(gameKey, parsedScore, cleanPlayer, !!lowerIsBetter);
res.json({
success: true,
isNewRecord: result.isUpdated,
highscore: result.record
});
} catch (err) {
console.error("Error in POST /api/highscores:", err);
res.status(500).json({ error: "Failed to update highscore" });
}
});
// 2. Current Activity
app.get("/api/activity", async (req, res) => {
try {
const activity = await getActivity();
res.json(activity);
} catch (err) {
console.error("Error in GET /api/activity:", err);
res.status(500).json({ error: "Failed to retrieve activity" });
}
});
app.post("/api/activity", async (req, res) => {
try {
const { moodId, passcode } = req.body;
if (!moodId) {
return res.status(400).json({ error: "Missing moodId" });
}
if (passcode !== ADMIN_PASSWORD) {
return res.status(401).json({ error: "Unauthorized: Invalid passcode" });
}
const updatedActivity = await updateActivity(moodId);
res.json({
success: true,
activity: updatedActivity
});
} catch (err) {
console.error("Error in POST /api/activity:", err);
res.status(500).json({ error: "Failed to update activity" });
}
});
// Start server after initializing DB
initDb().then(() => {
app.listen(PORT, () => {
console.log(`π Server running on port ${PORT}`);
});
});
|