Spaces:
Paused
Paused
Update server.js
Browse files
server.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
| 1 |
// ==========================================
|
| 2 |
-
// PIXELDRIVE v4.
|
|
|
|
|
|
|
| 3 |
// ==========================================
|
| 4 |
import express from 'express';
|
| 5 |
import session from 'express-session';
|
|
@@ -37,6 +39,7 @@ const IS_PROD = process.env.NODE_ENV === 'production';
|
|
| 37 |
const USER_QUOTA = parseInt(process.env.USER_QUOTA_GB || '50', 10) * 1024 * 1024 * 1024;
|
| 38 |
const DAILY_TRANSFER = parseInt(process.env.DAILY_TRANSFER_GB || '100', 10) * 1024 * 1024 * 1024;
|
| 39 |
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
|
|
| 40 |
|
| 41 |
function log(level, msg) {
|
| 42 |
const n = new Date();
|
|
@@ -86,19 +89,24 @@ async function pngToBuffer(pngBuffer, expectedLen) {
|
|
| 86 |
return rgb.subarray(0, expectedLen);
|
| 87 |
}
|
| 88 |
|
|
|
|
|
|
|
|
|
|
| 89 |
db.exec(`
|
| 90 |
CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password_hash BLOB NOT NULL, salt BLOB NOT NULL, is_admin INTEGER DEFAULT 0, tos_accepted INTEGER DEFAULT 0, avatar BLOB, created_at INTEGER DEFAULT (strftime('%s','now')));
|
| 91 |
CREATE TABLE IF NOT EXISTS folders (id INTEGER PRIMARY KEY AUTOINCREMENT, parent_id INTEGER REFERENCES folders(id) ON DELETE CASCADE, owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, name TEXT NOT NULL, created_at INTEGER DEFAULT (strftime('%s','now')), UNIQUE(parent_id, owner_id, name));
|
| 92 |
CREATE TABLE IF NOT EXISTS files (id TEXT PRIMARY KEY, folder_id INTEGER REFERENCES folders(id) ON DELETE SET NULL, owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, name TEXT NOT NULL, mime TEXT NOT NULL, size INTEGER NOT NULL, chunk_count INTEGER DEFAULT 1, status TEXT DEFAULT 'pending', progress REAL DEFAULT 0, error_msg TEXT, encryption_key_hash TEXT NOT NULL, master_key_enc BLOB, created_at INTEGER DEFAULT (strftime('%s','now')), updated_at INTEGER DEFAULT (strftime('%s','now')));
|
| 93 |
CREATE TABLE IF NOT EXISTS file_chunks (id INTEGER PRIMARY KEY AUTOINCREMENT, file_id TEXT NOT NULL REFERENCES files(id) ON DELETE CASCADE, chunk_index INTEGER NOT NULL, imgbb_url TEXT, imgbb_delete_url TEXT, imgbb_id TEXT, size INTEGER NOT NULL, encrypted_len INTEGER NOT NULL, UNIQUE(file_id, chunk_index));
|
| 94 |
-
CREATE TABLE IF NOT EXISTS share_links (token TEXT PRIMARY KEY, file_id TEXT NOT NULL REFERENCES files(id) ON DELETE CASCADE, owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, type TEXT NOT NULL, created_at INTEGER DEFAULT (strftime('%s','now')), expires_at INTEGER);
|
| 95 |
CREATE TABLE IF NOT EXISTS user_shares (id INTEGER PRIMARY KEY AUTOINCREMENT, file_id TEXT REFERENCES files(id) ON DELETE CASCADE, folder_id INTEGER REFERENCES folders(id) ON DELETE CASCADE, owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, shared_with INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, created_at INTEGER DEFAULT (strftime('%s','now')));
|
| 96 |
CREATE TABLE IF NOT EXISTS transfer_daily (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, day TEXT NOT NULL, up_bytes INTEGER DEFAULT 0, down_bytes INTEGER DEFAULT 0, UNIQUE(user_id, day));
|
|
|
|
| 97 |
CREATE INDEX IF NOT EXISTS idx_files_owner ON files(owner_id);
|
| 98 |
CREATE INDEX IF NOT EXISTS idx_chunks_file ON file_chunks(file_id);
|
| 99 |
CREATE INDEX IF NOT EXISTS idx_share_owner ON share_links(owner_id);
|
| 100 |
CREATE INDEX IF NOT EXISTS idx_ushares_with ON user_shares(shared_with);
|
| 101 |
CREATE INDEX IF NOT EXISTS idx_transfer_day ON transfer_daily(user_id, day);
|
|
|
|
| 102 |
`);
|
| 103 |
|
| 104 |
function runMigrations() {
|
|
@@ -126,11 +134,16 @@ function runMigrations() {
|
|
| 126 |
}
|
| 127 |
}
|
| 128 |
if (updatedAdded) db.exec(`UPDATE files SET updated_at = strftime('%s','now') WHERE updated_at = 0;`);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all().map(t => t.name);
|
| 130 |
if (!tables.includes('folders')) db.exec(`CREATE TABLE folders (id INTEGER PRIMARY KEY AUTOINCREMENT, parent_id INTEGER REFERENCES folders(id) ON DELETE CASCADE, owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, name TEXT NOT NULL, created_at INTEGER DEFAULT (strftime('%s','now')), UNIQUE(parent_id, owner_id, name));`);
|
| 131 |
-
if (!tables.includes('share_links')) db.exec(`CREATE TABLE share_links (token TEXT PRIMARY KEY, file_id TEXT NOT NULL REFERENCES files(id) ON DELETE CASCADE, owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, type TEXT NOT NULL, created_at INTEGER DEFAULT (strftime('%s','now')), expires_at INTEGER);`);
|
| 132 |
if (!tables.includes('user_shares')) db.exec(`CREATE TABLE user_shares (id INTEGER PRIMARY KEY AUTOINCREMENT, file_id TEXT REFERENCES files(id) ON DELETE CASCADE, folder_id INTEGER REFERENCES folders(id) ON DELETE CASCADE, owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, shared_with INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, created_at INTEGER DEFAULT (strftime('%s','now'))); CREATE INDEX idx_ushares_with ON user_shares(shared_with);`);
|
| 133 |
if (!tables.includes('transfer_daily')) db.exec(`CREATE TABLE transfer_daily (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, day TEXT NOT NULL, up_bytes INTEGER DEFAULT 0, down_bytes INTEGER DEFAULT 0, UNIQUE(user_id, day)); CREATE INDEX idx_transfer_day ON transfer_daily(user_id, day);`);
|
|
|
|
| 134 |
const sessionsCols = tables.includes('sessions') ? db.prepare("PRAGMA table_info(sessions)").all().map(c => c.name) : [];
|
| 135 |
if (tables.includes('sessions') && (!sessionsCols.includes('data') || !sessionsCols.includes('expires_at'))) {
|
| 136 |
log('WARN', 'Table sessions invalide → reconstruction');
|
|
@@ -165,6 +178,11 @@ function addTransfer(userId, bytes, dir) {
|
|
| 165 |
}
|
| 166 |
function transferBlocked(userId) { return getTransfer(userId).total >= DAILY_TRANSFER; }
|
| 167 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
// --- NETTOYAGE + BACKUPS ---
|
| 169 |
function cleanTemp() {
|
| 170 |
try {
|
|
@@ -186,28 +204,23 @@ function backupDb() {
|
|
| 186 |
log('INFO', `Backup BDD: ${name}`);
|
| 187 |
} catch (e) { log('ERROR', `Backup échoué: ${e.message}`); }
|
| 188 |
}
|
| 189 |
-
function
|
| 190 |
try {
|
| 191 |
-
const
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
const olds = db.prepare("SELECT id FROM files WHERE status='error' AND updated_at < ?").all(cutoff);
|
| 193 |
-
for (const f of olds) {
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
}
|
| 197 |
-
if (olds.length) log('INFO', `Cleanup: ${olds.length} fichier(s) en erreur supprimé(s)`);
|
| 198 |
-
} catch (e) { log('WARN', `Error-files cleanup: ${e.message}`); }
|
| 199 |
-
}
|
| 200 |
-
function cleanOldTransfers() {
|
| 201 |
-
try {
|
| 202 |
-
const old = new Date(Date.now() - 3 * 86400000).toISOString().slice(0, 10);
|
| 203 |
-
const r = db.prepare('DELETE FROM transfer_daily WHERE day < ?').run(old);
|
| 204 |
-
if (r.changes) log('INFO', `Cleanup: ${r.changes} ligne(s) transfer_daily`);
|
| 205 |
-
} catch (e) { log('WARN', `Transfer cleanup: ${e.message}`); }
|
| 206 |
}
|
| 207 |
mkdirSync(TEMP_DIR, { recursive: true });
|
| 208 |
mkdirSync(THUMB_DIR, { recursive: true });
|
| 209 |
cleanTemp();
|
| 210 |
-
setInterval(
|
| 211 |
setInterval(backupDb, 6 * 3600000);
|
| 212 |
setTimeout(backupDb, 60000);
|
| 213 |
|
|
@@ -290,13 +303,6 @@ class ByteLRUCache extends LRUCache { constructor(){ super({maxSize:CACHE_MAX_BY
|
|
| 290 |
const fileCache = new ByteLRUCache();
|
| 291 |
setInterval(()=>{ const m = process.memoryUsage(); if(m.rss > 13*1024*1024*1024){ log('ALERT', `RAM ${(m.rss/1e9).toFixed(1)}GB → vidage du cache`); fileCache.clear(); if(global.gc) global.gc(); } }, 30000);
|
| 292 |
|
| 293 |
-
setInterval(() => {
|
| 294 |
-
const now = Date.now();
|
| 295 |
-
const s = db.prepare('DELETE FROM sessions WHERE expires_at < ?').run(now);
|
| 296 |
-
const l = db.prepare('DELETE FROM share_links WHERE expires_at IS NOT NULL AND expires_at < ?').run(now);
|
| 297 |
-
if (s.changes || l.changes) log('INFO', `Cleanup: ${s.changes} session(s), ${l.changes} lien(s) expiré(s)`);
|
| 298 |
-
}, 3600000);
|
| 299 |
-
|
| 300 |
let nsfwModel = null;
|
| 301 |
async function loadNsfwModel(){ try{ await tf.setBackend('wasm'); tf.wasm.setWasmPaths('/app/tfjs_wasm/','tfjs-backend-wasm.wasm'); await tf.ready(); nsfwModel = await nsfwjs.load('/app/tfjs_wasm/',{type:'mobilenet_v2',size:224}); log('INFO', 'NSFW WASM chargé'); }catch(e){ log('WARN', `NSFW load fail: ${e.message}`); } }
|
| 302 |
loadNsfwModel();
|
|
@@ -382,13 +388,12 @@ async function streamFile(res,file,key,range,counterUserId){
|
|
| 382 |
if(cs > e) break;
|
| 383 |
}
|
| 384 |
res.end();
|
| 385 |
-
if (counterUserId) addTransfer(counterUserId, sentBytes, 'down');
|
| 386 |
}
|
| 387 |
|
| 388 |
const sseClients = new Map();
|
| 389 |
function broadcast(fid,d){ const cs = sseClients.get(fid); if(cs){ const p = `data: ${JSON.stringify(d)}\n\n`; for(const r of cs) r.write(p); } }
|
| 390 |
|
| 391 |
-
// ✅ TEMPLATE EMBED (public/embed.html)
|
| 392 |
let EMBED_TPL = null;
|
| 393 |
function embedTpl() {
|
| 394 |
if (EMBED_TPL === null) {
|
|
@@ -423,6 +428,7 @@ app.post('/api/login', loginLimit, async(req,res)=>{
|
|
| 423 |
catch(e) { log('ERROR', `Session regenerate échouée: ${e.message}`); return res.status(500).json({error:'Erreur session'}); }
|
| 424 |
req.session.userId = usr.id; req.session.isAdmin = !!usr.is_admin; req.session.tosAccepted = !!usr.tos_accepted; req.session.username = usr.username;
|
| 425 |
log('INFO', `Connexion: ${u}`);
|
|
|
|
| 426 |
res.json({ok:true,user:{id:usr.id,username:usr.username,isAdmin:!!usr.is_admin,tosAccepted:!!usr.tos_accepted}});
|
| 427 |
});
|
| 428 |
app.post('/api/logout',(req,res)=>req.session.destroy(()=>res.json({ok:true})));
|
|
@@ -436,7 +442,48 @@ app.get('/api/me',(req,res)=>{
|
|
| 436 |
});
|
| 437 |
app.post('/api/tos/accept',requireAuth,(req,res)=>{db.prepare('UPDATE users SET tos_accepted=1 WHERE id=?').run(req.session.userId);req.session.tosAccepted=true;res.json({ok:true});});
|
| 438 |
|
| 439 |
-
// ✅
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 440 |
app.get('/api/admin/stats', requireAuth, requireAdmin, (req,res) => {
|
| 441 |
const users = db.prepare('SELECT COUNT(*) c FROM users').get().c;
|
| 442 |
const files = db.prepare('SELECT COUNT(*) c, COALESCE(SUM(size),0) s FROM files').get();
|
|
@@ -454,13 +501,16 @@ app.get('/api/admin/users', requireAuth, requireAdmin, (req,res) => {
|
|
| 454 |
transferToday: getTransfer(u.id).total,
|
| 455 |
})));
|
| 456 |
});
|
|
|
|
|
|
|
|
|
|
| 457 |
app.delete('/api/admin/users/:id', requireAuth, requireAdmin, (req,res) => {
|
| 458 |
const id = parseInt(req.params.id, 10);
|
| 459 |
if (!id) return res.status(400).json({error:'ID invalide'});
|
| 460 |
if (id === req.session.userId) return res.status(400).json({error:'Impossible de supprimer votre propre compte'});
|
| 461 |
-
const urls = db.prepare('SELECT fc.imgbb_delete_url FROM file_chunks fc JOIN files f ON f.id
|
| 462 |
db.prepare('DELETE FROM users WHERE id=?').run(id);
|
| 463 |
-
log('ALERT', `Admin ${req.session.username} a supprimé le compte #${id}
|
| 464 |
(async () => { for (const u of urls) await imgbbDelete(u); })();
|
| 465 |
res.json({ok:true});
|
| 466 |
});
|
|
@@ -508,7 +558,7 @@ app.post('/api/folders/:id/rename',requireAuth,(req,res)=>{
|
|
| 508 |
if(!name || typeof name !== 'string' || !name.trim() || name.length > 100) return res.status(400).json({error:'Nom invalide'});
|
| 509 |
const fo = db.prepare('SELECT id FROM folders WHERE id=? AND owner_id=?').get(req.params.id, req.session.userId);
|
| 510 |
if(!fo) return res.status(404).json({error:'Introuvable'});
|
| 511 |
-
try { db.prepare('UPDATE folders SET name=? WHERE id=?').run(name.trim(), req.params.id); res.json({ok:true}); }
|
| 512 |
catch(e){ res.status(409).json({error:'Un dossier porte déjà ce nom'}); }
|
| 513 |
});
|
| 514 |
app.post('/api/folders/:id/move',requireAuth,(req,res)=>{
|
|
@@ -526,6 +576,7 @@ app.post('/api/folders/:id/move',requireAuth,(req,res)=>{
|
|
| 526 |
}
|
| 527 |
}
|
| 528 |
db.prepare('UPDATE folders SET parent_id=? WHERE id=?').run(parent_id || null, req.params.id);
|
|
|
|
| 529 |
res.json({ok:true});
|
| 530 |
});
|
| 531 |
|
|
@@ -545,6 +596,7 @@ app.post('/api/files/:id/rename',requireAuth,(req,res)=>{
|
|
| 545 |
const f = db.prepare('SELECT id FROM files WHERE id=? AND owner_id=?').get(req.params.id, req.session.userId);
|
| 546 |
if(!f) return res.status(404).json({error:'Introuvable'});
|
| 547 |
db.prepare('UPDATE files SET name=? WHERE id=?').run(name.trim(), req.params.id);
|
|
|
|
| 548 |
res.json({ok:true});
|
| 549 |
});
|
| 550 |
app.post('/api/files/:id/move',requireAuth,(req,res)=>{
|
|
@@ -557,6 +609,7 @@ app.post('/api/files/:id/move',requireAuth,(req,res)=>{
|
|
| 557 |
if (!target || target.owner_id !== req.session.userId) return res.status(403).json({error:'Dossier cible invalide'});
|
| 558 |
}
|
| 559 |
db.prepare('UPDATE files SET folder_id=? WHERE id=?').run(folder_id || null, req.params.id);
|
|
|
|
| 560 |
res.json({ok:true});
|
| 561 |
});
|
| 562 |
|
|
@@ -572,6 +625,7 @@ app.post('/api/share-user',requireAuth,requireTos,shareLimit,(req,res)=>{
|
|
| 572 |
if (db.prepare(`SELECT 1 FROM user_shares WHERE ${col}=? AND shared_with=?`).get(id, target.id)) return res.status(409).json({error:'Déjà partagé'});
|
| 573 |
db.prepare(`INSERT INTO user_shares(${col},owner_id,shared_with) VALUES(?,?,?)`).run(id, req.session.userId, target.id);
|
| 574 |
log('INFO', `Partage ${type} ${id} → ${username.trim()}`);
|
|
|
|
| 575 |
res.json({ok:true});
|
| 576 |
});
|
| 577 |
|
|
@@ -659,6 +713,7 @@ async function processUpload(fid,path,mk,cc,mime,fsize,username,uid){
|
|
| 659 |
db.prepare("UPDATE files SET status='ready',progress=100 WHERE id=?").run(fid);
|
| 660 |
broadcast(fid,{type:'progress',progress:100,status:'ready',type:'done'});
|
| 661 |
addTransfer(uid, fsize, 'up');
|
|
|
|
| 662 |
const secs = (Date.now()-t0)/1000;
|
| 663 |
log('INFO', `Upload terminé: ${fid} en ${secs.toFixed(1)}s (${(fsize/1048576/secs).toFixed(2)} MB/s)`);
|
| 664 |
}catch(e){
|
|
@@ -678,33 +733,38 @@ app.get('/api/files/:id/download',requireAuth,async(req,res)=>{
|
|
| 678 |
const f = canAccessFile(req.session.userId, req.params.id);
|
| 679 |
if(!f)return res.status(404).json({error:'Introuvable'});
|
| 680 |
if(f.status!=='ready')return res.status(409).json({error:'Pas prêt',status:f.status});
|
|
|
|
| 681 |
const k = await getMasterKey(f.id);
|
| 682 |
await streamFile(res,f,k,req.headers.range,req.session.userId);
|
| 683 |
});
|
| 684 |
|
|
|
|
| 685 |
app.post('/api/files/:id/share',requireAuth,shareLimit,async(req,res)=>{
|
| 686 |
const f=db.prepare('SELECT * FROM files WHERE id=? AND owner_id=?').get(req.params.id,req.session.userId);
|
| 687 |
if(!f||f.status!=='ready') return res.status(404).json({error:'Fichier non disponible'});
|
| 688 |
-
const
|
|
|
|
|
|
|
| 689 |
db.prepare('INSERT INTO share_links(token,file_id,owner_id,type,expires_at) VALUES(?,?,?,?,?)').run(pt,f.id,req.session.userId,'embed',expires);
|
| 690 |
db.prepare('INSERT INTO share_links(token,file_id,owner_id,type,expires_at) VALUES(?,?,?,?,?)').run(dt2,f.id,req.session.userId,'download',expires);
|
| 691 |
-
|
|
|
|
| 692 |
});
|
| 693 |
|
| 694 |
-
// ✅ /s/:
|
| 695 |
app.get('/s/:token',async(req,res)=>{
|
| 696 |
const tpl = embedTpl();
|
| 697 |
const serve = (status, data, og) => {
|
| 698 |
if (!tpl) return res.status(status).send('Lien invalide');
|
| 699 |
-
const out = tpl
|
| 700 |
-
.replace('__OG_META__', og || '')
|
| 701 |
-
.replace('__EMBED_DATA__', JSON.stringify(data).replace(/</g, '\\u003c'));
|
| 702 |
res.status(status).send(out);
|
| 703 |
};
|
| 704 |
const l = db.prepare('SELECT * FROM share_links WHERE token=? AND type=? AND (expires_at IS NULL OR expires_at>?)').get(req.params.token,'embed',Date.now());
|
| 705 |
if (!l) return serve(404, { error: 'Lien invalide ou expiré' });
|
| 706 |
const f = db.prepare('SELECT * FROM files WHERE id=?').get(l.file_id);
|
| 707 |
if (!f) return serve(404, { error: 'Fichier supprimé' });
|
|
|
|
|
|
|
| 708 |
let dt;
|
| 709 |
const existing = db.prepare('SELECT token FROM share_links WHERE file_id=? AND type=? AND owner_id=? AND (expires_at IS NULL OR expires_at>?)').get(f.id,'download',l.owner_id,Date.now());
|
| 710 |
if (existing) dt = existing.token;
|
|
@@ -714,12 +774,15 @@ app.get('/s/:token',async(req,res)=>{
|
|
| 714 |
serve(200, { name: f.name, size: f.size, mime: f.mime, dl: '/d/' + dt }, og);
|
| 715 |
});
|
| 716 |
|
|
|
|
| 717 |
app.get('/d/:token',async(req,res)=>{
|
| 718 |
const l=db.prepare('SELECT * FROM share_links WHERE token=? AND type=? AND (expires_at IS NULL OR expires_at>?)').get(req.params.token,'download',Date.now());
|
| 719 |
if(!l)return res.status(404).json({error:'Invalide'});
|
| 720 |
const f=db.prepare('SELECT * FROM files WHERE id=?').get(l.file_id);
|
| 721 |
if(!f||f.status!=='ready')return res.status(404).json({error:'Indisponible'});
|
| 722 |
if (transferBlocked(f.owner_id)) { log('ALERT', `Quota transit propriétaire atteint: ${f.id}`); return res.status(429).json({error:'Quota journalier du propriétaire atteint'}); }
|
|
|
|
|
|
|
| 723 |
log('INFO', `Téléchargement public /d/${req.params.token} (${f.name})`);
|
| 724 |
const mk = decryptMasterKey(db.prepare('SELECT master_key_enc FROM files WHERE id=?').get(f.id).master_key_enc);
|
| 725 |
await streamFile(res,f,mk,req.headers.range,f.owner_id);
|
|
@@ -734,6 +797,7 @@ app.delete('/api/files/:id',requireAuth,async(req,res)=>{
|
|
| 734 |
db.prepare('DELETE FROM files WHERE id=?').run(f.id);
|
| 735 |
fileCache.delete(`chunk:${f.id}:0`);
|
| 736 |
try{unlinkSync(join(THUMB_DIR,`${f.id}.jpg`));}catch(_){}
|
|
|
|
| 737 |
res.json({ok:true});
|
| 738 |
});
|
| 739 |
|
|
@@ -774,5 +838,5 @@ app.use((err, req, res, next) => {
|
|
| 774 |
res.status(500).json({ error: 'Internal Server Error' });
|
| 775 |
});
|
| 776 |
|
| 777 |
-
const server = app.listen(PORT, '0.0.0.0', () => log('INFO', `PixelDrive v4.
|
| 778 |
process.on('SIGTERM', () => { log('WARN', 'SIGTERM reçu, arrêt...'); server.close(() => process.exit(0)); });
|
|
|
|
| 1 |
// ==========================================
|
| 2 |
+
// PIXELDRIVE v4.8 - SERVER.JS (ESM)
|
| 3 |
+
// + password change, account delete, activity log, stats,
|
| 4 |
+
// share TTL, view/download counters
|
| 5 |
// ==========================================
|
| 6 |
import express from 'express';
|
| 7 |
import session from 'express-session';
|
|
|
|
| 39 |
const USER_QUOTA = parseInt(process.env.USER_QUOTA_GB || '50', 10) * 1024 * 1024 * 1024;
|
| 40 |
const DAILY_TRANSFER = parseInt(process.env.DAILY_TRANSFER_GB || '100', 10) * 1024 * 1024 * 1024;
|
| 41 |
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
| 42 |
+
const TTL_ALLOWED = [1, 24, 168, 720]; // ✅ 1h / 24h / 7j / 30j
|
| 43 |
|
| 44 |
function log(level, msg) {
|
| 45 |
const n = new Date();
|
|
|
|
| 89 |
return rgb.subarray(0, expectedLen);
|
| 90 |
}
|
| 91 |
|
| 92 |
+
// ==========================================
|
| 93 |
+
// SCHÉMA (+ activity, + compteurs views/downloads)
|
| 94 |
+
// ==========================================
|
| 95 |
db.exec(`
|
| 96 |
CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password_hash BLOB NOT NULL, salt BLOB NOT NULL, is_admin INTEGER DEFAULT 0, tos_accepted INTEGER DEFAULT 0, avatar BLOB, created_at INTEGER DEFAULT (strftime('%s','now')));
|
| 97 |
CREATE TABLE IF NOT EXISTS folders (id INTEGER PRIMARY KEY AUTOINCREMENT, parent_id INTEGER REFERENCES folders(id) ON DELETE CASCADE, owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, name TEXT NOT NULL, created_at INTEGER DEFAULT (strftime('%s','now')), UNIQUE(parent_id, owner_id, name));
|
| 98 |
CREATE TABLE IF NOT EXISTS files (id TEXT PRIMARY KEY, folder_id INTEGER REFERENCES folders(id) ON DELETE SET NULL, owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, name TEXT NOT NULL, mime TEXT NOT NULL, size INTEGER NOT NULL, chunk_count INTEGER DEFAULT 1, status TEXT DEFAULT 'pending', progress REAL DEFAULT 0, error_msg TEXT, encryption_key_hash TEXT NOT NULL, master_key_enc BLOB, created_at INTEGER DEFAULT (strftime('%s','now')), updated_at INTEGER DEFAULT (strftime('%s','now')));
|
| 99 |
CREATE TABLE IF NOT EXISTS file_chunks (id INTEGER PRIMARY KEY AUTOINCREMENT, file_id TEXT NOT NULL REFERENCES files(id) ON DELETE CASCADE, chunk_index INTEGER NOT NULL, imgbb_url TEXT, imgbb_delete_url TEXT, imgbb_id TEXT, size INTEGER NOT NULL, encrypted_len INTEGER NOT NULL, UNIQUE(file_id, chunk_index));
|
| 100 |
+
CREATE TABLE IF NOT EXISTS share_links (token TEXT PRIMARY KEY, file_id TEXT NOT NULL REFERENCES files(id) ON DELETE CASCADE, owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, type TEXT NOT NULL, created_at INTEGER DEFAULT (strftime('%s','now')), expires_at INTEGER, views INTEGER DEFAULT 0, downloads INTEGER DEFAULT 0);
|
| 101 |
CREATE TABLE IF NOT EXISTS user_shares (id INTEGER PRIMARY KEY AUTOINCREMENT, file_id TEXT REFERENCES files(id) ON DELETE CASCADE, folder_id INTEGER REFERENCES folders(id) ON DELETE CASCADE, owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, shared_with INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, created_at INTEGER DEFAULT (strftime('%s','now')));
|
| 102 |
CREATE TABLE IF NOT EXISTS transfer_daily (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, day TEXT NOT NULL, up_bytes INTEGER DEFAULT 0, down_bytes INTEGER DEFAULT 0, UNIQUE(user_id, day));
|
| 103 |
+
CREATE TABLE IF NOT EXISTS activity (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, action TEXT NOT NULL, detail TEXT, created_at INTEGER DEFAULT (strftime('%s','now')));
|
| 104 |
CREATE INDEX IF NOT EXISTS idx_files_owner ON files(owner_id);
|
| 105 |
CREATE INDEX IF NOT EXISTS idx_chunks_file ON file_chunks(file_id);
|
| 106 |
CREATE INDEX IF NOT EXISTS idx_share_owner ON share_links(owner_id);
|
| 107 |
CREATE INDEX IF NOT EXISTS idx_ushares_with ON user_shares(shared_with);
|
| 108 |
CREATE INDEX IF NOT EXISTS idx_transfer_day ON transfer_daily(user_id, day);
|
| 109 |
+
CREATE INDEX IF NOT EXISTS idx_activity_user ON activity(user_id, created_at);
|
| 110 |
`);
|
| 111 |
|
| 112 |
function runMigrations() {
|
|
|
|
| 134 |
}
|
| 135 |
}
|
| 136 |
if (updatedAdded) db.exec(`UPDATE files SET updated_at = strftime('%s','now') WHERE updated_at = 0;`);
|
| 137 |
+
// ✅ Compteurs de vues/téléchargements sur share_links
|
| 138 |
+
const slCols = db.prepare("PRAGMA table_info(share_links)").all().map(c => c.name);
|
| 139 |
+
if (!slCols.includes('views')) db.exec(`ALTER TABLE share_links ADD COLUMN views INTEGER DEFAULT 0;`);
|
| 140 |
+
if (!slCols.includes('downloads')) db.exec(`ALTER TABLE share_links ADD COLUMN downloads INTEGER DEFAULT 0;`);
|
| 141 |
const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all().map(t => t.name);
|
| 142 |
if (!tables.includes('folders')) db.exec(`CREATE TABLE folders (id INTEGER PRIMARY KEY AUTOINCREMENT, parent_id INTEGER REFERENCES folders(id) ON DELETE CASCADE, owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, name TEXT NOT NULL, created_at INTEGER DEFAULT (strftime('%s','now')), UNIQUE(parent_id, owner_id, name));`);
|
| 143 |
+
if (!tables.includes('share_links')) db.exec(`CREATE TABLE share_links (token TEXT PRIMARY KEY, file_id TEXT NOT NULL REFERENCES files(id) ON DELETE CASCADE, owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, type TEXT NOT NULL, created_at INTEGER DEFAULT (strftime('%s','now')), expires_at INTEGER, views INTEGER DEFAULT 0, downloads INTEGER DEFAULT 0);`);
|
| 144 |
if (!tables.includes('user_shares')) db.exec(`CREATE TABLE user_shares (id INTEGER PRIMARY KEY AUTOINCREMENT, file_id TEXT REFERENCES files(id) ON DELETE CASCADE, folder_id INTEGER REFERENCES folders(id) ON DELETE CASCADE, owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, shared_with INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, created_at INTEGER DEFAULT (strftime('%s','now'))); CREATE INDEX idx_ushares_with ON user_shares(shared_with);`);
|
| 145 |
if (!tables.includes('transfer_daily')) db.exec(`CREATE TABLE transfer_daily (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, day TEXT NOT NULL, up_bytes INTEGER DEFAULT 0, down_bytes INTEGER DEFAULT 0, UNIQUE(user_id, day)); CREATE INDEX idx_transfer_day ON transfer_daily(user_id, day);`);
|
| 146 |
+
if (!tables.includes('activity')) db.exec(`CREATE TABLE activity (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, action TEXT NOT NULL, detail TEXT, created_at INTEGER DEFAULT (strftime('%s','now'))); CREATE INDEX idx_activity_user ON activity(user_id, created_at);`);
|
| 147 |
const sessionsCols = tables.includes('sessions') ? db.prepare("PRAGMA table_info(sessions)").all().map(c => c.name) : [];
|
| 148 |
if (tables.includes('sessions') && (!sessionsCols.includes('data') || !sessionsCols.includes('expires_at'))) {
|
| 149 |
log('WARN', 'Table sessions invalide → reconstruction');
|
|
|
|
| 178 |
}
|
| 179 |
function transferBlocked(userId) { return getTransfer(userId).total >= DAILY_TRANSFER; }
|
| 180 |
|
| 181 |
+
// ✅ JOURNAL D'ACTIVITÉ
|
| 182 |
+
function logActivity(userId, action, detail) {
|
| 183 |
+
try { db.prepare('INSERT INTO activity(user_id, action, detail) VALUES(?,?,?)').run(userId, action, String(detail || '').slice(0, 200)); } catch (e) {}
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
// --- NETTOYAGE + BACKUPS ---
|
| 187 |
function cleanTemp() {
|
| 188 |
try {
|
|
|
|
| 204 |
log('INFO', `Backup BDD: ${name}`);
|
| 205 |
} catch (e) { log('ERROR', `Backup échoué: ${e.message}`); }
|
| 206 |
}
|
| 207 |
+
function cleanHourly() {
|
| 208 |
try {
|
| 209 |
+
const now = Date.now();
|
| 210 |
+
const s = db.prepare('DELETE FROM sessions WHERE expires_at < ?').run(now);
|
| 211 |
+
const l = db.prepare('DELETE FROM share_links WHERE expires_at IS NOT NULL AND expires_at < ?').run(now);
|
| 212 |
+
const a = db.prepare('DELETE FROM activity WHERE created_at < ?').run(Math.floor(now / 1000) - 30 * 86400);
|
| 213 |
+
db.prepare('DELETE FROM activity WHERE id NOT IN (SELECT id FROM activity ORDER BY id DESC LIMIT 2000)').run();
|
| 214 |
+
const cutoff = Math.floor(now / 1000) - 7 * 86400;
|
| 215 |
const olds = db.prepare("SELECT id FROM files WHERE status='error' AND updated_at < ?").all(cutoff);
|
| 216 |
+
for (const f of olds) { db.prepare('DELETE FROM files WHERE id=?').run(f.id); try { unlinkSync(join(THUMB_DIR, `${f.id}.jpg`)); } catch (_) {} }
|
| 217 |
+
if (s.changes || l.changes || a.changes || olds.length) log('INFO', `Cleanup: ${s.changes} session(s), ${l.changes} lien(s), ${a.changes} activité(s), ${olds.length} fichier(s) erreur`);
|
| 218 |
+
} catch (e) { log('WARN', `Cleanup: ${e.message}`); }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
}
|
| 220 |
mkdirSync(TEMP_DIR, { recursive: true });
|
| 221 |
mkdirSync(THUMB_DIR, { recursive: true });
|
| 222 |
cleanTemp();
|
| 223 |
+
setInterval(cleanHourly, 3600000);
|
| 224 |
setInterval(backupDb, 6 * 3600000);
|
| 225 |
setTimeout(backupDb, 60000);
|
| 226 |
|
|
|
|
| 303 |
const fileCache = new ByteLRUCache();
|
| 304 |
setInterval(()=>{ const m = process.memoryUsage(); if(m.rss > 13*1024*1024*1024){ log('ALERT', `RAM ${(m.rss/1e9).toFixed(1)}GB → vidage du cache`); fileCache.clear(); if(global.gc) global.gc(); } }, 30000);
|
| 305 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 306 |
let nsfwModel = null;
|
| 307 |
async function loadNsfwModel(){ try{ await tf.setBackend('wasm'); tf.wasm.setWasmPaths('/app/tfjs_wasm/','tfjs-backend-wasm.wasm'); await tf.ready(); nsfwModel = await nsfwjs.load('/app/tfjs_wasm/',{type:'mobilenet_v2',size:224}); log('INFO', 'NSFW WASM chargé'); }catch(e){ log('WARN', `NSFW load fail: ${e.message}`); } }
|
| 308 |
loadNsfwModel();
|
|
|
|
| 388 |
if(cs > e) break;
|
| 389 |
}
|
| 390 |
res.end();
|
| 391 |
+
if (counterUserId) addTransfer(counterUserId, sentBytes, 'down');
|
| 392 |
}
|
| 393 |
|
| 394 |
const sseClients = new Map();
|
| 395 |
function broadcast(fid,d){ const cs = sseClients.get(fid); if(cs){ const p = `data: ${JSON.stringify(d)}\n\n`; for(const r of cs) r.write(p); } }
|
| 396 |
|
|
|
|
| 397 |
let EMBED_TPL = null;
|
| 398 |
function embedTpl() {
|
| 399 |
if (EMBED_TPL === null) {
|
|
|
|
| 428 |
catch(e) { log('ERROR', `Session regenerate échouée: ${e.message}`); return res.status(500).json({error:'Erreur session'}); }
|
| 429 |
req.session.userId = usr.id; req.session.isAdmin = !!usr.is_admin; req.session.tosAccepted = !!usr.tos_accepted; req.session.username = usr.username;
|
| 430 |
log('INFO', `Connexion: ${u}`);
|
| 431 |
+
logActivity(usr.id, 'login', 'Connexion');
|
| 432 |
res.json({ok:true,user:{id:usr.id,username:usr.username,isAdmin:!!usr.is_admin,tosAccepted:!!usr.tos_accepted}});
|
| 433 |
});
|
| 434 |
app.post('/api/logout',(req,res)=>req.session.destroy(()=>res.json({ok:true})));
|
|
|
|
| 442 |
});
|
| 443 |
app.post('/api/tos/accept',requireAuth,(req,res)=>{db.prepare('UPDATE users SET tos_accepted=1 WHERE id=?').run(req.session.userId);req.session.tosAccepted=true;res.json({ok:true});});
|
| 444 |
|
| 445 |
+
// ✅ CHANGER SON MOT DE PASSE
|
| 446 |
+
app.post('/api/password', requireAuth, async(req,res)=>{
|
| 447 |
+
const { current, next } = req.body;
|
| 448 |
+
if (typeof current !== 'string' || typeof next !== 'string') return res.status(400).json({error:'Champs manquants'});
|
| 449 |
+
if (next.length < 6) return res.status(400).json({error:'Nouveau mot de passe trop court (6 min)'});
|
| 450 |
+
const usr = db.prepare('SELECT * FROM users WHERE id=?').get(req.session.userId);
|
| 451 |
+
const hCur = await deriveKey(current, usr.salt);
|
| 452 |
+
if (!hCur.equals(usr.password_hash)) return res.status(403).json({error:'Mot de passe actuel invalide'});
|
| 453 |
+
const salt = randomBytes(16);
|
| 454 |
+
const hNew = await deriveKey(next, salt);
|
| 455 |
+
db.prepare('UPDATE users SET password_hash=?, salt=? WHERE id=?').run(hNew, salt, usr.id);
|
| 456 |
+
log('INFO', `Mot de passe changé: ${usr.username}`);
|
| 457 |
+
logActivity(usr.id, 'password', 'Mot de passe modifié');
|
| 458 |
+
res.json({ok:true});
|
| 459 |
+
});
|
| 460 |
+
|
| 461 |
+
// ✅ SUPPRIMER SON COMPTE (self-service)
|
| 462 |
+
app.delete('/api/account', requireAuth, async(req,res)=>{
|
| 463 |
+
const { password } = req.body;
|
| 464 |
+
const usr = db.prepare('SELECT * FROM users WHERE id=?').get(req.session.userId);
|
| 465 |
+
const h = await deriveKey(String(password || ''), usr.salt);
|
| 466 |
+
if (!h.equals(usr.password_hash)) return res.status(403).json({error:'Mot de passe invalide'});
|
| 467 |
+
const urls = db.prepare('SELECT fc.imgbb_delete_url FROM file_chunks fc JOIN files f ON f.id=fc.file_id WHERE f.owner_id=? AND fc.imgbb_delete_url IS NOT NULL').all(usr.id).map(r => r.imgbb_delete_url);
|
| 468 |
+
logActivity(usr.id, 'account_delete', 'Compte supprimé');
|
| 469 |
+
db.prepare('DELETE FROM users WHERE id=?').run(usr.id);
|
| 470 |
+
log('ALERT', `Compte #${usr.id} (${usr.username}) auto-supprimé (${urls.length} chunks en nettoyage)`);
|
| 471 |
+
(async () => { for (const u of urls) await imgbbDelete(u); })();
|
| 472 |
+
req.session.destroy(() => res.json({ok:true}));
|
| 473 |
+
});
|
| 474 |
+
|
| 475 |
+
// ✅ STATS PERSO (donut par type)
|
| 476 |
+
app.get('/api/stats', requireAuth, (req,res) => {
|
| 477 |
+
res.json(db.prepare(`SELECT CASE WHEN mime LIKE 'image/%' THEN 'image' WHEN mime LIKE 'video/%' THEN 'video' WHEN mime LIKE 'audio/%' THEN 'audio' ELSE 'autre' END as cat, COUNT(*) c, COALESCE(SUM(size),0) s
|
| 478 |
+
FROM files WHERE owner_id=? AND status!='error' GROUP BY cat`).all(req.session.userId));
|
| 479 |
+
});
|
| 480 |
+
|
| 481 |
+
// ✅ ACTIVITÉ PERSO
|
| 482 |
+
app.get('/api/activity', requireAuth, (req,res) => {
|
| 483 |
+
res.json(db.prepare('SELECT action, detail, created_at FROM activity WHERE user_id=? ORDER BY created_at DESC LIMIT 100').all(req.session.userId));
|
| 484 |
+
});
|
| 485 |
+
|
| 486 |
+
// ✅ ADMIN
|
| 487 |
app.get('/api/admin/stats', requireAuth, requireAdmin, (req,res) => {
|
| 488 |
const users = db.prepare('SELECT COUNT(*) c FROM users').get().c;
|
| 489 |
const files = db.prepare('SELECT COUNT(*) c, COALESCE(SUM(size),0) s FROM files').get();
|
|
|
|
| 501 |
transferToday: getTransfer(u.id).total,
|
| 502 |
})));
|
| 503 |
});
|
| 504 |
+
app.get('/api/admin/activity', requireAuth, requireAdmin, (req,res) => {
|
| 505 |
+
res.json(db.prepare(`SELECT a.action, a.detail, a.created_at, COALESCE(u.username,'public') as username FROM activity a LEFT JOIN users u ON u.id=a.user_id ORDER BY a.created_at DESC LIMIT 100`).all());
|
| 506 |
+
});
|
| 507 |
app.delete('/api/admin/users/:id', requireAuth, requireAdmin, (req,res) => {
|
| 508 |
const id = parseInt(req.params.id, 10);
|
| 509 |
if (!id) return res.status(400).json({error:'ID invalide'});
|
| 510 |
if (id === req.session.userId) return res.status(400).json({error:'Impossible de supprimer votre propre compte'});
|
| 511 |
+
const urls = db.prepare('SELECT fc.imgbb_delete_url FROM file_chunks fc JOIN files f ON f.id=fc.file_id WHERE f.owner_id=? AND fc.imgbb_delete_url IS NOT NULL').all(id).map(r => r.imgbb_delete_url);
|
| 512 |
db.prepare('DELETE FROM users WHERE id=?').run(id);
|
| 513 |
+
log('ALERT', `Admin ${req.session.username} a supprimé le compte #${id}`);
|
| 514 |
(async () => { for (const u of urls) await imgbbDelete(u); })();
|
| 515 |
res.json({ok:true});
|
| 516 |
});
|
|
|
|
| 558 |
if(!name || typeof name !== 'string' || !name.trim() || name.length > 100) return res.status(400).json({error:'Nom invalide'});
|
| 559 |
const fo = db.prepare('SELECT id FROM folders WHERE id=? AND owner_id=?').get(req.params.id, req.session.userId);
|
| 560 |
if(!fo) return res.status(404).json({error:'Introuvable'});
|
| 561 |
+
try { db.prepare('UPDATE folders SET name=? WHERE id=?').run(name.trim(), req.params.id); logActivity(req.session.userId,'rename',name.trim()); res.json({ok:true}); }
|
| 562 |
catch(e){ res.status(409).json({error:'Un dossier porte déjà ce nom'}); }
|
| 563 |
});
|
| 564 |
app.post('/api/folders/:id/move',requireAuth,(req,res)=>{
|
|
|
|
| 576 |
}
|
| 577 |
}
|
| 578 |
db.prepare('UPDATE folders SET parent_id=? WHERE id=?').run(parent_id || null, req.params.id);
|
| 579 |
+
logActivity(req.session.userId,'move',fo.name);
|
| 580 |
res.json({ok:true});
|
| 581 |
});
|
| 582 |
|
|
|
|
| 596 |
const f = db.prepare('SELECT id FROM files WHERE id=? AND owner_id=?').get(req.params.id, req.session.userId);
|
| 597 |
if(!f) return res.status(404).json({error:'Introuvable'});
|
| 598 |
db.prepare('UPDATE files SET name=? WHERE id=?').run(name.trim(), req.params.id);
|
| 599 |
+
logActivity(req.session.userId,'rename',name.trim());
|
| 600 |
res.json({ok:true});
|
| 601 |
});
|
| 602 |
app.post('/api/files/:id/move',requireAuth,(req,res)=>{
|
|
|
|
| 609 |
if (!target || target.owner_id !== req.session.userId) return res.status(403).json({error:'Dossier cible invalide'});
|
| 610 |
}
|
| 611 |
db.prepare('UPDATE files SET folder_id=? WHERE id=?').run(folder_id || null, req.params.id);
|
| 612 |
+
logActivity(req.session.userId,'move',f.name);
|
| 613 |
res.json({ok:true});
|
| 614 |
});
|
| 615 |
|
|
|
|
| 625 |
if (db.prepare(`SELECT 1 FROM user_shares WHERE ${col}=? AND shared_with=?`).get(id, target.id)) return res.status(409).json({error:'Déjà partagé'});
|
| 626 |
db.prepare(`INSERT INTO user_shares(${col},owner_id,shared_with) VALUES(?,?,?)`).run(id, req.session.userId, target.id);
|
| 627 |
log('INFO', `Partage ${type} ${id} → ${username.trim()}`);
|
| 628 |
+
logActivity(req.session.userId,'share_user',`${type} → ${username.trim()}`);
|
| 629 |
res.json({ok:true});
|
| 630 |
});
|
| 631 |
|
|
|
|
| 713 |
db.prepare("UPDATE files SET status='ready',progress=100 WHERE id=?").run(fid);
|
| 714 |
broadcast(fid,{type:'progress',progress:100,status:'ready',type:'done'});
|
| 715 |
addTransfer(uid, fsize, 'up');
|
| 716 |
+
logActivity(uid, 'upload', path.split('/').pop());
|
| 717 |
const secs = (Date.now()-t0)/1000;
|
| 718 |
log('INFO', `Upload terminé: ${fid} en ${secs.toFixed(1)}s (${(fsize/1048576/secs).toFixed(2)} MB/s)`);
|
| 719 |
}catch(e){
|
|
|
|
| 733 |
const f = canAccessFile(req.session.userId, req.params.id);
|
| 734 |
if(!f)return res.status(404).json({error:'Introuvable'});
|
| 735 |
if(f.status!=='ready')return res.status(409).json({error:'Pas prêt',status:f.status});
|
| 736 |
+
logActivity(req.session.userId,'download',f.name);
|
| 737 |
const k = await getMasterKey(f.id);
|
| 738 |
await streamFile(res,f,k,req.headers.range,req.session.userId);
|
| 739 |
});
|
| 740 |
|
| 741 |
+
// ✅ PARTAGE AVEC TTL AU CHOIX (1h / 24h / 7j / 30j)
|
| 742 |
app.post('/api/files/:id/share',requireAuth,shareLimit,async(req,res)=>{
|
| 743 |
const f=db.prepare('SELECT * FROM files WHERE id=? AND owner_id=?').get(req.params.id,req.session.userId);
|
| 744 |
if(!f||f.status!=='ready') return res.status(404).json({error:'Fichier non disponible'});
|
| 745 |
+
const ttlReq = parseInt(req.body.ttl, 10);
|
| 746 |
+
const ttl = TTL_ALLOWED.includes(ttlReq) ? ttlReq : 168;
|
| 747 |
+
const pt=uuidv4(), dt2=uuidv4(), expires=Date.now()+ttl*3600000;
|
| 748 |
db.prepare('INSERT INTO share_links(token,file_id,owner_id,type,expires_at) VALUES(?,?,?,?,?)').run(pt,f.id,req.session.userId,'embed',expires);
|
| 749 |
db.prepare('INSERT INTO share_links(token,file_id,owner_id,type,expires_at) VALUES(?,?,?,?,?)').run(dt2,f.id,req.session.userId,'download',expires);
|
| 750 |
+
logActivity(req.session.userId,'share_link',`${f.name} (${ttl}h)`);
|
| 751 |
+
res.json({preview:`/s/${pt}`,download:`/d/${dt2}`,expires,ttl});
|
| 752 |
});
|
| 753 |
|
| 754 |
+
// ✅ /s/ : embed + compteur de vues + activité
|
| 755 |
app.get('/s/:token',async(req,res)=>{
|
| 756 |
const tpl = embedTpl();
|
| 757 |
const serve = (status, data, og) => {
|
| 758 |
if (!tpl) return res.status(status).send('Lien invalide');
|
| 759 |
+
const out = tpl.replace('__OG_META__', og || '').replace('__EMBED_DATA__', JSON.stringify(data).replace(/</g, '\\u003c'));
|
|
|
|
|
|
|
| 760 |
res.status(status).send(out);
|
| 761 |
};
|
| 762 |
const l = db.prepare('SELECT * FROM share_links WHERE token=? AND type=? AND (expires_at IS NULL OR expires_at>?)').get(req.params.token,'embed',Date.now());
|
| 763 |
if (!l) return serve(404, { error: 'Lien invalide ou expiré' });
|
| 764 |
const f = db.prepare('SELECT * FROM files WHERE id=?').get(l.file_id);
|
| 765 |
if (!f) return serve(404, { error: 'Fichier supprimé' });
|
| 766 |
+
db.prepare('UPDATE share_links SET views = views + 1 WHERE token=?').run(req.params.token);
|
| 767 |
+
logActivity(f.owner_id, 'public_view', f.name);
|
| 768 |
let dt;
|
| 769 |
const existing = db.prepare('SELECT token FROM share_links WHERE file_id=? AND type=? AND owner_id=? AND (expires_at IS NULL OR expires_at>?)').get(f.id,'download',l.owner_id,Date.now());
|
| 770 |
if (existing) dt = existing.token;
|
|
|
|
| 774 |
serve(200, { name: f.name, size: f.size, mime: f.mime, dl: '/d/' + dt }, og);
|
| 775 |
});
|
| 776 |
|
| 777 |
+
// ✅ /d/ : compteur de téléchargements + activité
|
| 778 |
app.get('/d/:token',async(req,res)=>{
|
| 779 |
const l=db.prepare('SELECT * FROM share_links WHERE token=? AND type=? AND (expires_at IS NULL OR expires_at>?)').get(req.params.token,'download',Date.now());
|
| 780 |
if(!l)return res.status(404).json({error:'Invalide'});
|
| 781 |
const f=db.prepare('SELECT * FROM files WHERE id=?').get(l.file_id);
|
| 782 |
if(!f||f.status!=='ready')return res.status(404).json({error:'Indisponible'});
|
| 783 |
if (transferBlocked(f.owner_id)) { log('ALERT', `Quota transit propriétaire atteint: ${f.id}`); return res.status(429).json({error:'Quota journalier du propriétaire atteint'}); }
|
| 784 |
+
db.prepare('UPDATE share_links SET downloads = downloads + 1 WHERE token=?').run(req.params.token);
|
| 785 |
+
logActivity(f.owner_id, 'public_download', f.name);
|
| 786 |
log('INFO', `Téléchargement public /d/${req.params.token} (${f.name})`);
|
| 787 |
const mk = decryptMasterKey(db.prepare('SELECT master_key_enc FROM files WHERE id=?').get(f.id).master_key_enc);
|
| 788 |
await streamFile(res,f,mk,req.headers.range,f.owner_id);
|
|
|
|
| 797 |
db.prepare('DELETE FROM files WHERE id=?').run(f.id);
|
| 798 |
fileCache.delete(`chunk:${f.id}:0`);
|
| 799 |
try{unlinkSync(join(THUMB_DIR,`${f.id}.jpg`));}catch(_){}
|
| 800 |
+
logActivity(req.session.userId,'delete',f.name);
|
| 801 |
res.json({ok:true});
|
| 802 |
});
|
| 803 |
|
|
|
|
| 838 |
res.status(500).json({ error: 'Internal Server Error' });
|
| 839 |
});
|
| 840 |
|
| 841 |
+
const server = app.listen(PORT, '0.0.0.0', () => log('INFO', `PixelDrive v4.8 démarré | stockage ${(USER_QUOTA/1073741824).toFixed(0)} GB | transit ${(DAILY_TRANSFER/1073741824).toFixed(0)} GB/j`));
|
| 842 |
process.on('SIGTERM', () => { log('WARN', 'SIGTERM reçu, arrêt...'); server.close(() => process.exit(0)); });
|