feat: batch download

This commit is contained in:
tao.chen
2026-08-27 19:35:30 +08:00
parent 7225b72906
commit a897a08534
10 changed files with 443 additions and 77 deletions
+30
View File
@@ -176,6 +176,29 @@
}
.files-header h2 { font-size: 16px; font-weight: 600; }
.files-header .meta { font-size: 12px; color: var(--text-dim); }
.files-header-right {
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
justify-content: flex-end;
}
.check-all-wrap {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 12px;
color: var(--text-dim);
cursor: pointer;
user-select: none;
}
.check-all-wrap input {
width: 14px;
height: 14px;
accent-color: var(--primary);
cursor: pointer;
}
.batch-btn { padding: 6px 14px; font-size: 13px; }
/* Quota */
.quota-wrap { margin-bottom: 16px; }
@@ -214,6 +237,13 @@
border-radius: 8px;
margin-bottom: 8px;
}
.file-check {
width: 18px;
height: 18px;
accent-color: var(--primary);
cursor: pointer;
flex-shrink: 0;
}
.file-icon {
width: 36px;
height: 36px;
+19 -64
View File
@@ -17,12 +17,18 @@ const quotaBar = $('quotaBar');
const toastEl = $('toast');
const totalProgress= $('totalProgress');
const totalLabel = $('totalLabel');
const checkAll = $('checkAll');
const checkAllWrap = $('checkAllWrap');
const batchBtn = $('batchBtn');
const batchCount = $('batchCount');
// pending[i] = { id, file, xhr, status: 'pending'|'uploading'|'done'|'error'|'cancelled', progress, error }
let pending = [];
let nextId = 1;
let isUploading = false;
// selectedFiles 在 batch.js 顶层 var 声明, 同 <script> 内共享.
// ---------------------------------------------------------------------------
// Toast
// ---------------------------------------------------------------------------
@@ -316,11 +322,19 @@ async function loadFiles() {
quotaState = data.quota;
if (!data.files || data.files.length === 0) {
filesList.innerHTML = '<div class="empty">暂无文件</div>';
selectedFiles.clear();
updateBatchUI();
return;
}
filesList.innerHTML = '';
data.files.sort((a, b) => new Date(b.mod_time) - new Date(a.mod_time));
// 清理已不存在文件的勾选 (跨刷新保留)
const currentNames = new Set(data.files.map(f => f.filename));
for (const n of [...selectedFiles]) {
if (!currentNames.has(n)) selectedFiles.delete(n);
}
data.files.forEach(f => filesList.appendChild(fileRow(f)));
updateBatchUI();
} catch (e) {
filesMeta.textContent = '加载失败';
}
@@ -348,7 +362,9 @@ function fileRow(f) {
div.className = 'file-item';
const ext = (f.filename.split('.').pop() || '').toLowerCase();
const ttlHtml = `<span class="ttl" data-expires="${f.expires_at}">${formatRemain(f.expires_at)}</span>`;
const checked = selectedFiles.has(f.filename) ? 'checked' : '';
div.innerHTML = `
<input type="checkbox" class="file-check" data-name="${escapeHtml(f.filename)}" ${checked} aria-label="选择 ${escapeHtml(f.filename)}" />
<div class="file-icon">${iconFor(ext)}</div>
<div class="file-info">
<div class="file-name" title="${escapeHtml(f.filename)}">${escapeHtml(f.filename)}</div>
@@ -364,6 +380,7 @@ function fileRow(f) {
<button class="icon-btn danger" title="删除" data-delete="${escapeHtml(f.filename)}">✕</button>
</div>
`;
div.querySelector('.file-check').addEventListener('change', e => onCheckChange(f.filename, e.target.checked));
div.querySelector('[data-url]').onclick = () => copyToClipboard(location.origin + f.url);
div.querySelector('[data-delete]').onclick = () => deleteFile(f.filename, div);
return div;
@@ -420,67 +437,5 @@ async function copyToClipboard(text) {
}
}
// ---------------------------------------------------------------------------
// 倒计时: 每秒刷新一次剩余时间
// ---------------------------------------------------------------------------
setInterval(() => {
document.querySelectorAll('[data-expires]').forEach(el => {
el.textContent = formatRemain(el.dataset.expires);
el.classList.toggle('danger', isAlmostExpired(el.dataset.expires));
});
}, 1000);
function isAlmostExpired(iso) {
const ms = new Date(iso).getTime() - Date.now();
return ms > 0 && ms < 60 * 60 * 1000; // < 1h
}
function formatRemain(iso) {
const ms = new Date(iso).getTime() - Date.now();
if (ms <= 0) return '已过期';
const s = Math.floor(ms / 1000);
if (s < 60) return `${s}`;
const m = Math.floor(s / 60);
if (m < 60) return `${m} 分钟`;
const h = Math.floor(m / 60);
if (h < 24) return `${h} 小时${m % 60 ? ' ' + (m % 60) + ' 分' : ''}`;
const d = Math.floor(h / 24);
return `${d}${h % 24 ? ' ' + (h % 24) + ' 小时' : ''}`;
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function iconFor(ext) {
const map = { pdf:'📄', zip:'📦', rar:'📦', '7z':'📦', txt:'📄', md:'📄',
png:'🖼', jpg:'🖼', jpeg:'🖼', gif:'🖼', webp:'🖼', svg:'🖼',
mp4:'🎬', mov:'🎬', avi:'🎬', mkv:'🎬',
mp3:'🎵', wav:'🎵', flac:'🎵',
xls:'📊', xlsx:'📊', csv:'📊',
doc:'📃', docx:'📃', ppt:'📽', pptx:'📽' };
return map[ext] || '📁';
}
function formatSize(b) {
if (b == null || isNaN(b)) return '-';
if (b < 1024) return b + ' B';
if (b < 1024 * 1024) return (b / 1024).toFixed(1) + ' KB';
if (b < 1024 * 1024 * 1024) return (b / 1024 / 1024).toFixed(2) + ' MB';
return (b / 1024 / 1024 / 1024).toFixed(2) + ' GB';
}
function formatTime(iso) {
const d = new Date(iso);
const pad = n => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
}
// ---------------------------------------------------------------------------
// Boot
// ---------------------------------------------------------------------------
loadFiles();
setInterval(loadFiles, 30000);
// formatRemain / isAlmostExpired / iconFor / formatSize / formatTime / escapeHtml
// 见 helpers.js; 倒计时 setInterval 也在 helpers.js 中启动
+88
View File
@@ -0,0 +1,88 @@
'use strict';
// ---------------------------------------------------------------------------
// 批量选择 / 批量下载 (依赖 app.js 的 consts: checkAll, checkAllWrap,
// batchBtn, batchCount, filesList, toast)
// 用 var 顶层声明, 与 app.js 同 <script> 内共享 (loadFiles / fileRow 读写).
// ---------------------------------------------------------------------------
var selectedFiles = new Set();
function onCheckChange(name, checked) {
if (checked) selectedFiles.add(name);
else selectedFiles.delete(name);
updateBatchUI();
}
function updateBatchUI() {
const n = selectedFiles.size;
batchCount.textContent = n;
batchBtn.style.display = n > 0 ? 'inline-block' : 'none';
const checks = filesList.querySelectorAll('.file-check');
if (checks.length === 0) {
checkAllWrap.style.display = 'none';
checkAll.checked = false;
checkAll.indeterminate = false;
return;
}
checkAllWrap.style.display = 'inline-flex';
let checkedCount = 0;
checks.forEach(c => { if (c.checked) checkedCount++; });
checkAll.checked = checkedCount === checks.length;
checkAll.indeterminate = checkedCount > 0 && checkedCount < checks.length;
}
checkAll.addEventListener('change', () => {
const want = checkAll.checked;
filesList.querySelectorAll('.file-check').forEach(c => {
if (c.checked !== want) {
c.checked = want;
const name = c.dataset.name;
if (want) selectedFiles.add(name);
else selectedFiles.delete(name);
}
});
updateBatchUI();
});
batchBtn.addEventListener('click', async () => {
if (selectedFiles.size === 0) return;
const names = [...selectedFiles];
batchBtn.disabled = true;
const restore = () => { batchBtn.disabled = false; batchBtn.textContent = `批量下载 (${selectedFiles.size})`; };
batchBtn.textContent = '打包中...';
try {
const r = await fetch('/download-zip', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ files: names }),
});
if (!r.ok) {
let msg = 'HTTP ' + r.status;
try { msg = (await r.json()).error || msg; } catch {}
throw new Error(msg);
}
// 从 Content-Disposition 取 server 起的 zip 文件名, 兜底 'files.zip'
let fname = 'files.zip';
const cd = r.headers.get('Content-Disposition') || '';
const m = cd.match(/filename="?([^";]+)"?/);
if (m) fname = m[1];
const blob = await r.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url; a.download = fname;
document.body.appendChild(a); a.click(); document.body.removeChild(a);
setTimeout(() => URL.revokeObjectURL(url), 1000);
toast(`已下载 ${names.length} 个文件`, 'success');
} catch (e) {
toast('批量下载失败: ' + e.message, 'error');
} finally {
restore();
}
});
// ---------------------------------------------------------------------------
// Boot (从 app.js 末尾移过来, 确保 selectedFiles 已声明再启动首次 loadFiles)
// ---------------------------------------------------------------------------
loadFiles();
setInterval(loadFiles, 30000);
+59
View File
@@ -0,0 +1,59 @@
'use strict';
// ---------------------------------------------------------------------------
// 纯函数 + 倒计时 interval
// 与 app.js 同 <script> 内共享 (load order: app → helpers → batch).
// ---------------------------------------------------------------------------
function formatRemain(iso) {
const ms = new Date(iso).getTime() - Date.now();
if (ms <= 0) return '已过期';
const s = Math.floor(ms / 1000);
if (s < 60) return `${s}`;
const m = Math.floor(s / 60);
if (m < 60) return `${m} 分钟`;
const h = Math.floor(m / 60);
if (h < 24) return `${h} 小时${m % 60 ? ' ' + (m % 60) + ' 分' : ''}`;
const d = Math.floor(h / 24);
return `${d}${h % 24 ? ' ' + (h % 24) + ' 小时' : ''}`;
}
function isAlmostExpired(iso) {
const ms = new Date(iso).getTime() - Date.now();
return ms > 0 && ms < 60 * 60 * 1000; // < 1h
}
setInterval(() => {
document.querySelectorAll('[data-expires]').forEach(el => {
el.textContent = formatRemain(el.dataset.expires);
el.classList.toggle('danger', isAlmostExpired(el.dataset.expires));
});
}, 1000);
function iconFor(ext) {
const map = { pdf:'📄', zip:'📦', rar:'📦', '7z':'📦', txt:'📄', md:'📄',
png:'🖼', jpg:'🖼', jpeg:'🖼', gif:'🖼', webp:'🖼', svg:'🖼',
mp4:'🎬', mov:'🎬', avi:'🎬', mkv:'🎬',
mp3:'🎵', wav:'🎵', flac:'🎵',
xls:'📊', xlsx:'📊', csv:'📊',
doc:'📃', docx:'📃', ppt:'📽', pptx:'📽' };
return map[ext] || '📁';
}
function formatSize(b) {
if (b == null || isNaN(b)) return '-';
if (b < 1024) return b + ' B';
if (b < 1024 * 1024) return (b / 1024).toFixed(1) + ' KB';
if (b < 1024 * 1024 * 1024) return (b / 1024 / 1024).toFixed(2) + ' MB';
return (b / 1024 / 1024 / 1024).toFixed(2) + ' GB';
}
function formatTime(iso) {
const d = new Date(iso);
const pad = n => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
}
+8 -1
View File
@@ -35,7 +35,14 @@
<div class="card">
<div class="files-header">
<h2>文件列表</h2>
<span class="meta" id="filesMeta">加载中...</span>
<div class="files-header-right">
<label class="check-all-wrap" id="checkAllWrap" style="display:none">
<input type="checkbox" id="checkAll" />
<span>全选</span>
</label>
<span class="meta" id="filesMeta">加载中...</span>
<button class="btn ghost batch-btn" id="batchBtn" style="display:none">批量下载 (<span id="batchCount">0</span>)</button>
</div>
</div>
<div class="quota-wrap" id="quotaWrap" style="display:none">
<div class="quota-row">