diff --git a/main.py b/main.py
index 4541a76..88cb311 100644
--- a/main.py
+++ b/main.py
@@ -882,17 +882,23 @@ async def admin_file_users_endpoint(request: Request):
@app.get("/api/admin/files")
async def admin_list_files_endpoint(request: Request):
- """All files uploaded by a specific user (across every tab)."""
+ """All files uploaded by a specific user (across every tab).
+
+ Спец-значение `username=__all__` — файлы всех юзеров. Каждая
+ запись содержит поле `username` (для одиночного режима тоже —
+ UI единообразно).
+ """
_require_admin(request)
target_user = request.query_params.get("username", "").strip()
if not target_user:
raise HTTPException(400, "username query param required")
- safe_user = Path(target_user).name
- if safe_user != target_user or not safe_user:
- raise HTTPException(400, "Invalid username")
- user_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data")) / safe_user
+
+ data_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data"))
files = []
- if user_dir.exists() and user_dir.is_dir():
+
+ def _collect(user_dir: Path, username: str):
+ if not user_dir.exists() or not user_dir.is_dir():
+ return
for tab_dir in sorted(user_dir.iterdir()):
if not tab_dir.is_dir() or tab_dir.name.startswith("."):
continue
@@ -900,11 +906,25 @@ async def admin_list_files_endpoint(request: Request):
if f.is_file() and not f.name.startswith("."):
st = f.stat()
files.append({
+ "username": username,
"tab_id": tab_dir.name,
"filename": f.name,
"size": st.st_size,
"mtime": st.st_mtime,
})
+
+ if target_user == "__all__":
+ if data_dir.exists():
+ for d in sorted(data_dir.iterdir()):
+ if not d.is_dir() or d.name.startswith(".") or d.name.startswith("_"):
+ continue
+ _collect(d, d.name)
+ return {"username": "__all__", "count": len(files), "files": files}
+
+ safe_user = Path(target_user).name
+ if safe_user != target_user or not safe_user:
+ raise HTTPException(400, "Invalid username")
+ _collect(data_dir / safe_user, safe_user)
return {"username": safe_user, "count": len(files), "files": files}
@@ -937,7 +957,7 @@ async def admin_download_file_endpoint(request: Request):
return FileResponse(fpath, filename=safe_name)
-ADMIN_HTML_VERSION = "20260506f"
+ADMIN_HTML_VERSION = "20260506g"
@app.get("/admin", response_class=HTMLResponse)
diff --git a/static/admin.html b/static/admin.html
index dd78593..a557336 100644
--- a/static/admin.html
+++ b/static/admin.html
@@ -41,14 +41,14 @@ a { color: var(--accent); text-decoration: none; }
@@ -114,9 +114,7 @@ a { color: var(--accent); text-decoration: none; }
-
- | Tab ID | Файл | Размер | Загружен | Действие |
-
+
@@ -155,6 +153,14 @@ function showPage(name) {
document.querySelectorAll('.sidebar a').forEach(a => a.classList.remove('active'));
document.getElementById('page-' + name).classList.add('active');
document.querySelector('.sidebar a[href="#' + name + '"]').classList.add('active');
+ // Обновляем hash без default-скролла браузера и без записи в history
+ // (default делает window.scrollTo + history.pushState —
+ // это и есть «дёрганье». Возвращаем false из onclick, default отменяется,
+ // мы сами тихо ставим hash через replaceState).
+ if (location.hash !== '#' + name) {
+ history.replaceState(null, '', '#' + name);
+ }
+ return false;
}
// Handle hash on load
if (location.hash) showPage(location.hash.slice(1));
@@ -218,28 +224,21 @@ async function loadFileUsers() {
const r = await fetch('/api/admin/file_users', {headers: H});
if (!r.ok) return;
const d = await r.json();
- sel.innerHTML = '';
+ const total = d.users.reduce((acc, u) => acc + u.file_count, 0);
+ sel.innerHTML = '';
for (const u of d.users) {
const opt = document.createElement('option');
opt.value = u.username;
opt.textContent = u.username + ' (' + u.file_count + ')';
sel.appendChild(opt);
}
- // 1) Сначала пробуем восстановить ранее выбранного юзера из localStorage
+ // По умолчанию — «Все»; localStorage только если ранее юзер
+ // явно выбирал не-«все»
const saved = localStorage.getItem('admin_files_user');
- if (saved && Array.from(sel.options).some(o => o.value === saved)) {
- sel.value = saved;
- loadFiles();
- return;
- }
- // 2) Иначе — автовыбор первого юзера с file_count > 0,
- // чтобы при первом заходе админ сразу видел список файлов
- const firstWithFiles = d.users.find(u => u.file_count > 0);
- if (firstWithFiles) {
- sel.value = firstWithFiles.username;
- localStorage.setItem('admin_files_user', firstWithFiles.username);
- loadFiles();
- }
+ sel.value = (saved && Array.from(sel.options).some(o => o.value === saved))
+ ? saved
+ : '__all__';
+ loadFiles();
}
function onFilesUserChange() {
const v = document.getElementById('files-user').value;
@@ -252,7 +251,11 @@ async function loadFiles() {
const u = document.getElementById('files-user').value;
const tbl = document.getElementById('files');
const cnt = document.getElementById('files-count');
- tbl.innerHTML = '| Tab ID | Файл | Размер | Загружен | Действие |
';
+ const isAll = (u === '__all__');
+ // header
+ tbl.innerHTML = isAll
+ ? '| Пользователь | Tab ID | Файл | Размер | Загружен | Действие |
'
+ : '| Tab ID | Файл | Размер | Загружен | Действие |
';
cnt.textContent = '';
if (!u) return;
cnt.textContent = 'Загрузка…';
@@ -260,13 +263,18 @@ async function loadFiles() {
if (!r.ok) { cnt.textContent = 'Ошибка: ' + r.status; return; }
const d = await r.json();
cnt.textContent = 'Файлов: ' + d.count;
- for (const f of d.files) {
+ // Сортировка: новые сверху
+ const rows = d.files.slice().sort((a, b) => b.mtime - a.mtime);
+ for (const f of rows) {
const ts = new Date(f.mtime * 1000).toLocaleString('ru-RU', {day:'2-digit', month:'2-digit', year:'2-digit', hour:'2-digit', minute:'2-digit'});
const tr = document.createElement('tr');
- const dlUrl = '/api/admin/file_download?username=' + encodeURIComponent(u)
+ const owner = f.username || u;
+ const dlUrl = '/api/admin/file_download?username=' + encodeURIComponent(owner)
+ '&tab_id=' + encodeURIComponent(f.tab_id)
+ '&filename=' + encodeURIComponent(f.filename);
- tr.innerHTML = '' + f.tab_id + ' | '
+ const userCol = isAll ? '' + owner + ' | ' : '';
+ tr.innerHTML = userCol
+ + '' + f.tab_id + ' | '
+ '' + f.filename.replace(/'
+ ' | ' + fmtSize(f.size) + ' | '
+ '' + ts + ' | '