Spaces:
Runtime error
Runtime error
blaze-aura69 commited on
Update index.js
Browse files12342 unmodified lines789101112132 unmodified lines1617181920212223242517 unmodified lines43444546474849505152535455565758599 unmodified lines6970717273747576777879801 unmodified line82838485868788899091925 unmodified lines98991001011021031041051061071085 unmodified lines11411511611711811912012112 unmodified lines13413513613713813914030 unmodified lines17117217317417517617764 unmodified lines24224324424524624724829 unmodified lines27827928028128228326 unmodified lines31031131231331431531631731812 unmodified lines3313323333343353365 unmodified lines34234334434534634734834935035135235335435533 unmodified lines38939039139239339439539639739839940040140240340440540640740840941010 unmodified lines4214224234244254264274 unmodified lines4324334344354364374381 unmodified line4404414424434444454464478 unmodified lines4564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954965 unmodified lines5025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575584 unmodified lines56356456556656756856957057157257357457557657711 unmodified lines589590591592593594595'use strict'; const { Worker: ThreadWorker, isMainThread, parentPort, workerData } = require('worker_threads');// ============ DATABASE WORKER THREAD ============if (!isMainThread) {2 unmodified linesconst fs = require('fs');const DATA_DIR = workerData.dataDir || "/data";if (!fs.existsSync(DATA_DIR)) {fs.mkdirSync(DATA_DIR, { recursive: true });}2 unmodified linesconst db = new Database(dbPath);db.pragma('journal_mode = WAL');db.pragma('synchronous = OFF');db.pragma('cache_size = -2000000');db.pragma('temp_store = MEMORY');db.pragma('mmap_size = 268435456');db.exec(`CREATE TABLE IF NOT EXISTS users (17 unmodified linesgetUserById: db.prepare('SELECT * FROM users WHERE id = ?'),getUserByUsername: db.prepare('SELECT * FROM users WHERE username = ?'),insertUser: db.prepare(`INSERT INTO users (id, username, password_hash, name, created_at, is_login,bio, pic_url, date_of_birth, is_profile_public) VALUES (@id, @username, @password_hash, @name, @created_at, @is_login,@bio, @pic_url, @date_of_birth, @is_profile_public)`),updateLogin: db.prepare('UPDATE users SET is_login = ? WHERE id = ?'),updateProfile: db.prepare(`UPDATE users SETname = COALESCE(NULLIF(@name, ''), name),bio = COALESCE(NULLIF(@bio, ''), bio),date_of_birth = COALESCE(NULLIF(@date_of_birth, ''), date_of_birth),9 unmodified linestry {let result;switch (action) {case 'getAllUsers': result = stmts.getAllUsers.all(); break;case 'getUserById': result = stmts.getUserById.get(data.userId); break;case 'getUserByUsername': result = stmts.getUserByUsername.get(data.username); break;case 'insertUser': stmts.insertUser.run(data.user); result = { success: true }; break;case 'updateLogin': stmts.updateLogin.run(data.isLogin ? 1 : 0, data.userId); result = { success: true }; break;case 'updateProfile':stmts.updateProfile.run({id: data.userId,name: data.name || 'Unknown',1 unmodified linedate_of_birth: data.date_of_birth || '',is_profile_public: data.is_profile_public || 'true'});result = { success: true }; break;case 'updatePhoto': stmts.updatePhoto.run(data.picUrl, data.userId); result = { success: true }; break;case 'batchOperation': result = processBatch(data.operations); break;case 'getCount': result = stmts.getCount.get().count; break;default: throw new Error(`Unknown action: ${action}`);}parentPort.postMessage({ id, success: true, result });} catch (error) {5 unmodified linesconst transaction = db.transaction(() => {for (const op of operations) {switch (op.action) {case 'signup': stmts.insertUser.run(op.user); break;case 'login': stmts.updateLogin.run(1, op.userId); break;case 'logout': stmts.updateLogin.run(0, op.userId); break;case 'updateProfile': stmts.updateProfile.run(op.data); break;case 'updatePhoto': stmts.updatePhoto.run(op.picUrl, op.userId); break;}}});5 unmodified lines}// ============ MAIN THREAD - ONLY RUNS ONCE ============// This code only executes in the main threadconst fastify = require('fastify')({logger: false,bodyLimit: 1048576,12 unmodified linesconst path = require('path');let sharp;try { sharp = require('sharp'); } catch (e) {}const MAX_BUCKET_SIZE = 60 * 1024 * 1024 * 1024;const MAX_USERS = 30000;30 unmodified linestry {const content = await fsp.readFile(FULL_FILE, 'utf8');return content.trim() ? content.trim().split('|') : [];} catch (e) { return []; }}async function addSpaceToFull() {64 unmodified linesfunction initDBWorker() {return new Promise((resolve, reject) => {dbWorker = new ThreadWorker(__filename, { workerData: { dataDir: DATA_DIR } });dbWorker.on('message', (message) => {const { id, success, result, error } = message;const promise = dbPromises.get(id);29 unmodified linesthis.requests = 0;this.windowStart = Date.now();}isAllowed() {const now = Date.now();if (now - this.windowStart >= this.windowMs) {26 unmodified linestry {const files = fs.readdirSync(PHOTOS_DIR);for (const file of files) {try { totalSize += fs.statSync(path.join(PHOTOS_DIR, file)).size; } catch (e) {}}try { totalSize += fs.statSync(path.join(DATA_DIR, 'users.db')).size; } catch (e) {}} catch (e) {}return totalSize;}12 unmodified lines} catch (e) {}}async function compressToWebp(fileData, maxSizeKb = 20) {if (!sharp) return fileData;try {5 unmodified lineslet quality = 80;let outputBuffer;while (quality >= 10) {outputBuffer = await image.resize(800, 800, { fit: 'inside', withoutEnlargement: true }).webp({ quality }).toBuffer();if (outputBuffer.length / 1024 <= maxSizeKb) break;quality -= 10;}if (outputBuffer.length / 1024 > maxSizeKb) {outputBuffer = await image.resize(400, 400, { fit: 'inside', withoutEnlargement: true }).webp({ quality: 30 }).toBuffer();}return outputBuffer;} catch (e) {33 unmodified linesis_profile_public: 'true'};operations.push({ action: 'signup', userId: req.user_id, user });usersCache.set(req.user_id, user);usernameIndex.set(user.username.toLowerCase(), user);break;}case 'login':operations.push({ action: 'login', userId: req.user_id });const loginUser = usersCache.get(req.user_id);if (loginUser) loginUser.is_login = 1;break;case 'logout':operations.push({ action: 'logout', userId: req.user_id });const logoutUser = usersCache.get(req.user_id);if (logoutUser) logoutUser.is_login = 0;break;case 'update_profile': {const profileUser = usersCache.get(req.user_id);const updateData = req.data || {};if (profileUser) {if (updateData.name) profileUser.name = updateData.name;10 unmodified linesconst compressed = await compressToWebp(Buffer.from(req.pic_buffer, 'base64'), MAX_PHOTO_SIZE_KB);const filename = `${req.user_id}_${Math.floor(Date.now() / 1000)}.webp`;await fsp.writeFile(path.join(PHOTOS_DIR, filename), compressed);const photoUser = usersCache.get(req.user_id);if (photoUser) photoUser.pic_url = `/photos/${filename}`;operations.push({ action: 'updatePhoto', userId: req.user_id, picUrl: `/photos/${filename}` });} catch (e) {}4 unmodified lines}if (operations.length > 0) {try { await dbRequest('batchOperation', { operations }); } catch (e) {}}processingLock = false;}1 unmodified linefunction addRequest(userId, username, action, data, picBuffer = null) {if (!userId) userId = generateId();batchBuffer.push({user_id: userId, username: username || 'unknown',action: action || 'unknown', data: data || {},pic_buffer: picBuffer ? picBuffer.toString('base64') : null,timestamp: Date.now()});8 unmodified linesfastify.addHook('onRequest', async (request, reply) => {if (!rateLimiter.isAllowed()) {reply.status(503).send({ error: 'rate_limit' }); return;}if (totalUsers >= MAX_USERS) {reply.status(503).send({ error: 'full' }); return;}});fastify.post('/signup', async (request, reply) => {if (totalUsers >= MAX_USERS) {reply.status(507).send({ detail: 'Server full' }); return;}const { username, password, name } = request.body || {};if (!username || !password || !name) {reply.status(400).send({ detail: 'Missing fields' }); return;}const cleanUsername = username.trim().toLowerCase();if (cleanUsername.length < 3 || cleanUsername.length > MAX_USERNAME_LENGTH) {reply.status(400).send({ detail: `Username must be 3-${MAX_USERNAME_LENGTH} chars` }); return;}if (password.length < 6 || password.length > MAX_PASSWORD_LENGTH) {reply.status(400).send({ detail: `Password must be 6-${MAX_PASSWORD_LENGTH} chars` }); return;}if (name.trim().length > MAX_NAME_LENGTH) {reply.status(400).send({ detail: `Name max ${MAX_NAME_LENGTH} chars` }); return;}if (usernameIndex.has(cleanUsername)) {reply.status(409).send({ detail: 'Username exists' }); return;}const userId = generateId();const newUser = {id: userId, username: cleanUsername,password_hash: hashPassword(password), name: name.trim(),created_at: new Date().toISOString(), is_login: 0,bio: '', pic_url: '', date_of_birth: '', is_profile_public: 'true'};usersCache.set(userId, newUser);usernameIndex.set(cleanUsername, newUser);totalUsers = usersCache.size;5 unmodified linesfastify.post('/login', async (request, reply) => {const { username, password } = request.body || {};if (!username || !password) {reply.status(400).send({ detail: 'Missing fields' }); return;}const user = usernameIndex.get(username.trim().toLowerCase());if (!user || !verifyPassword(password, user.password_hash)) {reply.status(401).send({ detail: 'Invalid credentials' }); return;}addRequest(user.id, user.username, 'login', {});reply.send({success: true, id: user.id, username: user.username,name: user.name, bio: user.bio || '', pic_url: user.pic_url || '',date_of_birth: user.date_of_birth || '', is_profile_public: user.is_profile_public || 'true',created_at: user.created_at});});fastify.post('/logout', async (request, reply) => {const { id } = request.body || {};if (!id) { reply.status(400).send({ detail: 'Missing ID' }); return; }if (!usersCache.has(id)) { reply.status(404).send({ detail: 'Not found' }); return; }addRequest(id, '', 'logout', {});reply.send({ success: true });});fastify.put('/updateprofiledetails', async (request, reply) => {const { id, ...data } = request.body || {};if (!id) { reply.status(400).send({ detail: 'Missing ID' }); return; }if (!usersCache.has(id)) { reply.status(404).send({ detail: 'Not found' }); return; }if (data.name && data.name.length > MAX_NAME_LENGTH) {reply.status(400).send({ detail: `Name max ${MAX_NAME_LENGTH} chars` }); return;}if (data.bio && data.bio.length > MAX_BIO_LENGTH) {reply.status(400).send({ detail: `Bio max ${MAX_BIO_LENGTH} chars` }); return;}addRequest(id, '', 'update_profile', data);reply.send({ success: true });});fastify.post('/uploadphoto', async (request, reply) => {if (getBucketSize() >= MAX_BUCKET_SIZE) {reply.status(507).send({ detail: 'Storage full' }); return;}try {const data = await request.file();if (!data || !data.mimetype.startsWith('image/')) {reply.status(400).send({ detail: 'Invalid image' }); return;}const fileBuffer = await data.toBuffer();const id = (data.fields && data.fields.id) ? data.fields.id.value : null;if (!id || !usersCache.has(id)) {reply.status(404).send({ detail: 'Not found' }); return;}addRequest(id, '', 'upload_photo', {}, fileBuffer);reply.send({ success: true });} catch (e) {4 unmodified linesfastify.get('/getuser', async (request, reply) => {const { id, username } = request.query || {};let user;if (username) user = usernameIndex.get(username.toLowerCase());else if (id) user = usersCache.get(id);else { reply.status(400).send({ detail: 'Missing params' }); return; }if (!user) { reply.status(404).send({ detail: 'Not found' }); return; }reply.send({id: user.id, username: user.username, name: user.name,bio: user.bio || '', pic_url: user.pic_url || '',date_of_birth: user.date_of_birth || '', is_profile_public: user.is_profile_public || 'true',created_at: user.created_at, is_login: Boolean(user.is_login)});});11 unmodified linesif (batchBuffer.length > 0) flushBatch();}, 100);setInterval(async () => { await checkUserCountStatus(); }, 5000);const port = process.env.PORT || 7860;await fastify.listen({ port, host: '0.0.0.0' });123452 unmodified lines89101112132 unmodified lines161718192021222324252617 unmodified lines44454647484950515253545556575859609 unmodified lines7071727374757677787980818283848586878889909192931 unmodified line95969798991001011021031041051061071081091101111121131145 unmodified lines1201211221231241251261271281291301311321331341351361371381391405 unmodified lines14614714814915015112 unmodified lines16416516616716816917017117230 unmodified lines20320420520620720820921021164 unmodified lines27627727827928028128228328429 unmodified lines31431531631731831932026 unmodified lines34734834935035135235335435535635735835912 unmodified lines3723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014025 unmodified lines40840941041141241341441541641741841942042142242342442542633 unmodified lines46046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149210 unmodified lines5035045055065075085095105115124 unmodified lines5175185195205215225235245251 unmodified line5275285295305315325335345355368 unmodified lines5455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106115 unmodified lines6176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267274 unmodified lines73273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978011 unmodified lines792793794795796797798799800801802803804805806807808809810811812813814'use strict';const { Worker: ThreadWorker, isMainThread, parentPort, workerData } = require('worker_threads');// ============ DATABASE WORKER THREAD ============if (!isMainThread) {2 unmodified linesconst fs = require('fs');const DATA_DIR = workerData.dataDir || "/data";if (!fs.existsSync(DATA_DIR)) {fs.mkdirSync(DATA_DIR, { recursive: true });}2 unmodified linesconst db = new Database(dbPath);db.pragma('journal_mode = WAL');db.pragma('synchronous = NORMAL');db.pragma('cache_size = -2000000');db.pragma('temp_store = MEMORY');db.pragma('mmap_size = 268435456');db.pragma('busy_timeout = 5000');db.exec(`CREATE TABLE IF NOT EXISTS users (17 unmodified linesgetUserById: db.prepare('SELECT * FROM users WHERE id = ?'),getUserByUsername: db.prepare('SELECT * FROM users WHERE username = ?'),insertUser: db.prepare(`INSERT OR IGNORE INTO users (id, username, password_hash, name, created_at, is_login,bio, pic_url, date_of_birth, is_profile_public) VALUES (@id, @username, @password_hash, @name, @created_at, @is_login,@bio, @pic_url, @date_of_birth, @is_profile_public)`),updateLogin: db.prepare('UPDATE users SET is_login = ? WHERE id = ?'),updateProfile: db.prepare(`UPDATE users SETname = COALESCE(NULLIF(@name, ''), name),bio = COALESCE(NULLIF(@bio, ''), bio),date_of_birth = COALESCE(NULLIF(@date_of_birth, ''), date_of_birth),9 unmodified linestry {let result;switch (action) {case 'getAllUsers':result = stmts.getAllUsers.all();break;case 'getUserById':result = stmts.getUserById.get(data.userId);break;case 'getUserByUsername':result = stmts.getUserByUsername.get(data.username);break;case 'insertUser':stmts.insertUser.run(data.user);result = { success: true };break;case 'updateLogin':stmts.updateLogin.run(data.isLogin ? 1 : 0, data.userId);result = { success: true };break;case 'updateProfile':stmts.updateProfile.run({id: data.userId,name: data.name || 'Unknown',1 unmodified linedate_of_birth: data.date_of_birth || '',is_profile_public: data.is_profile_public || 'true'});result = { success: true };break;case 'updatePhoto':stmts.updatePhoto.run(data.picUrl, data.userId);result = { success: true };break;case 'batchOperation':result = processBatch(data.operations);break;case 'getCount':result = stmts.getCount.get().count;break;default:throw new Error(`Unknown action: ${action}`);}parentPort.postMessage({ id, success: true, result });} catch (error) {5 unmodified linesconst transaction = db.transaction(() => {for (const op of operations) {switch (op.action) {case 'signup':stmts.insertUser.run(op.user);break;case 'login':stmts.updateLogin.run(1, op.userId);break;case 'logout':stmts.updateLogin.run(0, op.userId);break;case 'updateProfile':stmts.updateProfile.run(op.data);break;case 'updatePhoto':stmts.updatePhoto.run(op.picUrl, op.userId);break;}}});5 unmodified lines}// ============ MAIN THREAD - ONLY RUNS ONCE ============const fastify = require('fastify')({logger: false,bodyLimit: 1048576,12 unmodified linesconst path = require('path');let sharp;try {sharp = require('sharp');} catch (e) {}const MAX_BUCKET_SIZE = 60 * 1024 * 1024 * 1024;const MAX_USERS = 30000;30 unmodified linestry {const content = await fsp.readFile(FULL_FILE, 'utf8');return content.trim() ? content.trim().split('|') : [];} catch (e) {return [];}}async function addSpaceToFull() {64 unmodified linesfunction initDBWorker() {return new Promise((resolve, reject) => {dbWorker = new ThreadWorker(__filename, {workerData: { dataDir: DATA_DIR }});dbWorker.on('message', (message) => {const { id, success, result, error } = message;const promise = dbPromises.get(id);29 unmodified linesthis.requests = 0;this.windowStart = Date.now();}isAllowed() {const now = Date.now();if (now - this.windowStart >= this.windowMs) {26 unmodified linestry {const files = fs.readdirSync(PHOTOS_DIR);for (const file of files) {try {totalSize += fs.statSync(path.join(PHOTOS_DIR, file)).size;} catch (e) {}}try {totalSize += fs.statSync(path.join(DATA_DIR, 'users.db')).size;} catch (e) {}} catch (e) {}return totalSize;}12 unmodified lines} catch (e) {}}// Fetch user from DB if not in cacheasync function getUserFromDB(userId) {try {const user = await dbRequest('getUserById', { userId });if (user) {usersCache.set(user.id, user);usernameIndex.set(user.username.toLowerCase(), user);return user;}} catch (e) {}return null;}async function getUserByUsernameFromDB(username) {try {const user = await dbRequest('getUserByUsername', { username });if (user) {usersCache.set(user.id, user);usernameIndex.set(user.username.toLowerCase(), user);return user;}} catch (e) {}return null;}async function compressToWebp(fileData, maxSizeKb = 20) {if (!sharp) return fileData;try {5 unmodified lineslet quality = 80;let outputBuffer;while (quality >= 10) {outputBuffer = await image.resize(800, 800, { fit: 'inside', withoutEnlargement: true }).webp({ quality }).toBuffer();if (outputBuffer.length / 1024 <= maxSizeKb) break;quality -= 10;}if (outputBuffer.length / 1024 > maxSizeKb) {outputBuffer = await image.resize(400, 400, { fit: 'inside', withoutEnlargement: true }).webp({ quality: 30 }).toBuffer();}return outputBuffer;} catch (e) {33 unmodified linesis_profile_public: 'true'};operations.push({ action: 'signup', userId: req.user_id, user });if (!usersCache.has(req.user_id)) {usersCache.set(req.user_id, user);usernameIndex.set(user.username.toLowerCase(), user);}break;}case 'login':operations.push({ action: 'login', userId: req.user_id });let loginUser = usersCache.get(req.user_id);if (!loginUser) {loginUser = await getUserFromDB(req.user_id);}if (loginUser) loginUser.is_login = 1;break;case 'logout':operations.push({ action: 'logout', userId: req.user_id });let logoutUser = usersCache.get(req.user_id);if (!logoutUser) {logoutUser = await getUserFromDB(req.user_id);}if (logoutUser) logoutUser.is_login = 0;break;case 'update_profile': {let profileUser = usersCache.get(req.user_id);if (!profileUser) {profileUser = await getUserFromDB(req.user_id);}const updateData = req.data || {};if (profileUser) {if (updateData.name) profileUser.name = updateData.name;10 unmodified linesconst compressed = await compressToWebp(Buffer.from(req.pic_buffer, 'base64'), MAX_PHOTO_SIZE_KB);const filename = `${req.user_id}_${Math.floor(Date.now() / 1000)}.webp`;await fsp.writeFile(path.join(PHOTOS_DIR, filename), compressed);let photoUser = usersCache.get(req.user_id);if (!photoUser) {photoUser = await getUserFromDB(req.user_id);}if (photoUser) photoUser.pic_url = `/photos/${filename}`;operations.push({ action: 'updatePhoto', userId: req.user_id, picUrl: `/photos/${filename}` });} catch (e) {}4 unmodified lines}if (operations.length > 0) {try {await dbRequest('batchOperation', { operations });} catch (e) {}}processingLock = false;}1 unmodified linefunction addRequest(userId, username, action, data, picBuffer = null) {if (!userId) userId = generateId();batchBuffer.push({user_id: userId,username: username || 'unknown',action: action || 'unknown',data: data || {},pic_buffer: picBuffer ? picBuffer.toString('base64') : null,timestamp: Date.now()});8 unmodified linesfastify.addHook('onRequest', async (request, reply) => {if (!rateLimiter.isAllowed()) {reply.status(503).send({ error: 'rate_limit' });return;}if (totalUsers >= MAX_USERS) {reply.status(503).send({ error: 'full' });return;}});fastify.post('/signup', async (request, reply) => {if (totalUsers >= MAX_USERS) {reply.status(507).send({ detail: 'Server full' });return;}const { username, password, name } = request.body || {};if (!username || !password || !name) {reply.status(400).send({ detail: 'Missing fields' });return;}const cleanUsername = username.trim().toLowerCase();if (cleanUsername.length < 3 || cleanUsername.length > MAX_USERNAME_LENGTH) {reply.status(400).send({ detail: `Username must be 3-${MAX_USERNAME_LENGTH} chars` });return;}if (password.length < 6 || password.length > MAX_PASSWORD_LENGTH) {reply.status(400).send({ detail: `Password must be 6-${MAX_PASSWORD_LENGTH} chars` });return;}if (name.trim().length > MAX_NAME_LENGTH) {reply.status(400).send({ detail: `Name max ${MAX_NAME_LENGTH} chars` });return;}// Check cache first, then DBif (usernameIndex.has(cleanUsername)) {reply.status(409).send({ detail: 'Username exists' });return;}const existingUser = await getUserByUsernameFromDB(cleanUsername);if (existingUser) {reply.status(409).send({ detail: 'Username exists' });return;}const userId = generateId();const newUser = {id: userId,username: cleanUsername,password_hash: hashPassword(password),name: name.trim(),created_at: new Date().toISOString(),is_login: 0,bio: '',pic_url: '',date_of_birth: '',is_profile_public: 'true'};usersCache.set(userId, newUser);usernameIndex.set(cleanUsername, newUser);totalUsers = usersCache.size;5 unmodified linesfastify.post('/login', async (request, reply) => {const { username, password } = request.body || {};if (!username || !password) {reply.status(400).send({ detail: 'Missing fields' });return;}let user = usernameIndex.get(username.trim().toLowerCase());if (!user) {user = await getUserByUsernameFromDB(username.trim().toLowerCase());}if (!user || !verifyPassword(password, user.password_hash)) {reply.status(401).send({ detail: 'Invalid credentials' });return;}addRequest(user.id, user.username, 'login', {});reply.send({success: true,id: user.id,username: user.username,name: user.name,bio: user.bio || '',pic_url: user.pic_url || '',date_of_birth: user.date_of_birth || '',is_profile_public: user.is_profile_public || 'true',created_at: user.created_at});});fastify.post('/logout', async (request, reply) => {const { id } = request.body || {};if (!id) {reply.status(400).send({ detail: 'Missing ID' });return;}let user = usersCache.get(id);if (!user) {user = await getUserFromDB(id);}if (!user) {reply.status(404).send({ detail: 'Not found' });return;}addRequest(id, '', 'logout', {});reply.send({ success: true });});fastify.put('/updateprofiledetails', async (request, reply) => {const { id, ...data } = request.body || {};if (!id) {reply.status(400).send({ detail: 'Missing ID' });return;}let user = usersCache.get(id);if (!user) {user = await getUserFromDB(id);}if (!user) {reply.status(404).send({ detail: 'Not found' });return;}if (data.name && data.name.length > MAX_NAME_LENGTH) {reply.status(400).send({ detail: `Name max ${MAX_NAME_LENGTH} chars` });return;}if (data.bio && data.bio.length > MAX_BIO_LENGTH) {reply.status(400).send({ detail: `Bio max ${MAX_BIO_LENGTH} chars` });return;}addRequest(id, '', 'update_profile', data);reply.send({ success: true });});fastify.post('/uploadphoto', async (request, reply) => {if (getBucketSize() >= MAX_BUCKET_SIZE) {reply.status(507).send({ detail: 'Storage full' });return;}try {const data = await request.file();if (!data || !data.mimetype.startsWith('image/')) {reply.status(400).send({ detail: 'Invalid image' });return;}const fileBuffer = await data.toBuffer();const id = (data.fields && data.fields.id) ? data.fields.id.value : null;let user = usersCache.get(id);if (!user) {user = await getUserFromDB(id);}if (!id || !user) {reply.status(404).send({ detail: 'Not found' });return;}addRequest(id, '', 'upload_photo', {}, fileBuffer);reply.send({ success: true });} catch (e) {4 unmodified linesfastify.get('/getuser', async (request, reply) => {const { id, username } = request.query || {};let user;if (username) {user = usernameIndex.get(username.toLowerCase());if (!user) {user = await getUserByUsernameFromDB(username.toLowerCase());}} else if (id) {user = usersCache.get(id);if (!user) {user = await getUserFromDB(id);}} else {reply.status(400).send({ detail: 'Missing params' });return;}if (!user) {reply.status(404).send({ detail: 'Not found' });return;}reply.send({id: user.id,username: user.username,name: user.name,bio: user.bio || '',pic_url: user.pic_url || '',date_of_birth: user.date_of_birth || '',is_profile_public: user.is_profile_public || 'true',created_at: user.created_at,is_login: Boolean(user.is_login)});});fastify.get('/check', async (request, reply) => {const count = await dbRequest('getCount');const isFull = totalUsers >= MAX_USERS;reply.send({status: 'ok',count: count,maxUsers: MAX_USERS,isFull: isFull,spaceName: SPACE_NAME});});11 unmodified linesif (batchBuffer.length > 0) flushBatch();}, 100);setInterval(async () => {await checkUserCountStatus();}, 5000);// Reload cache from DB every 30 seconds to stay in sync with other spacessetInterval(async () => {try {const users = await dbRequest('getAllUsers');for (const user of users) {if (!usersCache.has(user.id)) {usersCache.set(user.id, user);usernameIndex.set(user.username.toLowerCase(), user);}}totalUsers = users.length;} catch (e) {}}, 30000);const port = process.env.PORT || 7860;await fastify.listen({ port, host: '0.0.0.0' });
index.js+304-85