UNPKG

aiom_pack

Version:

Framework for interdependent (mcmc-like) behavioral experiments

68 lines (62 loc) 2.31 kB
// come into effect when the user set production to true in .env file const { pool } = require('../../core/database'); const sharp = require('sharp'); exports.upload_files = async (req, res, next) => { try { const consentPublications = req.header('Consent-Publications'); const pid = req.header('pid'); if (consentPublications === 'false') { await pool.query( `UPDATE participants SET face_authorization = false WHERE participant = $1`, [pid] ); } // Create images table if it doesn't exist await pool.query(` CREATE TABLE IF NOT EXISTS production ( id SERIAL PRIMARY KEY, participant_id TEXT NOT NULL, image_name TEXT NOT NULL, image_data BYTEA NOT NULL, upload_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) `); const files = req.files.files; const filesArray = Array.isArray(files) ? files : [files]; const MAX_SIZE_MB = 1; // Define max size in MB const MAX_SIZE_BYTES = MAX_SIZE_MB * 1024 * 1024; for (let i = 0; i < filesArray.length; i++) { const file = filesArray[i]; let imageData = file.data; if (imageData.length > MAX_SIZE_BYTES) { let quality = 90; while (quality >= 40 && imageData.length > MAX_SIZE_BYTES) { try { imageData = await sharp(file.data) .jpeg({ quality }) .toBuffer(); quality -= 10; } catch (err) { console.error(`Error compressing ${file.name}:`, err); imageData = file.data; break; } } } // Insert image into database const result = await pool.query( `INSERT INTO production (participant_id, image_name, image_data) VALUES ($1, $2, $3) RETURNING id`, [pid, file.name.split('.')[0], imageData] ); } console.log(`Files uploaded successfully for participant ${pid}`); res.status(200).json({ progress: 100, message: "Files uploaded successfully -- thank you!", }); } catch (error) { next(error); } }