532 lines
18 KiB
JavaScript
532 lines
18 KiB
JavaScript
'use strict';
|
|
|
|
const $ = id => document.getElementById(id);
|
|
|
|
const dropzone = $('dropzone');
|
|
const fileInput = $('fileInput');
|
|
const progressList = $('progressList');
|
|
const actionRow = $('actionRow');
|
|
const uploadBtn = $('uploadBtn');
|
|
const clearBtn = $('clearBtn');
|
|
const filesList = $('filesList');
|
|
const filesMeta = $('filesMeta');
|
|
const quotaWrap = $('quotaWrap');
|
|
const quotaText = $('quotaText');
|
|
const quotaPercent = $('quotaPercent');
|
|
const quotaBar = $('quotaBar');
|
|
const toastEl = $('toast');
|
|
const totalProgress= $('totalProgress');
|
|
const totalLabel = $('totalLabel');
|
|
const checkAll = $('checkAll');
|
|
const checkAllWrap = $('checkAllWrap');
|
|
const batchBtn = $('batchBtn');
|
|
const batchCount = $('batchCount');
|
|
const batchDeleteBtn = $('batchDeleteBtn');
|
|
const batchDeleteCount= $('batchDeleteCount');
|
|
|
|
// 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 声明, 跨文件共享 (classic <script> 加载顺序: app.js → helpers.js → batch.js).
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Toast
|
|
// ---------------------------------------------------------------------------
|
|
let toastTimer = null;
|
|
function toast(msg, type) {
|
|
toastEl.textContent = msg;
|
|
toastEl.className = 'toast show ' + (type || 'info');
|
|
if (toastTimer) clearTimeout(toastTimer);
|
|
toastTimer = setTimeout(() => toastEl.classList.remove('show'), 2400);
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Drop zone (用 counter 解决子元素上 dragleave 反复触发的 bug)
|
|
// ---------------------------------------------------------------------------
|
|
let dragCounter = 0;
|
|
dropzone.addEventListener('dragenter', e => {
|
|
e.preventDefault();
|
|
dragCounter++;
|
|
dropzone.classList.add('dragover');
|
|
});
|
|
dropzone.addEventListener('dragover', e => e.preventDefault());
|
|
dropzone.addEventListener('dragleave', e => {
|
|
e.preventDefault();
|
|
dragCounter--;
|
|
if (dragCounter <= 0) {
|
|
dragCounter = 0;
|
|
dropzone.classList.remove('dragover');
|
|
}
|
|
});
|
|
dropzone.addEventListener('drop', e => {
|
|
e.preventDefault();
|
|
dragCounter = 0;
|
|
dropzone.classList.remove('dragover');
|
|
if (e.dataTransfer && e.dataTransfer.files) addFiles(e.dataTransfer.files);
|
|
});
|
|
fileInput.addEventListener('change', e => {
|
|
addFiles(e.target.files);
|
|
// reset 后允许重复选择同一文件
|
|
e.target.value = '';
|
|
});
|
|
|
|
// 点击 / 键盘 触发文件选择
|
|
dropzone.addEventListener('click', () => fileInput.click());
|
|
dropzone.addEventListener('keydown', e => {
|
|
if (e.key === 'Enter' || e.key === ' ') {
|
|
e.preventDefault();
|
|
fileInput.click();
|
|
}
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Pending list
|
|
// ---------------------------------------------------------------------------
|
|
function addFiles(fileList) {
|
|
for (const f of fileList) {
|
|
pending.push({
|
|
id: nextId++,
|
|
file: f,
|
|
xhr: null,
|
|
chunkXhrs: new Set(),
|
|
chunkProgress: null,
|
|
status: 'pending',
|
|
progress: 0,
|
|
loaded: 0,
|
|
});
|
|
}
|
|
renderPending();
|
|
}
|
|
|
|
function renderPending() {
|
|
progressList.innerHTML = '';
|
|
if (pending.length === 0) {
|
|
actionRow.style.display = 'none';
|
|
return;
|
|
}
|
|
actionRow.style.display = 'flex';
|
|
|
|
pending.forEach(item => {
|
|
const div = document.createElement('div');
|
|
div.className = 'progress-item';
|
|
if (item.status === 'done') div.classList.add('done');
|
|
else if (item.status === 'error') div.classList.add('error');
|
|
|
|
const statusChar =
|
|
item.status === 'done' ? '✓' :
|
|
item.status === 'error' ? '✗' :
|
|
item.status === 'cancelled' ? '⊘' : '';
|
|
|
|
const sizeInfo = (item.file.size > 0
|
|
? `${formatSize(item.loaded)} / ${formatSize(item.file.size)}`
|
|
: formatSize(item.file.size)) + (item.file.size > CHUNK_THRESHOLD ? ' (分片上传)' : '');
|
|
|
|
div.innerHTML = `
|
|
<div class="progress-item-head">
|
|
<span class="name" title="${escapeHtml(item.file.name)}">${escapeHtml(item.file.name)}</span>
|
|
<span class="size-info">${sizeInfo}</span>
|
|
<span class="status">${statusChar}</span>
|
|
</div>
|
|
<div class="progress-bar"><div style="width:${item.progress}%"></div></div>
|
|
<div class="progress-item-actions"></div>
|
|
`;
|
|
const actions = div.querySelector('.progress-item-actions');
|
|
|
|
if (item.status === 'pending' || item.status === 'uploading') {
|
|
const cancel = document.createElement('button');
|
|
cancel.textContent = item.status === 'uploading' ? '取消' : '移除';
|
|
cancel.onclick = () => cancelItem(item.id);
|
|
actions.appendChild(cancel);
|
|
} else if (item.status === 'error' || item.status === 'cancelled') {
|
|
const retry = document.createElement('button');
|
|
retry.textContent = '重试';
|
|
retry.onclick = () => {
|
|
item.status = 'pending';
|
|
item.progress = 0;
|
|
item.loaded = 0;
|
|
item.error = null;
|
|
renderPending();
|
|
};
|
|
const remove = document.createElement('button');
|
|
remove.textContent = '移除';
|
|
remove.onclick = () => removeItem(item.id);
|
|
actions.appendChild(retry);
|
|
actions.appendChild(remove);
|
|
} else if (item.status === 'done') {
|
|
const remove = document.createElement('button');
|
|
remove.textContent = '移除';
|
|
remove.onclick = () => removeItem(item.id);
|
|
actions.appendChild(remove);
|
|
}
|
|
progressList.appendChild(div);
|
|
});
|
|
|
|
// 总进度
|
|
const total = pending.length;
|
|
const finished = pending.filter(p => p.status === 'done').length;
|
|
if (isUploading && total > 0) {
|
|
totalProgress.style.display = 'block';
|
|
totalLabel.style.display = 'inline';
|
|
const pct = Math.round(finished / total * 100);
|
|
totalProgress.firstElementChild.style.width = pct + '%';
|
|
totalLabel.textContent = `${finished} / ${total} · ${pct}%`;
|
|
} else {
|
|
totalProgress.style.display = 'none';
|
|
totalLabel.style.display = 'none';
|
|
}
|
|
}
|
|
|
|
function cancelItem(id) {
|
|
const item = pending.find(p => p.id === id);
|
|
if (!item) return;
|
|
item.chunkXhrs.forEach(x => x.abort());
|
|
item.chunkXhrs.clear();
|
|
if (item.xhr) {
|
|
item.xhr.abort();
|
|
item.status = 'cancelled';
|
|
} else {
|
|
removeItem(id);
|
|
return;
|
|
}
|
|
renderPending();
|
|
}
|
|
|
|
function removeItem(id) {
|
|
const item = pending.find(p => p.id === id);
|
|
if (item) {
|
|
item.chunkXhrs.forEach(x => x.abort());
|
|
item.chunkXhrs.clear();
|
|
if (item.xhr && item.xhr.readyState !== XMLHttpRequest.DONE) item.xhr.abort();
|
|
}
|
|
pending = pending.filter(p => p.id !== id);
|
|
renderPending();
|
|
}
|
|
|
|
clearBtn.addEventListener('click', () => {
|
|
// 取消所有进行中的上传
|
|
pending.forEach(p => {
|
|
p.chunkXhrs.forEach(x => x.abort());
|
|
p.chunkXhrs.clear();
|
|
if (p.xhr && p.xhr.readyState !== XMLHttpRequest.DONE) p.xhr.abort();
|
|
});
|
|
pending = [];
|
|
isUploading = false;
|
|
renderPending();
|
|
uploadBtn.disabled = false;
|
|
uploadBtn.textContent = '开始上传';
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Upload
|
|
// ---------------------------------------------------------------------------
|
|
uploadBtn.addEventListener('click', async () => {
|
|
if (isUploading) return;
|
|
const queue = pending.filter(p => p.status === 'pending' || p.status === 'error' || p.status === 'cancelled');
|
|
if (queue.length === 0) {
|
|
toast('没有可上传的文件', 'error');
|
|
return;
|
|
}
|
|
await loadFiles();
|
|
const totalSize = queue.reduce((s, i) => s + i.file.size, 0);
|
|
if (quotaState.cap > 0 && totalSize > quotaState.cap - quotaState.used) {
|
|
toast(`队列总大小 ${formatSize(totalSize)} 超过剩余配额 ${formatSize(quotaState.cap - quotaState.used)}`, 'error');
|
|
return;
|
|
}
|
|
isUploading = true;
|
|
uploadBtn.disabled = true;
|
|
uploadBtn.textContent = '上传中...';
|
|
|
|
const tasks = queue.map(item => async () => {
|
|
if (item.status !== 'pending' && item.status !== 'error' && item.status !== 'cancelled') return;
|
|
item.status = 'uploading';
|
|
item.progress = 0;
|
|
item.loaded = 0;
|
|
item.error = null;
|
|
renderPending();
|
|
try {
|
|
await (item.file.size > CHUNK_THRESHOLD ? uploadChunked(item) : uploadOne(item));
|
|
item.status = 'done';
|
|
item.progress = 100;
|
|
} catch (err) {
|
|
if (err.name !== 'AbortError') {
|
|
item.status = 'error';
|
|
item.error = err && err.message || 'unknown';
|
|
toast(`上传失败: ${item.file.name} - ${item.error}`, 'error');
|
|
}
|
|
}
|
|
renderPending();
|
|
});
|
|
await runWithLimit(tasks, 3);
|
|
|
|
isUploading = false;
|
|
uploadBtn.disabled = false;
|
|
uploadBtn.textContent = '开始上传';
|
|
await loadFiles();
|
|
// 已完成的进度条 2.5s 后从 pending 移除, 避免列表里堆一堆"已完成"
|
|
const doneItems = pending.filter(p => p.status === 'done');
|
|
if (doneItems.length > 0) {
|
|
setTimeout(() => {
|
|
const doneIds = new Set(doneItems.map(p => p.id));
|
|
pending = pending.filter(p => !doneIds.has(p.id));
|
|
renderPending();
|
|
}, 2500);
|
|
}
|
|
});
|
|
|
|
async function runWithLimit(tasks, limit) {
|
|
const workers = Array.from({ length: limit }, async () => {
|
|
while (true) {
|
|
const t = tasks.shift();
|
|
if (!t) return;
|
|
await t();
|
|
}
|
|
});
|
|
await Promise.all(workers);
|
|
}
|
|
|
|
function uploadOne(item) {
|
|
return new Promise((resolve, reject) => {
|
|
const xhr = new XMLHttpRequest();
|
|
item.xhr = xhr;
|
|
const fd = new FormData();
|
|
fd.append('file', item.file);
|
|
xhr.open('POST', '/upload');
|
|
xhr.upload.onprogress = e => {
|
|
if (e.lengthComputable) {
|
|
item.progress = Math.round(e.loaded / e.total * 100);
|
|
item.loaded = e.loaded;
|
|
renderPending();
|
|
}
|
|
};
|
|
xhr.onload = () => {
|
|
if (xhr.status >= 200 && xhr.status < 300) {
|
|
try { resolve(JSON.parse(xhr.responseText)); }
|
|
catch { resolve({}); }
|
|
} else {
|
|
let msg = 'HTTP ' + xhr.status;
|
|
try { msg = JSON.parse(xhr.responseText).error || msg; } catch {}
|
|
reject(new Error(msg));
|
|
}
|
|
};
|
|
xhr.onerror = () => reject(new Error('network error'));
|
|
xhr.onabort = () => { const e = new Error('aborted'); e.name = 'AbortError'; reject(e); };
|
|
xhr.send(fd);
|
|
});
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 大文件分片上传 (>5GB, 1GB/片)
|
|
// ---------------------------------------------------------------------------
|
|
async function uploadChunked(item) {
|
|
const uploadId = uuid();
|
|
const totalChunks = Math.ceil(item.file.size / CHUNK_SIZE);
|
|
item.chunkProgress = new Array(totalChunks).fill(0);
|
|
let result = null;
|
|
const tasks = Array.from({ length: totalChunks }, (_, i) => async () => {
|
|
if (item.status !== 'uploading') return; // 已取消则不再发起新分片
|
|
const r = await uploadOneChunk(item, uploadId, i, totalChunks);
|
|
if (i === totalChunks - 1) result = r; // 末片响应即整个上传结果
|
|
});
|
|
await runWithLimit(tasks, 3);
|
|
return result;
|
|
}
|
|
|
|
// 单分片上传: 失败最多重试 3 次, 退避 500/1000/2000ms
|
|
function uploadOneChunk(item, uploadId, idx, total) {
|
|
return new Promise((resolve, reject) => {
|
|
const delays = [500, 1000, 2000];
|
|
const attempt = n => {
|
|
if (item.status === 'cancelled') {
|
|
const e = new Error('aborted'); e.name = 'AbortError'; reject(e);
|
|
return;
|
|
}
|
|
const xhr = new XMLHttpRequest();
|
|
item.chunkXhrs.add(xhr);
|
|
const fd = new FormData();
|
|
const start = idx * CHUNK_SIZE;
|
|
const end = Math.min(start + CHUNK_SIZE, item.file.size);
|
|
fd.append('chunk', item.file.slice(start, end));
|
|
xhr.open('POST', '/upload-chunk');
|
|
xhr.setRequestHeader('X-Upload-Id', uploadId);
|
|
xhr.setRequestHeader('X-Chunk-Index', String(idx));
|
|
xhr.setRequestHeader('X-Total-Chunks', String(total));
|
|
xhr.setRequestHeader('X-Filename', item.file.name);
|
|
xhr.setRequestHeader('X-Total-Size', String(item.file.size));
|
|
xhr.upload.onprogress = e => {
|
|
if (e.lengthComputable) {
|
|
item.chunkProgress[idx] = e.loaded;
|
|
item.loaded = item.chunkProgress.reduce((s, v) => s + v, 0);
|
|
item.progress = item.file.size ? Math.round(item.loaded / item.file.size * 100) : 0;
|
|
renderPending();
|
|
}
|
|
};
|
|
const cleanup = () => item.chunkXhrs.delete(xhr);
|
|
xhr.onload = () => {
|
|
cleanup();
|
|
if (xhr.status >= 200 && xhr.status < 300) {
|
|
if (idx === total - 1) {
|
|
let res = {};
|
|
try { res = JSON.parse(xhr.responseText); } catch {}
|
|
resolve(res);
|
|
} else {
|
|
resolve(undefined);
|
|
}
|
|
} else if (n < 4) {
|
|
setTimeout(() => attempt(n + 1), delays[n - 1]);
|
|
} else {
|
|
let msg = 'HTTP ' + xhr.status;
|
|
try { msg = JSON.parse(xhr.responseText).error || msg; } catch {}
|
|
reject(new Error(msg));
|
|
}
|
|
};
|
|
xhr.onerror = () => {
|
|
cleanup();
|
|
if (n < 4) setTimeout(() => attempt(n + 1), delays[n - 1]);
|
|
else reject(new Error('network error'));
|
|
};
|
|
xhr.onabort = () => {
|
|
cleanup();
|
|
const e = new Error('aborted'); e.name = 'AbortError'; reject(e);
|
|
};
|
|
xhr.send(fd);
|
|
};
|
|
attempt(1);
|
|
});
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// File list
|
|
// ---------------------------------------------------------------------------
|
|
let loadSeq = 0;
|
|
let quotaState = { cap: 0, used: 0 };
|
|
async function loadFiles() {
|
|
const my = ++loadSeq;
|
|
try {
|
|
const r = await fetch('/files');
|
|
if (my !== loadSeq) return;
|
|
const data = await r.json();
|
|
filesMeta.textContent = `共 ${data.count} 个文件 · TTL ${data.ttl}`;
|
|
renderQuota(data.quota);
|
|
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 = '加载失败';
|
|
}
|
|
}
|
|
|
|
function renderQuota(q) {
|
|
if (!q || !q.cap) {
|
|
quotaWrap.style.display = 'none';
|
|
return;
|
|
}
|
|
quotaWrap.style.display = 'block';
|
|
const pct = q.cap > 0 ? Math.min(100, (q.used / q.cap) * 100) : 0;
|
|
quotaText.innerHTML = `已用 <strong>${q.used_str || formatSize(q.used)}</strong> / ${q.cap_str || formatSize(q.cap)}`;
|
|
quotaPercent.textContent = pct.toFixed(1) + '%';
|
|
quotaBar.firstElementChild.style.width = pct + '%';
|
|
// 颜色随占用率
|
|
quotaBar.classList.remove('warn', 'danger');
|
|
quotaText.classList.remove('warn', 'danger');
|
|
if (pct >= 95) { quotaBar.classList.add('danger'); quotaText.classList.add('danger'); }
|
|
else if (pct >= 80) { quotaBar.classList.add('warn'); quotaText.classList.add('warn'); }
|
|
}
|
|
|
|
function fileRow(f) {
|
|
const div = document.createElement('div');
|
|
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>
|
|
<div class="file-meta">
|
|
<span>${formatSize(f.size)}</span>
|
|
<span>·</span>
|
|
${ttlHtml}
|
|
</div>
|
|
</div>
|
|
<div class="file-actions">
|
|
<button class="icon-btn" title="复制链接" data-url="${escapeHtml(f.url)}">⎘</button>
|
|
<a class="icon-btn" title="下载" href="${escapeHtml(f.url)}" download>↓</a>
|
|
<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;
|
|
}
|
|
|
|
async function deleteFile(filename, rowEl) {
|
|
if (!confirm(`确定删除 "${filename}" 吗? 该操作不可撤销.`)) return;
|
|
rowEl.style.opacity = '0.4';
|
|
rowEl.style.pointerEvents = 'none';
|
|
try {
|
|
const r = await fetch('/files/' + encodeURIComponent(filename), { method: 'DELETE' });
|
|
if (r.status === 404) {
|
|
toast('文件已不存在 (可能已过期被清理)', 'error');
|
|
await loadFiles();
|
|
return;
|
|
}
|
|
if (!r.ok) {
|
|
let msg = 'HTTP ' + r.status;
|
|
try { msg = (await r.json()).error || msg; } catch {}
|
|
throw new Error(msg);
|
|
}
|
|
toast(`已删除: ${filename}`, 'success');
|
|
await loadFiles();
|
|
} catch (e) {
|
|
rowEl.style.opacity = '';
|
|
rowEl.style.pointerEvents = '';
|
|
toast('删除失败: ' + e.message, 'error');
|
|
}
|
|
}
|
|
|
|
async function copyToClipboard(text) {
|
|
// 兼容 HTTP 环境: clipboard API 不可用时用 fallback
|
|
try {
|
|
if (navigator.clipboard && window.isSecureContext) {
|
|
await navigator.clipboard.writeText(text);
|
|
toast('链接已复制', 'success');
|
|
return;
|
|
}
|
|
} catch {}
|
|
// fallback: 临时 textarea
|
|
const ta = document.createElement('textarea');
|
|
ta.value = text;
|
|
ta.style.position = 'fixed';
|
|
ta.style.opacity = '0';
|
|
document.body.appendChild(ta);
|
|
ta.select();
|
|
try {
|
|
const ok = document.execCommand('copy');
|
|
toast(ok ? '链接已复制' : '复制失败, 请手动复制', ok ? 'success' : 'error');
|
|
} catch {
|
|
toast('复制失败, 请手动复制', 'error');
|
|
} finally {
|
|
document.body.removeChild(ta);
|
|
}
|
|
}
|
|
|
|
// formatRemain / isAlmostExpired / iconFor / formatSize / formatTime / escapeHtml
|
|
// 见 helpers.js; 倒计时 setInterval 也在 helpers.js 中启动
|