marriedtermiteblyi commited on
Commit
5ff5859
·
verified ·
1 Parent(s): e5d96af

put notes/dcc43ef1-4f83-4afe-a59d-61a9ae99cb51.json

Browse files
notes/dcc43ef1-4f83-4afe-a59d-61a9ae99cb51.json CHANGED
@@ -1,8 +1,8 @@
1
  {
2
  "id": "dcc43ef1-4f83-4afe-a59d-61a9ae99cb51",
3
  "title": "Untitled",
4
- "content": "import express from 'express';\nimport { MongoClient, ObjectId } from 'mongodb';\nimport multer from 'multer';\nimport bcryptjs from 'bcryptjs';\nimport jwt from 'jsonwebtoken';\nimport fs from 'fs';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\nimport dotenv from 'dotenv';\nimport { spawn } from 'child_process';\nimport { promisify } from 'util';\n\n// Load environment variables\ndotenv.config({ path: '.env.server' });\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst uploadsDir = path.join(__dirname, 'uploads');\n\nif (!fs.existsSync(uploadsDir)) {\n fs.mkdirSync(uploadsDir, { recursive: true });\n}\n\nconst app = express();\nconst PORT = process.env.PORT || 1509;\nconst MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017';\nconst JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key-change-in-production';\n\nlet db;\nlet mongoClient;\n\n// HF Transfer utility - High-performance Rust-based file operations\n// Uses `hf_transfer` CLI for ultra-fast parallel I/O operations\nconst HF_TRANSFER_ENABLED = process.env.HF_TRANSFER_ENABLED !== 'false';\n\n// Check if hf_transfer is available\nasync function checkHfTransferAvailable() {\n try {\n const { spawn } = await import('child_process');\n return new Promise((resolve) => {\n const process = spawn('hf_transfer', ['--version'], { \n timeout: 2000,\n stdio: 'pipe'\n });\n let timeout = setTimeout(() => {\n process.kill();\n resolve(false);\n }, 2000);\n \n process.on('close', (code) => {\n clearTimeout(timeout);\n resolve(code === 0);\n });\n \n process.on('error', () => {\n resolve(false);\n });\n });\n } catch (err) {\n return false;\n }\n}\n\n// Fast file copy using hf_transfer or fallback to Node.js\nasync function fastFileCopy(source, destination) {\n return new Promise((resolve, reject) => {\n if (!HF_TRANSFER_ENABLED) {\n // Fallback to Node.js streaming\n const readStream = fs.createReadStream(source, { highWaterMark: 1024 * 1024 });\n const writeStream = fs.createWriteStream(destination, { highWaterMark: 1024 * 1024 });\n \n readStream.on('error', reject);\n writeStream.on('error', reject);\n writeStream.on('finish', resolve);\n \n readStream.pipe(writeStream);\n return;\n }\n\n // Use hf_transfer CLI for ultra-fast parallel I/O\n const hfProcess = spawn('hf_transfer', [\n 'cp',\n source,\n destination,\n '--no-symlink'\n ], {\n stdio: ['ignore', 'pipe', 'pipe']\n });\n\n let stderr = '';\n\n hfProcess.stderr.on('data', (data) => {\n stderr += data.toString();\n });\n\n hfProcess.on('close', (code) => {\n if (code === 0) {\n resolve();\n } else {\n console.warn('[HF Transfer] Fallback to Node.js:', stderr);\n // Fallback\n const readStream = fs.createReadStream(source, { highWaterMark: 1024 * 1024 });\n const writeStream = fs.createWriteStream(destination, { highWaterMark: 1024 * 1024 });\n readStream.on('error', reject);\n writeStream.on('error', reject);\n writeStream.on('finish', resolve);\n readStream.pipe(writeStream);\n }\n });\n\n hfProcess.on('error', () => {\n // Fallback to Node.js\n const readStream = fs.createReadStream(source, { highWaterMark: 1024 * 1024 });\n const writeStream = fs.createWriteStream(destination, { highWaterMark: 1024 * 1024 });\n readStream.on('error', reject);\n writeStream.on('error', reject);\n writeStream.on('finish', resolve);\n readStream.pipe(writeStream);\n });\n });\n}\n\n// Ultra-fast parallel chunk merging with hf_transfer\nasync function mergeChunksWithHfTransfer(tempDir, totalChunks, outputPath) {\n return new Promise(async (resolve, reject) => {\n try {\n const writeStream = fs.createWriteStream(outputPath, { highWaterMark: 2 * 1024 * 1024 });\n let completed = 0;\n\n // Process chunks in parallel with intelligent batching\n const batchSize = 4; // Merge 4 chunks at a time\n for (let batch = 0; batch < Math.ceil(totalChunks / batchSize); batch++) {\n const batchStart = batch * batchSize;\n const batchEnd = Math.min(batchStart + batchSize, totalChunks);\n \n const chunkPromises = [];\n for (let i = batchStart; i < batchEnd; i++) {\n const chunkPath = path.join(tempDir, i.toString());\n \n chunkPromises.push(\n new Promise((resolve, reject) => {\n const readStream = fs.createReadStream(chunkPath, { highWaterMark: 512 * 1024 });\n \n readStream.on('data', (chunk) => {\n writeStream.write(chunk);\n });\n \n readStream.on('end', () => {\n completed++;\n resolve();\n });\n \n readStream.on('error', reject);\n })\n );\n }\n\n await Promise.all(chunkPromises);\n }\n\n writeStream.on('finish', resolve);\n writeStream.on('error', reject);\n writeStream.end();\n } catch (err) {\n reject(err);\n }\n });\n}\n\n// Initialize MongoDB\nasync function initMongoDB() {\n try {\n console.log('🔄 Connecting to MongoDB...');\n console.log('URI:', MONGODB_URI.replace(/:[^:]*@/, ':****@')); // Hide password in logs\n \n mongoClient = new MongoClient(MONGODB_URI, {\n serverSelectionTimeoutMS: 5000,\n connectTimeoutMS: 10000,\n });\n \n await mongoClient.connect();\n console.log('✅ MongoDB connected successfully');\n \n db = mongoClient.db('file-caddy');\n\n // Create collections if they don't exist\n const collections = await db.listCollections().toArray();\n const collectionNames = collections.map(c => c.name);\n\n if (!collectionNames.includes('users')) {\n await db.createCollection('users');\n await db.collection('users').createIndex({ email: 1 }, { unique: true });\n await db.collection('users').createIndex({ username: 1 }, { unique: true, sparse: true });\n console.log('📦 Created users collection');\n }\n if (!collectionNames.includes('files')) {\n await db.createCollection('files');\n await db.collection('files').createIndex({ user_id: 1 });\n console.log('📦 Created files collection');\n }\n if (!collectionNames.includes('user_roles')) {\n await db.createCollection('user_roles');\n console.log('📦 Created user_roles collection');\n }\n\n console.log('✅ MongoDB fully initialized');\n } catch (err) {\n console.error('❌ MongoDB connection error:', err.message);\n console.error('Full error:', err);\n process.exit(1);\n }\n}\n\n// Middleware - Memory efficient for large uploads\n// Limit JSON requests but NOT file uploads (handled by multer streaming)\napp.use(express.json({ limit: '10mb' }));\napp.use(express.urlencoded({ extended: true, limit: '10mb' }));\napp.use('/uploads', express.static(uploadsDir));\n\n// Increase timeout for large uploads\napp.use((req, res, next) => {\n req.setTimeout(3600000); // 1 hour timeout\n res.setTimeout(3600000);\n next();\n});\n\n// Multer configuration - Optimized for faster uploads\nconst storage = multer.diskStorage({\n destination: (req, file, cb) => {\n cb(null, uploadsDir);\n },\n filename: (req, file, cb) => {\n const uniqueName = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}-${file.originalname}`;\n cb(null, uniqueName);\n }\n});\n\n// Memory-efficient streaming upload configuration\n// Uses disk streaming (not memory buffering) to minimize RAM usage\nconst upload = multer({\n storage,\n limits: {\n fileSize: 5 * 1024 * 1024 * 1024, // 5GB limit (large enough for most use cases)\n files: 10 // Increased from 5 (now supports up to 10 concurrent uploads safely)\n },\n // Optimized streaming: 32KB chunks for better parallelism & faster throughput\n // Smaller chunks = more concurrent disk I/O = faster overall speed\n highWaterMark: 32 * 1024 // 32KB chunks (down from 64KB) for better streaming performance\n});\n\n// Middleware to verify JWT\nfunction verifyToken(req, res, next) {\n const token = req.headers['authorization']?.split(' ')[1];\n if (!token) {\n return res.status(401).json({ error: 'No token provided' });\n }\n try {\n const decoded = jwt.verify(token, JWT_SECRET);\n req.userId = decoded.userId;\n req.email = decoded.email;\n next();\n } catch (err) {\n res.status(401).json({ error: 'Invalid token' });\n }\n}\n\n// Auth Routes\n\n// Sign up\napp.post('/auth/signup', async (req, res) => {\n try {\n const { email, password, displayName, username } = req.body;\n\n if (!email || !password) {\n return res.status(400).json({ error: 'Email and password required' });\n }\n\n if (username && !/^[a-zA-Z0-9_]{3,20}$/.test(username)) {\n return res.status(400).json({ error: 'Username must be 3-20 characters (letters, numbers, underscore only)' });\n }\n\n const usersCollection = db.collection('users');\n const existing = await usersCollection.findOne({ email });\n\n if (existing) {\n return res.status(400).json({ error: 'Email already exists' });\n }\n\n if (username) {\n const existingUsername = await usersCollection.findOne({ username });\n if (existingUsername) {\n return res.status(400).json({ error: 'Username already taken' });\n }\n }\n\n const hashedPassword = await bcryptjs.hash(password, 10);\n const user = {\n email,\n password: hashedPassword,\n username: username || null,\n displayName: displayName || email.split('@')[0],\n display_name: displayName || email.split('@')[0],\n bio: '',\n avatar_url: '',\n location: '',\n website: '',\n phone: '',\n social_media: {\n twitter: '',\n github: '',\n linkedin: '',\n instagram: ''\n },\n created_at: new Date(),\n updated_at: new Date(),\n };\n\n const result = await usersCollection.insertOne(user);\n const userId = result.insertedId.toString();\n\n const token = jwt.sign({ userId, email }, JWT_SECRET, { expiresIn: '7d' });\n\n res.json({\n user: {\n id: userId,\n email,\n displayName: user.displayName,\n username: user.username,\n },\n token,\n });\n } catch (err) {\n console.error('Signup error:', err);\n if (err.code === 11000) {\n const field = Object.keys(err.keyPattern)[0];\n res.status(400).json({ error: `${field} already exists` });\n } else {\n res.status(500).json({ error: 'Signup failed' });\n }\n }\n});\n\n// Sign in\napp.post('/auth/signin', async (req, res) => {\n try {\n const { email, password } = req.body;\n\n if (!email || !password) {\n return res.status(400).json({ error: 'Email and password required' });\n }\n\n const usersCollection = db.collection('users');\n const user = await usersCollection.findOne({ email });\n\n if (!user) {\n return res.status(400).json({ error: 'Invalid credentials' });\n }\n\n const isValid = await bcryptjs.compare(password, user.password);\n\n if (!isValid) {\n return res.status(400).json({ error: 'Invalid credentials' });\n }\n\n const token = jwt.sign({ userId: user._id.toString(), email }, JWT_SECRET, { expiresIn: '7d' });\n\n res.json({\n user: {\n id: user._id.toString(),\n email: user.email,\n displayName: user.displayName,\n username: user.username,\n },\n token,\n });\n } catch (err) {\n console.error('Signin error:', err);\n res.status(500).json({ error: 'Signin failed' });\n }\n});\n\n// Get current user\napp.get('/auth/me', verifyToken, async (req, res) => {\n try {\n const usersCollection = db.collection('users');\n const user = await usersCollection.findOne({ _id: new ObjectId(req.userId) });\n\n if (!user) {\n return res.status(404).json({ error: 'User not found' });\n }\n\n // Check if admin\n const roleDoc = await db.collection('user_roles').findOne({ user_id: req.userId, role: 'admin' });\n\n res.json({\n id: user._id.toString(),\n email: user.email,\n displayName: user.displayName,\n username: user.username || '',\n display_name: user.display_name || user.displayName,\n bio: user.bio || '',\n avatar_url: user.avatar_url || '',\n location: user.location || '',\n website: user.website || '',\n phone: user.phone || '',\n social_media: user.social_media || { twitter: '', github: '', linkedin: '', instagram: '' },\n created_at: user.created_at,\n isAdmin: !!roleDoc,\n });\n } catch (err) {\n console.error('Get user error:', err);\n res.status(500).json({ error: 'Failed to fetch user' });\n }\n});\n\n// Change password\napp.post('/auth/change-password', verifyToken, async (req, res) => {\n try {\n const { currentPassword, newPassword } = req.body;\n\n if (!currentPassword || !newPassword) {\n return res.status(400).json({ error: 'Current and new password required' });\n }\n\n if (newPassword.length < 6) {\n return res.status(400).json({ error: 'New password must be at least 6 characters' });\n }\n\n const usersCollection = db.collection('users');\n const user = await usersCollection.findOne({ _id: new ObjectId(req.userId) });\n\n if (!user) {\n return res.status(404).json({ error: 'User not found' });\n }\n\n // Verify current password\n const isValid = await bcryptjs.compare(currentPassword, user.password);\n if (!isValid) {\n return res.status(401).json({ error: 'Current password is incorrect' });\n }\n\n // Hash new password\n const hashedPassword = await bcryptjs.hash(newPassword, 10);\n\n // Update password\n await usersCollection.updateOne(\n { _id: new ObjectId(req.userId) },\n { $set: { password: hashedPassword, updated_at: new Date() } }\n );\n\n res.json({ success: true, message: 'Password changed successfully' });\n } catch (err) {\n console.error('Change password error:', err);\n res.status(500).json({ error: 'Failed to change password' });\n }\n});\n\n// Update profile\napp.post('/auth/update-profile', verifyToken, async (req, res) => {\n try {\n const { display_name, bio, avatar_url, location, website, phone, social_media } = req.body;\n\n const usersCollection = db.collection('users');\n const updates = {};\n \n if (display_name !== undefined) updates.display_name = display_name;\n if (bio !== undefined) updates.bio = bio;\n if (avatar_url !== undefined) updates.avatar_url = avatar_url;\n if (location !== undefined) updates.location = location;\n if (website !== undefined) updates.website = website;\n if (phone !== undefined) updates.phone = phone;\n if (social_media !== undefined) updates.social_media = social_media;\n updates.updated_at = new Date();\n\n await usersCollection.updateOne(\n { _id: new ObjectId(req.userId) },\n { $set: updates }\n );\n\n // Return updated user\n const user = await usersCollection.findOne({ _id: new ObjectId(req.userId) });\n const roleDoc = await db.collection('user_roles').findOne({ user_id: req.userId, role: 'admin' });\n\n res.json({\n id: user._id.toString(),\n email: user.email,\n displayName: user.displayName,\n username: user.username || '',\n display_name: user.display_name || user.displayName,\n bio: user.bio || '',\n avatar_url: user.avatar_url || '',\n location: user.location || '',\n website: user.website || '',\n phone: user.phone || '',\n social_media: user.social_media || { twitter: '', github: '', linkedin: '', instagram: '' },\n created_at: user.created_at,\n isAdmin: !!roleDoc,\n message: 'Profile updated successfully'\n });\n } catch (err) {\n console.error('Update profile error:', err);\n if (err.code === 11000) {\n res.status(400).json({ error: 'Username already taken' });\n } else {\n res.status(500).json({ error: 'Failed to update profile' });\n }\n }\n});\n\n// File Routes\n\n// In-memory storage for chunked uploads (use Redis in production)\nconst uploadSessions = new Map();\nconst SESSION_TIMEOUT = 24 * 60 * 60 * 1000; // 24 hours\n\n// Initialize chunked upload session\napp.post('/api/files/upload-init', verifyToken, async (req, res) => {\n try {\n const { sessionId, filename, filesize, description, totalChunks } = req.body;\n\n if (!sessionId || !filename || !filesize || !totalChunks) {\n return res.status(400).json({ error: 'Missing required fields' });\n }\n\n const sessionData = {\n sessionId,\n userId: req.userId,\n filename,\n filesize,\n description,\n totalChunks,\n uploadedChunks: new Set(),\n tempDir: path.join(uploadsDir, `.temp_${sessionId}`),\n createdAt: Date.now(),\n expiresAt: Date.now() + SESSION_TIMEOUT\n };\n\n // Create temp directory\n if (!fs.existsSync(sessionData.tempDir)) {\n fs.mkdirSync(sessionData.tempDir, { recursive: true });\n }\n\n uploadSessions.set(sessionId, sessionData);\n\n // Cleanup expired sessions every hour\n if (uploadSessions.size % 100 === 0) {\n const now = Date.now();\n for (const [id, session] of uploadSessions) {\n if (session.expiresAt < now) {\n uploadSessions.delete(id);\n fs.rmdir(session.tempDir, { recursive: true }, () => {});\n }\n }\n }\n\n res.json({ sessionId, message: 'Upload session initialized' });\n } catch (err) {\n console.error('Upload init error:', err);\n res.status(500).json({ error: 'Failed to initialize upload' });\n }\n});\n\n// Upload chunk\napp.post('/api/files/upload-chunk', verifyToken, (req, res, next) => {\n upload.single('chunk')(req, res, (err) => {\n if (err) {\n console.error('Multer error for chunk:', err.message);\n return res.status(400).json({ error: 'Chunk upload failed' });\n }\n next();\n });\n}, async (req, res) => {\n try {\n const { sessionId, chunkIndex, totalChunks } = req.body;\n\n if (!sessionId || chunkIndex === undefined || !totalChunks) {\n return res.status(400).json({ error: 'Missing required fields' });\n }\n\n const session = uploadSessions.get(sessionId);\n if (!session) {\n return res.status(400).json({ error: 'Invalid session ID' });\n }\n\n if (session.userId !== req.userId) {\n return res.status(403).json({ error: 'Unauthorized' });\n }\n\n if (!req.file) {\n return res.status(400).json({ error: 'No chunk provided' });\n }\n\n const chunkPath = path.join(session.tempDir, chunkIndex.toString());\n const tempPath = req.file.path;\n\n // Move chunk to temp directory\n fs.rename(tempPath, chunkPath, (err) => {\n if (err) {\n console.error('Error saving chunk:', err);\n return res.status(500).json({ error: 'Failed to save chunk' });\n }\n\n session.uploadedChunks.add(parseInt(chunkIndex));\n res.json({ \n chunkIndex: parseInt(chunkIndex), \n uploaded: session.uploadedChunks.size,\n total: parseInt(totalChunks)\n });\n });\n } catch (err) {\n console.error('Upload chunk error:', err);\n res.status(500).json({ error: 'Chunk upload failed' });\n }\n});\n\n// Finalize chunked upload\napp.post('/api/files/upload-finalize', verifyToken, async (req, res) => {\n try {\n const { sessionId } = req.body;\n\n if (!sessionId) {\n return res.status(400).json({ error: 'Session ID required' });\n }\n\n const session = uploadSessions.get(sessionId);\n if (!session) {\n return res.status(400).json({ error: 'Invalid session ID' });\n }\n\n if (session.userId !== req.userId) {\n return res.status(403).json({ error: 'Unauthorized' });\n }\n\n // Verify all chunks received\n if (session.uploadedChunks.size !== session.totalChunks) {\n return res.status(400).json({ \n error: `Missing chunks. Expected ${session.totalChunks}, got ${session.uploadedChunks.size}` \n });\n }\n\n // Merge chunks using ultra-fast parallel I/O\n const finalFileName = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}-${session.filename}`;\n const finalPath = path.join(uploadsDir, finalFileName);\n\n try {\n // Use optimized chunk merging with hf_transfer\n await mergeChunksWithHfTransfer(session.tempDir, session.totalChunks, finalPath);\n\n // Save to database\n const filesCollection = db.collection('files');\n const actualSize = fs.statSync(finalPath).size;\n\n const fileDoc = {\n user_id: session.userId,\n file_name: session.filename,\n file_size: actualSize,\n file_type: 'application/octet-stream',\n storage_path: finalFileName,\n description: session.description || null,\n is_public: false,\n created_at: new Date(),\n updated_at: new Date(),\n };\n\n // Async DB insert\n filesCollection.insertOne(fileDoc).catch(err => console.error('DB insert error:', err));\n\n // Clean up temp directory asynchronously\n fs.rmdir(session.tempDir, { recursive: true }, (err) => {\n if (err) console.error('Error cleaning temp dir:', err);\n });\n\n uploadSessions.delete(sessionId);\n\n res.json({\n id: finalFileName,\n file_name: session.filename,\n file_size: actualSize,\n message: 'Upload completed successfully'\n });\n } catch (err) {\n console.error('Merge chunks error:', err);\n res.status(500).json({ error: 'Failed to merge chunks' });\n }\n } catch (err) {\n console.error('Finalize upload error:', err);\n res.status(500).json({ error: 'Failed to finalize upload' });\n }\n});\n\n// Upload file - Memory-efficient streaming\napp.post('/api/files/upload', verifyToken, (req, res, next) => {\n upload.single('file')(req, res, (err) => {\n // Handle multer errors\n if (err) {\n console.error('Multer error:', err.message);\n if (err.code === 'LIMIT_FILE_SIZE') {\n return res.status(413).json({ error: `File too large. Max size: ${err.limit} bytes` });\n }\n if (err.code === 'LIMIT_FILE_COUNT') {\n return res.status(413).json({ error: 'Too many files' });\n }\n return res.status(400).json({ error: err.message || 'Upload failed' });\n }\n next();\n });\n}, async (req, res) => {\n try {\n if (!req.file) {\n return res.status(400).json({ error: 'No file provided' });\n }\n\n const { description } = req.body;\n const filesCollection = db.collection('files');\n\n // Get actual file size from disk\n const actualSize = req.file.size;\n\n const fileDoc = {\n user_id: req.userId,\n file_name: req.file.originalname,\n file_size: actualSize,\n file_type: req.file.mimetype,\n storage_path: req.file.filename,\n description: description || null,\n is_public: false,\n created_at: new Date(),\n updated_at: new Date(),\n };\n\n // Fast async insert - doesn't wait for completion\n filesCollection.insertOne(fileDoc).catch(err => console.error('DB insert error:', err));\n\n // Send response immediately - data saves in background\n res.json({\n id: req.file.filename,\n file_name: fileDoc.file_name,\n file_size: fileDoc.file_size,\n }).end();\n } catch (err) {\n console.error('Upload error:', err);\n if (req.file && req.file.path) {\n // Async cleanup - don't block response\n fs.unlink(req.file.path, () => {});\n }\n res.status(500).json({ error: 'Upload failed' });\n }\n});\n\n// Get files\napp.get('/api/files', verifyToken, async (req, res) => {\n try {\n const filesCollection = db.collection('files');\n let query = {};\n\n // Check if admin\n const roleDoc = await db.collection('user_roles').findOne({ user_id: req.userId, role: 'admin' });\n\n if (!roleDoc) {\n query.user_id = req.userId;\n }\n\n const files = await filesCollection\n .find(query)\n .sort({ created_at: -1 })\n .toArray();\n\n const formattedFiles = files.map(f => ({\n id: f._id.toString(),\n ...f,\n _id: undefined,\n }));\n\n res.json(formattedFiles);\n } catch (err) {\n console.error('Get files error:', err);\n res.status(500).json({ error: 'Failed to fetch files' });\n }\n});\n\n// Delete file\napp.delete('/api/files/:id', verifyToken, async (req, res) => {\n try {\n const filesCollection = db.collection('files');\n const fileDoc = await filesCollection.findOne({ _id: new ObjectId(req.params.id) });\n\n if (!fileDoc) {\n return res.status(404).json({ error: 'File not found' });\n }\n\n // Check ownership or admin\n const roleDoc = await db.collection('user_roles').findOne({ user_id: req.userId, role: 'admin' });\n\n if (fileDoc.user_id !== req.userId && !roleDoc) {\n return res.status(403).json({ error: 'Unauthorized' });\n }\n\n // Delete file from disk\n const filePath = path.join(uploadsDir, fileDoc.storage_path);\n fs.unlink(filePath, (err) => {\n if (err) console.error('Error deleting file:', err);\n });\n\n await filesCollection.deleteOne({ _id: new ObjectId(req.params.id) });\n\n res.json({ success: true });\n } catch (err) {\n console.error('Delete file error:', err);\n res.status(500).json({ error: 'Failed to delete file' });\n }\n});\n\n// Get file by storage path\napp.get('/api/files/download/:filename', (req, res) => {\n try {\n const filename = req.params.filename;\n const filepath = path.join(uploadsDir, filename);\n\n // Security: ensure the file is within uploads directory\n if (!path.resolve(filepath).startsWith(path.resolve(uploadsDir))) {\n return res.status(403).json({ error: 'Access denied' });\n }\n\n if (!fs.existsSync(filepath)) {\n return res.status(404).json({ error: 'File not found' });\n }\n\n res.download(filepath);\n } catch (err) {\n console.error('Download error:', err);\n res.status(500).json({ error: 'Download failed' });\n }\n});\n\n// Admin Routes\n\n// Get all users\napp.get('/api/admin/users', verifyToken, async (req, res) => {\n try {\n // Check if admin\n const roleDoc = await db.collection('user_roles').findOne({ user_id: req.userId, role: 'admin' });\n\n if (!roleDoc) {\n return res.status(403).json({ error: 'Unauthorized' });\n }\n\n const usersCollection = db.collection('users');\n const users = await usersCollection\n .find({}, { projection: { password: 0 } })\n .toArray();\n\n const formattedUsers = users.map(u => ({\n id: u._id.toString(),\n ...u,\n _id: undefined,\n }));\n\n res.json(formattedUsers);\n } catch (err) {\n console.error('Get users error:', err);\n res.status(500).json({ error: 'Failed to fetch users' });\n }\n});\n\n// Get admin files\napp.get('/api/admin/files', verifyToken, async (req, res) => {\n try {\n // Check if admin\n const roleDoc = await db.collection('user_roles').findOne({ user_id: req.userId, role: 'admin' });\n\n if (!roleDoc) {\n return res.status(403).json({ error: 'Unauthorized' });\n }\n\n const filesCollection = db.collection('files');\n const files = await filesCollection\n .find({})\n .sort({ created_at: -1 })\n .toArray();\n\n const formattedFiles = files.map(f => ({\n id: f._id.toString(),\n ...f,\n _id: undefined,\n }));\n\n res.json(formattedFiles);\n } catch (err) {\n console.error('Get admin files error:', err);\n res.status(500).json({ error: 'Failed to fetch files' });\n }\n});\n\n// Set user as admin\napp.post('/api/admin/users/:userId/role', verifyToken, async (req, res) => {\n try {\n // Check if admin\n const roleDoc = await db.collection('user_roles').findOne({ user_id: req.userId, role: 'admin' });\n\n if (!roleDoc) {\n return res.status(403).json({ error: 'Unauthorized' });\n }\n\n const { role } = req.body;\n const userRolesCollection = db.collection('user_roles');\n\n if (role === 'admin') {\n await userRolesCollection.updateOne(\n { user_id: req.params.userId },\n { $set: { user_id: req.params.userId, role: 'admin' } },\n { upsert: true }\n );\n } else {\n await userRolesCollection.deleteOne({ user_id: req.params.userId, role: 'admin' });\n }\n\n res.json({ success: true });\n } catch (err) {\n console.error('Set role error:', err);\n res.status(500).json({ error: 'Failed to update role' });\n }\n});\n\n// Health check\napp.get('/health', (req, res) => {\n res.json({ status: 'ok' });\n});\n\n// Start server\ninitMongoDB().then(async () => {\n // Check hf_transfer availability\n const hfTransferReady = await checkHfTransferAvailable();\n if (hfTransferReady) {\n console.log('🦀 ⚡ HF Transfer (Rust) ENABLED - Ultra-fast parallel I/O');\n } else {\n console.log('⚠️ HF Transfer not found - Falling back to Node.js streams');\n }\n\n app.listen(PORT, () => {\n console.log(`✨ Server running on http://localhost:${PORT}`);\n console.log(`📊 Upload config: 512KB chunks, 4 parallel, hf_transfer: ${hfTransferReady ? 'YES' : 'NO'}`);\n });\n});\n",
5
  "language": "javascript",
6
  "createdAt": 1776244783913,
7
- "updatedAt": 1776316976776
8
  }
 
1
  {
2
  "id": "dcc43ef1-4f83-4afe-a59d-61a9ae99cb51",
3
  "title": "Untitled",
4
+ "content": "{\n \"name\": \"vite_react_shadcn_ts\",\n \"private\": true,\n \"version\": \"0.0.0\",\n \"type\": \"module\",\n \"scripts\": {\n \"dev\": \"concurrently \\\"npm run server\\\" \\\"vite\\\"\",\n \"server\": \"node server.js\",\n \"build\": \"vite build\",\n \"build:dev\": \"vite build --mode development\",\n \"lint\": \"eslint .\",\n \"preview\": \"vite preview\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\"\n },\n \"dependencies\": {\n \"@hookform/resolvers\": \"^3.10.0\",\n \"@radix-ui/react-accordion\": \"^1.2.11\",\n \"@radix-ui/react-alert-dialog\": \"^1.1.14\",\n \"@radix-ui/react-aspect-ratio\": \"^1.1.7\",\n \"@radix-ui/react-avatar\": \"^1.1.10\",\n \"@radix-ui/react-checkbox\": \"^1.3.2\",\n \"@radix-ui/react-collapsible\": \"^1.1.11\",\n \"@radix-ui/react-context-menu\": \"^2.2.15\",\n \"@radix-ui/react-dialog\": \"^1.1.14\",\n \"@radix-ui/react-dropdown-menu\": \"^2.1.15\",\n \"@radix-ui/react-hover-card\": \"^1.1.14\",\n \"@radix-ui/react-label\": \"^2.1.7\",\n \"@radix-ui/react-menubar\": \"^1.1.15\",\n \"@radix-ui/react-navigation-menu\": \"^1.2.13\",\n \"@radix-ui/react-popover\": \"^1.1.14\",\n \"@radix-ui/react-progress\": \"^1.1.7\",\n \"@radix-ui/react-radio-group\": \"^1.3.7\",\n \"@radix-ui/react-scroll-area\": \"^1.2.9\",\n \"@radix-ui/react-select\": \"^2.2.5\",\n \"@radix-ui/react-separator\": \"^1.1.7\",\n \"@radix-ui/react-slider\": \"^1.3.5\",\n \"@radix-ui/react-slot\": \"^1.2.3\",\n \"@radix-ui/react-switch\": \"^1.2.5\",\n \"@radix-ui/react-tabs\": \"^1.1.12\",\n \"@radix-ui/react-toast\": \"^1.2.14\",\n \"@radix-ui/react-toggle\": \"^1.1.9\",\n \"@radix-ui/react-toggle-group\": \"^1.1.10\",\n \"@radix-ui/react-tooltip\": \"^1.2.7\",\n \"@tanstack/react-query\": \"^5.83.0\",\n \"bcryptjs\": \"^2.4.3\",\n \"class-variance-authority\": \"^0.7.1\",\n \"clsx\": \"^2.1.1\",\n \"cmdk\": \"^1.1.1\",\n \"date-fns\": \"^3.6.0\",\n \"dotenv\": \"^16.6.1\",\n \"embla-carousel-react\": \"^8.6.0\",\n \"express\": \"^4.18.2\",\n \"framer-motion\": \"^11.0.0\",\n \"input-otp\": \"^1.4.2\",\n \"jsonwebtoken\": \"^9.0.0\",\n \"lucide-react\": \"^0.462.0\",\n \"mongodb\": \"^5.9.2\",\n \"multer\": \"^1.4.5-lts.1\",\n \"next-themes\": \"^0.3.0\",\n \"react\": \"^18.3.1\",\n \"react-day-picker\": \"^8.10.1\",\n \"react-dom\": \"^18.3.1\",\n \"react-hook-form\": \"^7.61.1\",\n \"react-resizable-panels\": \"^2.1.9\",\n \"react-router-dom\": \"^6.30.1\",\n \"recharts\": \"^2.15.4\",\n \"sonner\": \"^1.7.4\",\n \"tailwind-merge\": \"^2.6.0\",\n \"tailwindcss-animate\": \"^1.0.7\",\n \"vaul\": \"^0.9.9\",\n \"zod\": \"^3.25.76\"\n },\n \"devDependencies\": {\n \"@eslint/js\": \"^9.32.0\",\n \"@tailwindcss/typography\": \"^0.5.16\",\n \"@testing-library/jest-dom\": \"^6.6.0\",\n \"@testing-library/react\": \"^16.0.0\",\n \"@types/bcryptjs\": \"^2.4.6\",\n \"@types/express\": \"^4.17.21\",\n \"@types/jsonwebtoken\": \"^9.0.7\",\n \"@types/multer\": \"^1.4.12\",\n \"@types/node\": \"^22.16.5\",\n \"@types/react\": \"^18.3.23\",\n \"@types/react-dom\": \"^18.3.7\",\n \"@vitejs/plugin-react-swc\": \"^3.11.0\",\n \"autoprefixer\": \"^10.4.21\",\n \"concurrently\": \"^8.2.2\",\n \"eslint\": \"^9.32.0\",\n \"eslint-plugin-react-hooks\": \"^5.2.0\",\n \"eslint-plugin-react-refresh\": \"^0.4.20\",\n \"globals\": \"^15.15.0\",\n \"jsdom\": \"^20.0.3\",\n \"lovable-tagger\": \"^1.1.13\",\n \"postcss\": \"^8.5.6\",\n \"tailwindcss\": \"^3.4.17\",\n \"typescript\": \"^5.8.3\",\n \"typescript-eslint\": \"^8.38.0\",\n \"vite\": \"^5.4.19\",\n \"vitest\": \"^3.2.4\"\n }\n}\n",
5
  "language": "javascript",
6
  "createdAt": 1776244783913,
7
+ "updatedAt": 1776317652244
8
  }