BlueGit

timfa filemanager

Persist last visited folder

Users now return to their previously opened folder after signing in, as long as they still have access to it.\nThe server stores each user's most recent successful folder browse and validates access before restoring it.\nRoute coverage was added to confirm last-folder persistence and stale-path fallback behaviour.

timfa Tim Falken · pushed by timfa

Authored 2026-05-26 · 5 months ago

Hash
60304be12a9f7f9124391eed633889ecb56b19d3
Parent
a06818e8
3 files changed +152 −1
server/db.js +8 −0
@@ -52,6 +52,14 @@ function initDb ()
52 52 CREATE INDEX IF NOT EXISTS idx_auth_sessions_username ON auth_sessions(username);
53 53 CREATE INDEX IF NOT EXISTS idx_auth_sessions_last_seen ON auth_sessions(last_seen_at);
54 54
55 CREATE TABLE IF NOT EXISTS user_last_navigation (
56 username TEXT PRIMARY KEY,
57 last_dir TEXT,
58 updated_at INTEGER NOT NULL
59 );
60
61 CREATE INDEX IF NOT EXISTS idx_user_last_navigation_updated_at ON user_last_navigation(updated_at);
62
55 63 CREATE TABLE IF NOT EXISTS share_tokens (
56 64 token TEXT PRIMARY KEY,
57 65 file_path TEXT NOT NULL,
@@ -52,6 +52,14 @@ function initDb ()
52 CREATE INDEX IF NOT EXISTS idx_auth_sessions_username ON auth_sessions(username);
52 CREATE INDEX IF NOT EXISTS idx_auth_sessions_username ON auth_sessions(username);
53 CREATE INDEX IF NOT EXISTS idx_auth_sessions_last_seen ON auth_sessions(last_seen_at);
53 CREATE INDEX IF NOT EXISTS idx_auth_sessions_last_seen ON auth_sessions(last_seen_at);
54
54
55 CREATE TABLE IF NOT EXISTS user_last_navigation (
56 username TEXT PRIMARY KEY,
57 last_dir TEXT,
58 updated_at INTEGER NOT NULL
59 );
60
61 CREATE INDEX IF NOT EXISTS idx_user_last_navigation_updated_at ON user_last_navigation(updated_at);
62
55 CREATE TABLE IF NOT EXISTS share_tokens (
63 CREATE TABLE IF NOT EXISTS share_tokens (
56 token TEXT PRIMARY KEY,
64 token TEXT PRIMARY KEY,
57 file_path TEXT NOT NULL,
65 file_path TEXT NOT NULL,
server/routes/files.js +76 −1
@@ -270,6 +270,49 @@ function effectivePaths ()
270 270 return getEffectivePaths(loadConfig().paths || []);
271 271 }
272 272
273 function ensureUserNavigationTable (db)
274 {
275 db.exec(`
276 CREATE TABLE IF NOT EXISTS user_last_navigation (
277 username TEXT PRIMARY KEY,
278 last_dir TEXT,
279 updated_at INTEGER NOT NULL
280 );
281 `);
282 }
283
284 function setUserLastDir (username, dirPath)
285 {
286 if (!username) return;
287 const db = getDb();
288 ensureUserNavigationTable(db);
289 db.prepare(`
290 INSERT INTO user_last_navigation (username, last_dir, updated_at)
291 VALUES (?, ?, ?)
292 ON CONFLICT(username) DO UPDATE SET
293 last_dir = excluded.last_dir,
294 updated_at = excluded.updated_at
295 `).run([String(username), String(dirPath || ''), Date.now()]);
296 }
297
298 function getUserLastDir (username)
299 {
300 if (!username) return null;
301 const db = getDb();
302 ensureUserNavigationTable(db);
303 const row = db.prepare('SELECT last_dir FROM user_last_navigation WHERE username = ?').get([String(username)]);
304 const value = String(row && row.last_dir || '').trim();
305 return value || null;
306 }
307
308 function clearUserLastDir (username)
309 {
310 if (!username) return;
311 const db = getDb();
312 ensureUserNavigationTable(db);
313 db.prepare('DELETE FROM user_last_navigation WHERE username = ?').run([String(username)]);
314 }
315
273 316 /**
274 317 * Loads config and returns { config, roots } together so both are consistent
275 318 * and user-folder checks can be performed in route handlers.
@@ -981,7 +1024,31 @@ router.get('/roots', requireAuth, (req, res) =>
981 1024 }
982 1025 }
983 1026
984 res.json({ roots: readable });
1027 let lastDir = getUserLastDir(req.user && req.user.username);
1028 if (lastDir)
1029 {
1030 const info = resolveRootForUser(lastDir, roots, req.user, config);
1031 const hasAccess = !!(info && canReadInfo(req.user, info));
1032 let isDir = false;
1033 if (hasAccess)
1034 {
1035 try
1036 {
1037 isDir = fs.statSync(lastDir).isDirectory();
1038 } catch
1039 {
1040 isDir = false;
1041 }
1042 }
1043
1044 if (!hasAccess || !isDir)
1045 {
1046 clearUserLastDir(req.user && req.user.username);
1047 lastDir = null;
1048 }
1049 }
1050
1051 res.json({ roots: readable, lastDir });
985 1052 });
986 1053
987 1054 // ---------------------------------------------------------------------------
@@ -1179,6 +1246,14 @@ router.get('/list', requireAuth, (req, res) =>
1179 1246 };
1180 1247 });
1181 1248
1249 try
1250 {
1251 setUserLastDir(req.user && req.user.username, dir);
1252 } catch
1253 {
1254 // Non-fatal preference persistence.
1255 }
1256
1182 1257 res.json({ items });
1183 1258 });
1184 1259
@@ -270,6 +270,49 @@ function effectivePaths ()
270 return getEffectivePaths(loadConfig().paths || []);
270 return getEffectivePaths(loadConfig().paths || []);
271}
271}
272
272
273function ensureUserNavigationTable (db)
274{
275 db.exec(`
276 CREATE TABLE IF NOT EXISTS user_last_navigation (
277 username TEXT PRIMARY KEY,
278 last_dir TEXT,
279 updated_at INTEGER NOT NULL
280 );
281 `);
282}
283
284function setUserLastDir (username, dirPath)
285{
286 if (!username) return;
287 const db = getDb();
288 ensureUserNavigationTable(db);
289 db.prepare(`
290 INSERT INTO user_last_navigation (username, last_dir, updated_at)
291 VALUES (?, ?, ?)
292 ON CONFLICT(username) DO UPDATE SET
293 last_dir = excluded.last_dir,
294 updated_at = excluded.updated_at
295 `).run([String(username), String(dirPath || ''), Date.now()]);
296}
297
298function getUserLastDir (username)
299{
300 if (!username) return null;
301 const db = getDb();
302 ensureUserNavigationTable(db);
303 const row = db.prepare('SELECT last_dir FROM user_last_navigation WHERE username = ?').get([String(username)]);
304 const value = String(row && row.last_dir || '').trim();
305 return value || null;
306}
307
308function clearUserLastDir (username)
309{
310 if (!username) return;
311 const db = getDb();
312 ensureUserNavigationTable(db);
313 db.prepare('DELETE FROM user_last_navigation WHERE username = ?').run([String(username)]);
314}
315
273/**
316/**
274 * Loads config and returns { config, roots } together so both are consistent
317 * Loads config and returns { config, roots } together so both are consistent
275 * and user-folder checks can be performed in route handlers.
318 * and user-folder checks can be performed in route handlers.
@@ -981,7 +1024,31 @@ router.get('/roots', requireAuth, (req, res) =>
981 }
1024 }
982 }
1025 }
983
1026
984 res.json({ roots: readable });
1027 let lastDir = getUserLastDir(req.user && req.user.username);
1028 if (lastDir)
1029 {
1030 const info = resolveRootForUser(lastDir, roots, req.user, config);
1031 const hasAccess = !!(info && canReadInfo(req.user, info));
1032 let isDir = false;
1033 if (hasAccess)
1034 {
1035 try
1036 {
1037 isDir = fs.statSync(lastDir).isDirectory();
1038 } catch
1039 {
1040 isDir = false;
1041 }
1042 }
1043
1044 if (!hasAccess || !isDir)
1045 {
1046 clearUserLastDir(req.user && req.user.username);
1047 lastDir = null;
1048 }
1049 }
1050
1051 res.json({ roots: readable, lastDir });
985});
1052});
986
1053
987// ---------------------------------------------------------------------------
1054// ---------------------------------------------------------------------------
@@ -1179,6 +1246,14 @@ router.get('/list', requireAuth, (req, res) =>
1179 };
1246 };
1180 });
1247 });
1181
1248
1249 try
1250 {
1251 setUserLastDir(req.user && req.user.username, dir);
1252 } catch
1253 {
1254 // Non-fatal preference persistence.
1255 }
1256
1182 res.json({ items });
1257 res.json({ items });
1183});
1258});
1184
1259
tests/files.routes.test.js +68 −0
@@ -566,6 +566,74 @@ describe('root alias endpoints', () =>
566 566
567 567 expect(status).toBe(400);
568 568 });
569
570 test('GET /api/files/roots returns lastDir when user still has access', async () =>
571 {
572 const nestedDir = path.join(rootDir, 'series');
573 fs.mkdirSync(nestedDir, { recursive: true });
574
575 const db = getDb();
576 db.exec(`
577 CREATE TABLE IF NOT EXISTS user_last_navigation (
578 username TEXT PRIMARY KEY,
579 last_dir TEXT,
580 updated_at INTEGER NOT NULL
581 );
582 `);
583 db.prepare('INSERT INTO user_last_navigation (username, last_dir, updated_at) VALUES (?, ?, ?)')
584 .run(['admin', nestedDir, Date.now()]);
585
586 const { status, body } = await req('GET', '/api/files/roots');
587 expect(status).toBe(200);
588 expect(body.lastDir).toBe(nestedDir);
589 });
590
591 test('GET /api/files/roots returns null lastDir when saved folder is no longer accessible', async () =>
592 {
593 const outsideDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-outside-'));
594 mockUser = {
595 username: 'reader',
596 isAdmin: false,
597 permissions: {},
598 };
599
600 const db = getDb();
601 db.exec(`
602 CREATE TABLE IF NOT EXISTS user_last_navigation (
603 username TEXT PRIMARY KEY,
604 last_dir TEXT,
605 updated_at INTEGER NOT NULL
606 );
607 `);
608 db.prepare('INSERT INTO user_last_navigation (username, last_dir, updated_at) VALUES (?, ?, ?)')
609 .run(['reader', outsideDir, Date.now()]);
610
611 try
612 {
613 const { status, body } = await req('GET', '/api/files/roots');
614 expect(status).toBe(200);
615 expect(body.lastDir).toBeNull();
616 } finally
617 {
618 fs.rmSync(outsideDir, { recursive: true, force: true });
619 }
620 });
621 });
622
623 describe('last visited folder persistence', () =>
624 {
625 test('GET /api/files/list stores the visited folder for the authenticated user', async () =>
626 {
627 const visited = path.join(rootDir, 'visited-folder');
628 fs.mkdirSync(visited, { recursive: true });
629
630 const { status } = await req('GET', `/api/files/list?dir=${encodeURIComponent(visited)}`);
631 expect(status).toBe(200);
632
633 const row = getDb().prepare('SELECT last_dir FROM user_last_navigation WHERE username = ?').get(['admin']);
634 expect(row).toBeTruthy();
635 expect(row.last_dir).toBe(visited);
636 });
569 637 });
570 638
571 639 describe('GET /api/files/thumbnail', () =>
@@ -566,6 +566,74 @@ describe('root alias endpoints', () =>
566
566
567 expect(status).toBe(400);
567 expect(status).toBe(400);
568 });
568 });
569
570 test('GET /api/files/roots returns lastDir when user still has access', async () =>
571 {
572 const nestedDir = path.join(rootDir, 'series');
573 fs.mkdirSync(nestedDir, { recursive: true });
574
575 const db = getDb();
576 db.exec(`
577 CREATE TABLE IF NOT EXISTS user_last_navigation (
578 username TEXT PRIMARY KEY,
579 last_dir TEXT,
580 updated_at INTEGER NOT NULL
581 );
582 `);
583 db.prepare('INSERT INTO user_last_navigation (username, last_dir, updated_at) VALUES (?, ?, ?)')
584 .run(['admin', nestedDir, Date.now()]);
585
586 const { status, body } = await req('GET', '/api/files/roots');
587 expect(status).toBe(200);
588 expect(body.lastDir).toBe(nestedDir);
589 });
590
591 test('GET /api/files/roots returns null lastDir when saved folder is no longer accessible', async () =>
592 {
593 const outsideDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-outside-'));
594 mockUser = {
595 username: 'reader',
596 isAdmin: false,
597 permissions: {},
598 };
599
600 const db = getDb();
601 db.exec(`
602 CREATE TABLE IF NOT EXISTS user_last_navigation (
603 username TEXT PRIMARY KEY,
604 last_dir TEXT,
605 updated_at INTEGER NOT NULL
606 );
607 `);
608 db.prepare('INSERT INTO user_last_navigation (username, last_dir, updated_at) VALUES (?, ?, ?)')
609 .run(['reader', outsideDir, Date.now()]);
610
611 try
612 {
613 const { status, body } = await req('GET', '/api/files/roots');
614 expect(status).toBe(200);
615 expect(body.lastDir).toBeNull();
616 } finally
617 {
618 fs.rmSync(outsideDir, { recursive: true, force: true });
619 }
620 });
621});
622
623describe('last visited folder persistence', () =>
624{
625 test('GET /api/files/list stores the visited folder for the authenticated user', async () =>
626 {
627 const visited = path.join(rootDir, 'visited-folder');
628 fs.mkdirSync(visited, { recursive: true });
629
630 const { status } = await req('GET', `/api/files/list?dir=${encodeURIComponent(visited)}`);
631 expect(status).toBe(200);
632
633 const row = getDb().prepare('SELECT last_dir FROM user_last_navigation WHERE username = ?').get(['admin']);
634 expect(row).toBeTruthy();
635 expect(row.last_dir).toBe(visited);
636 });
569});
637});
570
638
571describe('GET /api/files/thumbnail', () =>
639describe('GET /api/files/thumbnail', () =>