diff --git a/backup-restore.js b/backup-restore.js
index 0a204f2..ff18172 100644
--- a/backup-restore.js
+++ b/backup-restore.js
@@ -348,6 +348,7 @@ function normalizeRestoreData(data) {
token: reqToken(x.token),
path: reqUploadPath(x.path, 255),
name: reqStr(x.name, 255),
+ size: optInt(x.size, 0, Number.MAX_SAFE_INTEGER),
detached_at: optTs(x.detached_at),
created_at: optTs(x.created_at),
}));
diff --git a/db/init.sql b/db/init.sql
index 95129be..3733034 100644
--- a/db/init.sql
+++ b/db/init.sql
@@ -188,6 +188,7 @@ CREATE TABLE IF NOT EXISTS project_files (
token VARCHAR(64) UNIQUE NOT NULL,
path VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL,
+ size BIGINT,
created_at TIMESTAMPTZ DEFAULT now(),
detached_at TIMESTAMPTZ
);
diff --git a/db/migration.sql b/db/migration.sql
index dbe5c80..c0d53a1 100644
--- a/db/migration.sql
+++ b/db/migration.sql
@@ -92,6 +92,7 @@ CREATE UNIQUE INDEX IF NOT EXISTS project_files_token_key ON project_files(token
ALTER TABLE project_files ALTER COLUMN entry_id DROP NOT NULL;
ALTER TABLE project_files ADD COLUMN IF NOT EXISTS detached_at TIMESTAMPTZ;
+ALTER TABLE project_files ADD COLUMN IF NOT EXISTS size BIGINT;
CREATE TABLE IF NOT EXISTS entry_photos (
id SERIAL PRIMARY KEY,
diff --git a/lib/file-sizes.js b/lib/file-sizes.js
new file mode 100644
index 0000000..e22213b
--- /dev/null
+++ b/lib/file-sizes.js
@@ -0,0 +1,23 @@
+async function ensureProjectFileSizeColumn(pool) {
+ await pool.query('ALTER TABLE project_files ADD COLUMN IF NOT EXISTS size BIGINT');
+}
+
+async function backfillProjectFileSizes(pool, storage) {
+ const { rows } = await pool.query('SELECT id, path FROM project_files WHERE size IS NULL ORDER BY id');
+ if (!rows.length) return 0;
+ const objects = await storage.listAll('');
+ const sizes = new Map(objects.map(o => [o.key, o.size || 0]));
+ let updated = 0;
+ for (const row of rows) {
+ const key = storage.keyFromPath(row.path);
+ const size = key && sizes.has(key) ? sizes.get(key) : 0;
+ const { rowCount } = await pool.query(
+ 'UPDATE project_files SET size = $1 WHERE id = $2 AND size IS NULL',
+ [size, row.id]
+ );
+ updated += rowCount;
+ }
+ return updated;
+}
+
+module.exports = { ensureProjectFileSizeColumn, backfillProjectFileSizes };
diff --git a/public/files.html b/public/files.html
index 1de21ef..2ee6821 100644
--- a/public/files.html
+++ b/public/files.html
@@ -36,6 +36,23 @@
diff --git a/public/js/files.js b/public/js/files.js
index a197482..b7eaf43 100644
--- a/public/js/files.js
+++ b/public/js/files.js
@@ -123,6 +123,14 @@ async function loadFiles() {
if (df) p.set('date_from', df);
if (dt) p.set('date_to', dt);
}
+ const size = document.getElementById('sizeFilter').value;
+ if (size) {
+ const [minSize, maxSize] = size.split('-');
+ if (minSize) p.set('min_size', minSize);
+ if (maxSize) p.set('max_size', maxSize);
+ }
+ const order = document.getElementById('sortOrder').value;
+ if (order && order !== 'new') p.set('sort', order);
p.set('limit', PAGE_SIZE);
p.set('offset', (page - 1) * PAGE_SIZE);
const res = await fetch(`${API}/api/files${mode === 'detached' ? '/detached' : ''}?${p}`, { headers: hdr() });
@@ -142,6 +150,8 @@ document.getElementById('studentFilter').addEventListener('change', () => { page
document.getElementById('groupFilter').addEventListener('change', () => { page = 1; loadFiles(); });
document.getElementById('dateFrom').addEventListener('change', () => { page = 1; loadFiles(); });
document.getElementById('dateTo').addEventListener('change', () => { page = 1; loadFiles(); });
+document.getElementById('sizeFilter').addEventListener('change', () => { page = 1; loadFiles(); });
+document.getElementById('sortOrder').addEventListener('change', () => { page = 1; loadFiles(); });
document.getElementById('searchInput').addEventListener('input', () => {
clearTimeout(searchTimer);
searchTimer = setTimeout(() => { page = 1; loadFiles(); }, 300);
diff --git a/server.js b/server.js
index f2ca77a..b8a9907 100644
--- a/server.js
+++ b/server.js
@@ -47,6 +47,7 @@ const {
const { normalizeStudentStatus, ensureStudentsTable } = require('./lib/students');
const { lessonReportWriteBlocked } = require('./lib/lesson-reports');
const { groupOwnedBy } = require('./lib/groups');
+const { ensureProjectFileSizeColumn, backfillProjectFileSizes } = require('./lib/file-sizes');
const https = require('https');
const path = require('path');
@@ -6387,8 +6388,8 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
}
for (const x of ndata.project_files) {
await client.query(
- 'INSERT INTO project_files (id, entry_id, token, path, name, detached_at, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7)',
- [x.id, x.entry_id, x.token, x.path, x.name, x.detached_at, x.created_at]
+ 'INSERT INTO project_files (id, entry_id, token, path, name, detached_at, created_at, size) VALUES ($1,$2,$3,$4,$5,$6,$7,$8)',
+ [x.id, x.entry_id, x.token, x.path, x.name, x.detached_at, x.created_at, x.size]
);
}
for (const x of ndata.group_photos) {
@@ -6566,6 +6567,7 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
cleanupUpload(req);
try {
await sweepOrphanedUploads().catch(err => console.error('Upload sweep:', err));
+ await backfillProjectFileSizes(pool, storage).catch(err => console.error('Project file sizes:', err));
await loadBans().catch(err => console.error('Bans reload:', err));
await ensureFirstAdmin().catch(err => console.error('First admin:', err));
await logAudit(req, 'backup.restore', { format_version: formatVersion });
@@ -9634,8 +9636,8 @@ app.post('/api/entries/:id/files', requireAuth, (req, res, next) => {
for (const f of files) {
const token = crypto.randomBytes(16).toString('hex');
await client.query(
- 'INSERT INTO project_files (entry_id, token, path, name) VALUES ($1, $2, $3, $4)',
- [entryId, token, `/uploads/${f.filename}`, f.originalname]
+ 'INSERT INTO project_files (entry_id, token, path, name, size) VALUES ($1, $2, $3, $4, $5)',
+ [entryId, token, `/uploads/${f.filename}`, f.originalname, f.size || 0]
);
}
await client.query('COMMIT');
@@ -9716,7 +9718,7 @@ async function sendPlayableFile(req, res, key, name) {
}
app.get('/api/files', requireAuth, async (req, res) => {
- const { search, student_name, group_id, date_from, date_to, limit, offset } = req.query;
+ const { search, student_name, group_id, date_from, date_to, limit, offset, min_size, max_size, sort } = req.query;
const conditions = [];
const params = [];
conditions.push('e.deleted_at IS NULL');
@@ -9725,6 +9727,10 @@ app.get('/api/files', requireAuth, async (req, res) => {
if (group_id) { params.push(group_id); conditions.push(`e.group_id = $${params.length}`); }
if (date_from) { params.push(date_from); conditions.push(`e.created_at >= ${tzDayStart(params.length)}`); }
if (date_to) { params.push(date_to); conditions.push(`e.created_at < ${tzDayEnd(params.length)}`); }
+ const minSize = parseInt(min_size, 10);
+ if (Number.isFinite(minSize) && minSize >= 0) { params.push(minSize); conditions.push(`pf.size >= $${params.length}`); }
+ const maxSize = parseInt(max_size, 10);
+ if (Number.isFinite(maxSize) && maxSize > 0) { params.push(maxSize); conditions.push(`pf.size < $${params.length}`); }
if (req.user.role !== 'admin') {
if (group_id && !(await groupBelongsToBranches(req.user, group_id))) {
return res.status(403).json({ error: 'Нет доступа к этой группе' });
@@ -9743,11 +9749,17 @@ app.get('/api/files', requireAuth, async (req, res) => {
params
);
const total = crows[0].n;
- let q = `SELECT pf.id, pf.token, pf.name, pf.path, e.student_name, e.created_at, g.name AS group_name
+ const sorts = {
+ new: 'pf.id DESC',
+ old: 'pf.id ASC',
+ size_desc: 'pf.size DESC NULLS LAST, pf.id DESC',
+ size_asc: 'pf.size ASC NULLS LAST, pf.id DESC',
+ };
+ let q = `SELECT pf.id, pf.token, pf.name, pf.path, pf.size, e.student_name, e.created_at, g.name AS group_name
FROM project_files pf
JOIN entries e ON e.id = pf.entry_id
JOIN groups g ON g.id = e.group_id${where}
- ORDER BY pf.id DESC`;
+ ORDER BY ${Object.prototype.hasOwnProperty.call(sorts, sort) ? sorts[sort] : sorts.new}`;
const qparams = params.slice();
const lim = parseInt(limit, 10);
if (lim > 0) { qparams.push(lim); q += ` LIMIT $${qparams.length}`; }
@@ -9755,26 +9767,40 @@ app.get('/api/files', requireAuth, async (req, res) => {
if (off > 0) { qparams.push(off); q += ` OFFSET $${qparams.length}`; }
const { rows } = await pool.query(q, qparams);
const files = await Promise.all(rows.map(async r => {
- const size = await storage.sizeOf(r.path);
- return { id: r.id, token: r.token, name: r.name, student_name: r.student_name, group_name: r.group_name, created_at: r.created_at, size };
+ let size = r.size;
+ if (size == null) {
+ size = await storage.sizeOf(r.path);
+ pool.query('UPDATE project_files SET size = $1 WHERE id = $2 AND size IS NULL', [size, r.id]).catch(() => {});
+ }
+ return { id: r.id, token: r.token, name: r.name, student_name: r.student_name, group_name: r.group_name, created_at: r.created_at, size: Number(size) || 0 };
}));
res.json({ files, total });
});
app.get('/api/files/detached', requireAdmin, async (req, res) => {
- const { search, limit, offset } = req.query;
+ const { search, limit, offset, min_size, max_size, sort } = req.query;
const conditions = [];
const params = [];
conditions.push('entry_id IS NULL');
if (search) { params.push(`%${search}%`); conditions.push(`name ILIKE $${params.length}`); }
+ const minSize = parseInt(min_size, 10);
+ if (Number.isFinite(minSize) && minSize >= 0) { params.push(minSize); conditions.push(`size >= $${params.length}`); }
+ const maxSize = parseInt(max_size, 10);
+ if (Number.isFinite(maxSize) && maxSize > 0) { params.push(maxSize); conditions.push(`size < $${params.length}`); }
const where = conditions.join(' AND ');
const { rows: crows } = await pool.query(
`SELECT count(*)::int AS n FROM project_files WHERE ${where}`,
params
);
const total = crows[0].n;
- let q = `SELECT id, token, name, path, created_at FROM project_files
- WHERE ${where} ORDER BY created_at DESC`;
+ const sorts = {
+ new: 'created_at DESC',
+ old: 'created_at ASC',
+ size_desc: 'size DESC NULLS LAST, created_at DESC',
+ size_asc: 'size ASC NULLS LAST, created_at DESC',
+ };
+ let q = `SELECT id, token, name, path, size, created_at FROM project_files
+ WHERE ${where} ORDER BY ${Object.prototype.hasOwnProperty.call(sorts, sort) ? sorts[sort] : sorts.new}`;
const qparams = params.slice();
const lim = parseInt(limit, 10);
if (lim > 0) { qparams.push(lim); q += ` LIMIT $${qparams.length}`; }
@@ -9782,8 +9808,12 @@ app.get('/api/files/detached', requireAdmin, async (req, res) => {
if (off > 0) { qparams.push(off); q += ` OFFSET $${qparams.length}`; }
const { rows } = await pool.query(q, qparams);
const files = await Promise.all(rows.map(async r => {
- const size = await storage.sizeOf(r.path);
- return { id: r.id, token: r.token, name: r.name, created_at: r.created_at, size };
+ let size = r.size;
+ if (size == null) {
+ size = await storage.sizeOf(r.path);
+ pool.query('UPDATE project_files SET size = $1 WHERE id = $2 AND size IS NULL', [size, r.id]).catch(() => {});
+ }
+ return { id: r.id, token: r.token, name: r.name, created_at: r.created_at, size: Number(size) || 0 };
}));
res.json({ files, total });
});
@@ -11060,8 +11090,8 @@ app.post('/api/entries', entryLimiter, (req, res, next) => {
for (const f of projectFiles) {
const token = crypto.randomBytes(16).toString('hex');
await client.query(
- 'INSERT INTO project_files (entry_id, token, path, name) VALUES ($1, $2, $3, $4)',
- [rows[0].id, token, `/uploads/${f.filename}`, f.originalname]
+ 'INSERT INTO project_files (entry_id, token, path, name, size) VALUES ($1, $2, $3, $4, $5)',
+ [rows[0].id, token, `/uploads/${f.filename}`, f.originalname, f.size || 0]
);
}
await client.query('COMMIT');
@@ -13379,6 +13409,7 @@ if (fs.existsSync(certPath) && fs.existsSync(keyPath)) {
try { await ensureStudentPhotosTable(); } catch (err) { console.error('Student photos table:', err); }
try { await ensureStudentsTable(pool); } catch (err) { console.error('Students table:', err); }
try { await ensurePhotoOriginalColumn(); } catch (err) { console.error('Entry original photo column:', err); }
+ try { await ensureProjectFileSizeColumn(pool); } catch (err) { console.error('Project file size column:', err); }
try { await ensureFaceTables(); } catch (err) { console.error('Face tables:', err); }
try { await ensureEntryAiColumns(); } catch (err) { console.error('Entry AI columns:', err); }
try { await ensurePhotoJobsTable(); } catch (err) { console.error('Photo jobs table:', err); }
@@ -13404,6 +13435,7 @@ try { await ensureFeedbacksTable(); } catch (err) { console.error('Feedbacks tab
console.error('S3 bucket init:', err.message);
}
}
+ backfillProjectFileSizes(pool, storage).then(n => { if (n) console.log('Project file sizes backfilled:', n); }).catch(err => console.error('Project file sizes:', err));
try { await purgeScheduledDeletions(); } catch (err) { console.error('Trash purge:', err); }
setInterval(() => { purgeScheduledDeletions().catch(err => console.error('Trash purge:', err)); }, 60 * 60 * 1000).unref();
setInterval(() => {