Spaces:
Running
Running
Download server.js from pranz29/portfolio-api: direct link, hf CLI and curl.
- Browser
- Download file 13 kB
-
https://huggingface.co/spaces/pranz29/portfolio-api/resolve/main/server.js
- Command line
-
hf download hf://spaces/pranz29/portfolio-api/server.js
-
curl -L -o server.js https://huggingface.co/spaces/pranz29/portfolio-api/resolve/main/server.js
13 kB
| 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}`); | |
| }); | |
| }); | |