- 新增 cabinet 应用:Folder / StoredFile 及迁移 - 浏览公开;下载、新建目录、上传需要密码解锁(session 120 分钟) - 文件存放在 MEDIA_ROOT 之外的 storage/,下载必须经过视图鉴权 - 支持多级目录、文件名清洗、重名自动编号、分批上传与进度 - 页面:分类卡片、面包屑、文件行点击下载、上传进度、密码弹窗 - 修复弹窗命中测试:浮层移到 body、提升 z-index、去掉模糊与位移动画 - 首页新增「拾匣」入口
488 lines
16 KiB
JavaScript
488 lines
16 KiB
JavaScript
/* =========================================================
|
||
拾匣 · 交互
|
||
浏览公开;下载 / 上传 / 新建目录需要密码解锁。
|
||
========================================================= */
|
||
(function () {
|
||
'use strict';
|
||
|
||
var root = document.getElementById('cabinet');
|
||
if (!root) return;
|
||
|
||
var csrfMeta = document.querySelector('meta[name="csrf-token"]');
|
||
var CSRF = csrfMeta ? csrfMeta.getAttribute('content') || '' : '';
|
||
|
||
var el = {
|
||
lockBadge: document.getElementById('cbLockBadge'),
|
||
lockText: document.getElementById('cbLockText'),
|
||
lockBtn: document.getElementById('cbLockBtn'),
|
||
hint: document.getElementById('cbHint'),
|
||
newFolder: document.getElementById('cbNewFolder'),
|
||
upload: document.getElementById('cbUpload'),
|
||
fileInput: document.getElementById('cbFileInput'),
|
||
|
||
passwordModal: document.getElementById('cbPasswordModal'),
|
||
passwordForm: document.getElementById('cbPasswordForm'),
|
||
passwordInput: document.getElementById('cbPasswordInput'),
|
||
passwordError: document.getElementById('cbPasswordError'),
|
||
passwordSubmit: document.getElementById('cbPasswordSubmit'),
|
||
|
||
folderModal: document.getElementById('cbFolderModal'),
|
||
folderForm: document.getElementById('cbFolderForm'),
|
||
folderName: document.getElementById('cbFolderName'),
|
||
folderError: document.getElementById('cbFolderError'),
|
||
folderSubmit: document.getElementById('cbFolderSubmit'),
|
||
|
||
uploadPanel: document.getElementById('cbUploadPanel'),
|
||
uploadTitle: document.getElementById('cbUploadTitle'),
|
||
uploadMeta: document.getElementById('cbUploadMeta'),
|
||
progressBar: document.getElementById('cbProgressBar'),
|
||
uploadClose: document.getElementById('cbUploadClose'),
|
||
|
||
toast: document.getElementById('cbToast')
|
||
};
|
||
|
||
var state = {
|
||
unlocked: root.getAttribute('data-unlocked') === 'true',
|
||
folderId: root.getAttribute('data-folder-id') || '',
|
||
maxMb: parseInt(root.getAttribute('data-max-mb'), 10) || 200,
|
||
pendingAction: null,
|
||
pendingFiles: null,
|
||
uploading: false,
|
||
toastTimer: null
|
||
};
|
||
|
||
function setUnlocked(value) {
|
||
state.unlocked = !!value;
|
||
if (el.lockBadge) el.lockBadge.classList.toggle('is-open', state.unlocked);
|
||
if (el.lockText) el.lockText.textContent = state.unlocked ? '已解锁' : '未解锁';
|
||
if (el.lockBtn) {
|
||
el.lockBtn.hidden = false;
|
||
el.lockBtn.textContent = state.unlocked ? '锁定' : '解锁';
|
||
}
|
||
if (el.hint) el.hint.hidden = state.unlocked;
|
||
}
|
||
|
||
function toast(message, isError) {
|
||
if (!message) return;
|
||
el.toast.textContent = message;
|
||
el.toast.classList.toggle('is-error', !!isError);
|
||
el.toast.hidden = false;
|
||
window.clearTimeout(state.toastTimer);
|
||
state.toastTimer = window.setTimeout(function () { el.toast.hidden = true; }, 2800);
|
||
}
|
||
|
||
async function api(url, options) {
|
||
options = options || {};
|
||
var response = await fetch(url, {
|
||
method: options.method || 'POST',
|
||
credentials: 'same-origin',
|
||
headers: Object.assign({
|
||
'Accept': 'application/json',
|
||
'X-CSRFToken': CSRF
|
||
}, options.headers || {}),
|
||
body: options.body
|
||
});
|
||
|
||
var data = null;
|
||
try { data = await response.json(); } catch (err) {}
|
||
|
||
if (!response.ok) {
|
||
var error = new Error((data && data.error) || ('请求失败(HTTP ' + response.status + ')'));
|
||
error.code = data && data.code;
|
||
error.status = response.status;
|
||
throw error;
|
||
}
|
||
return data || {};
|
||
}
|
||
|
||
function postJson(url, payload) {
|
||
return api(url, {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify(payload || {})
|
||
});
|
||
}
|
||
|
||
/* ---------- 弹窗 ---------- */
|
||
function openModal(modal, focusEl) {
|
||
if (!modal) return;
|
||
[el.passwordModal, el.folderModal].forEach(function (item) {
|
||
if (item && item !== modal) item.hidden = true;
|
||
});
|
||
modal.hidden = false;
|
||
document.documentElement.classList.add('cb-modal-open');
|
||
document.body.classList.add('cb-modal-open');
|
||
if (focusEl) window.setTimeout(function () { focusEl.focus(); }, 30);
|
||
}
|
||
|
||
function closeModals() {
|
||
if (el.passwordModal) el.passwordModal.hidden = true;
|
||
if (el.folderModal) el.folderModal.hidden = true;
|
||
document.documentElement.classList.remove('cb-modal-open');
|
||
document.body.classList.remove('cb-modal-open');
|
||
}
|
||
|
||
function cancelModals() {
|
||
closeModals();
|
||
state.pendingAction = null;
|
||
state.pendingFiles = null;
|
||
}
|
||
|
||
function showPasswordError(message) {
|
||
el.passwordError.textContent = message;
|
||
el.passwordError.hidden = false;
|
||
}
|
||
|
||
function showFolderError(message) {
|
||
el.folderError.textContent = message;
|
||
el.folderError.hidden = false;
|
||
}
|
||
|
||
function requireUnlock(action) {
|
||
if (state.unlocked) {
|
||
action();
|
||
return;
|
||
}
|
||
state.pendingAction = action;
|
||
el.passwordError.hidden = true;
|
||
openModal(el.passwordModal, el.passwordInput);
|
||
}
|
||
|
||
/* ---------- 解锁 / 锁定 ---------- */
|
||
el.passwordForm.addEventListener('submit', async function (event) {
|
||
event.preventDefault();
|
||
|
||
var password = el.passwordInput.value;
|
||
if (!password) {
|
||
showPasswordError('请输入密码');
|
||
return;
|
||
}
|
||
|
||
el.passwordSubmit.disabled = true;
|
||
el.passwordError.hidden = true;
|
||
|
||
try {
|
||
var data = await postJson('/files/unlock/', { password: password });
|
||
setUnlocked(true);
|
||
closeModals();
|
||
toast('已解锁,' + (data.minutes || 120) + ' 分钟内有效');
|
||
|
||
var action = state.pendingAction;
|
||
state.pendingAction = null;
|
||
el.passwordInput.value = '';
|
||
if (action) action();
|
||
} catch (error) {
|
||
showPasswordError(error.message || '解锁失败');
|
||
el.passwordInput.select();
|
||
} finally {
|
||
el.passwordSubmit.disabled = false;
|
||
}
|
||
});
|
||
|
||
function promptUnlock() {
|
||
state.pendingAction = null;
|
||
el.passwordError.hidden = true;
|
||
el.passwordInput.value = '';
|
||
openModal(el.passwordModal, el.passwordInput);
|
||
}
|
||
|
||
el.lockBtn.addEventListener('click', async function () {
|
||
if (!state.unlocked) {
|
||
promptUnlock();
|
||
return;
|
||
}
|
||
|
||
try {
|
||
await postJson('/files/lock/', {});
|
||
setUnlocked(false);
|
||
toast('已锁定');
|
||
} catch (error) {
|
||
toast(error.message || '锁定失败', true);
|
||
}
|
||
});
|
||
|
||
/* ---------- 下载 ---------- */
|
||
function downloadFile(button) {
|
||
if (button.disabled) return;
|
||
|
||
var fileId = button.getAttribute('data-file-id');
|
||
var fileName = button.getAttribute('data-file-name') || 'download';
|
||
var original = button.textContent;
|
||
|
||
button.disabled = true;
|
||
button.textContent = '下载中…';
|
||
|
||
fetch('/files/download/' + fileId + '/', {
|
||
credentials: 'same-origin',
|
||
headers: { 'Accept': 'application/octet-stream' }
|
||
}).then(function (response) {
|
||
if (response.status === 403) {
|
||
setUnlocked(false);
|
||
state.pendingAction = function () { downloadFile(button); };
|
||
el.passwordError.hidden = true;
|
||
openModal(el.passwordModal, el.passwordInput);
|
||
showPasswordError('登录已过期,请重新解锁');
|
||
return null;
|
||
}
|
||
if (!response.ok) {
|
||
return response.json().catch(function () { return {}; }).then(function (data) {
|
||
throw new Error((data && data.error) || '下载失败');
|
||
});
|
||
}
|
||
return response.blob();
|
||
}).then(function (blob) {
|
||
if (!blob) return;
|
||
var url = URL.createObjectURL(blob);
|
||
var link = document.createElement('a');
|
||
link.href = url;
|
||
link.download = fileName;
|
||
document.body.appendChild(link);
|
||
link.click();
|
||
link.remove();
|
||
window.setTimeout(function () { URL.revokeObjectURL(url); }, 4000);
|
||
toast('开始下载');
|
||
}).catch(function (error) {
|
||
toast(error.message || '下载失败', true);
|
||
}).finally(function () {
|
||
button.disabled = false;
|
||
button.textContent = original;
|
||
});
|
||
}
|
||
|
||
Array.prototype.forEach.call(document.querySelectorAll('.cb-download'), function (button) {
|
||
button.addEventListener('click', function () {
|
||
requireUnlock(function () { downloadFile(button); });
|
||
});
|
||
});
|
||
|
||
// 点击文件行(名称、图标、大小、时间)也触发下载;避免和按钮重复
|
||
Array.prototype.forEach.call(document.querySelectorAll('.cb-file[data-file-id]'), function (row) {
|
||
var button = row.querySelector('.cb-download');
|
||
if (!button) return;
|
||
|
||
row.addEventListener('click', function (event) {
|
||
if (event.target.closest('.cb-download')) return;
|
||
if (window.getSelection && String(window.getSelection()).length) return;
|
||
button.click();
|
||
});
|
||
});
|
||
|
||
/* ---------- 新建目录 ---------- */
|
||
el.newFolder.addEventListener('click', function () {
|
||
requireUnlock(function () {
|
||
el.folderName.value = '';
|
||
el.folderError.hidden = true;
|
||
openModal(el.folderModal, el.folderName);
|
||
});
|
||
});
|
||
|
||
el.folderForm.addEventListener('submit', async function (event) {
|
||
event.preventDefault();
|
||
|
||
var name = el.folderName.value.trim();
|
||
if (!name) {
|
||
showFolderError('给目录起个名字');
|
||
return;
|
||
}
|
||
|
||
el.folderSubmit.disabled = true;
|
||
el.folderError.hidden = true;
|
||
|
||
try {
|
||
await postJson('/files/folders/create/', {
|
||
name: name,
|
||
parent_id: state.folderId || null
|
||
});
|
||
closeModals();
|
||
toast('目录已创建');
|
||
window.setTimeout(function () { window.location.reload(); }, 450);
|
||
} catch (error) {
|
||
if (error.code === 'locked') {
|
||
setUnlocked(false);
|
||
closeModals();
|
||
toast('登录已过期,请重新解锁', true);
|
||
} else {
|
||
showFolderError(error.message || '创建失败');
|
||
}
|
||
} finally {
|
||
el.folderSubmit.disabled = false;
|
||
}
|
||
});
|
||
|
||
/* ---------- 上传 ---------- */
|
||
el.upload.addEventListener('click', function () {
|
||
// label 会原生打开文件选择;这里只清旧值,让同一文件也能再次触发 change
|
||
el.fileInput.value = '';
|
||
});
|
||
|
||
el.fileInput.addEventListener('change', function () {
|
||
var files = Array.prototype.slice.call(el.fileInput.files || []);
|
||
if (!files.length) return;
|
||
|
||
if (!state.unlocked) {
|
||
state.pendingFiles = files;
|
||
state.pendingAction = function () { uploadFiles(files); };
|
||
el.passwordError.hidden = true;
|
||
openModal(el.passwordModal, el.passwordInput);
|
||
return;
|
||
}
|
||
|
||
uploadFiles(files);
|
||
});
|
||
|
||
var UPLOAD_BATCH = 10;
|
||
|
||
function uploadBatch(formData, onProgress) {
|
||
return new Promise(function (resolve, reject) {
|
||
var xhr = new XMLHttpRequest();
|
||
xhr.open('POST', '/files/upload/');
|
||
xhr.setRequestHeader('X-CSRFToken', CSRF);
|
||
xhr.setRequestHeader('Accept', 'application/json');
|
||
|
||
xhr.upload.onprogress = function (event) {
|
||
if (event.lengthComputable) onProgress(event.loaded, event.total);
|
||
};
|
||
xhr.onload = function () {
|
||
var data = null;
|
||
try { data = JSON.parse(xhr.responseText); } catch (err) {}
|
||
resolve({ status: xhr.status, data: data });
|
||
};
|
||
xhr.onerror = function () { reject(new Error('上传失败,请检查网络')); };
|
||
xhr.send(formData);
|
||
});
|
||
}
|
||
|
||
async function uploadFiles(files) {
|
||
if (state.uploading) {
|
||
toast('正在上传,请稍候');
|
||
return;
|
||
}
|
||
|
||
var maxBytes = state.maxMb * 1024 * 1024;
|
||
var accepted = files.filter(function (file) { return file.size <= maxBytes; });
|
||
var skipped = files.length - accepted.length;
|
||
|
||
if (skipped) {
|
||
toast('有 ' + skipped + ' 个文件超过 ' + state.maxMb + ' MB,已跳过', true);
|
||
}
|
||
if (!accepted.length) return;
|
||
|
||
state.uploading = true;
|
||
el.uploadPanel.hidden = false;
|
||
el.progressBar.style.width = '0%';
|
||
el.uploadTitle.textContent = '准备上传 ' + accepted.length + ' 个文件';
|
||
el.uploadMeta.textContent = accepted.map(function (file) { return file.name; }).join(' · ');
|
||
|
||
var totalBytes = accepted.reduce(function (sum, file) {
|
||
return sum + (file.size || 0);
|
||
}, 0) || 1;
|
||
var sentBytes = 0;
|
||
var uploaded = 0;
|
||
var failed = 0;
|
||
var firstError = '';
|
||
|
||
try {
|
||
for (var offset = 0; offset < accepted.length; offset += UPLOAD_BATCH) {
|
||
var batch = accepted.slice(offset, offset + UPLOAD_BATCH);
|
||
var form = new FormData();
|
||
if (state.folderId) form.append('folder_id', state.folderId);
|
||
batch.forEach(function (file) { form.append('files', file); });
|
||
|
||
var batchBytes = batch.reduce(function (sum, file) {
|
||
return sum + (file.size || 0);
|
||
}, 0);
|
||
|
||
el.uploadTitle.textContent = '正在上传 · ' + (uploaded + failed) + '/' + accepted.length;
|
||
|
||
var result;
|
||
try {
|
||
result = await uploadBatch(form, function (loaded) {
|
||
var percent = Math.round((sentBytes + loaded) / totalBytes * 100);
|
||
el.progressBar.style.width = Math.min(percent, 99) + '%';
|
||
});
|
||
} catch (error) {
|
||
failed += batch.length;
|
||
firstError = firstError || error.message;
|
||
sentBytes += batchBytes;
|
||
el.uploadMeta.textContent = '已上传 ' + uploaded + ' 个,失败 ' + failed + ' 个';
|
||
continue;
|
||
}
|
||
|
||
sentBytes += batchBytes;
|
||
|
||
if (result.status === 403 && result.data && result.data.code === 'locked') {
|
||
setUnlocked(false);
|
||
el.uploadPanel.hidden = true;
|
||
var remaining = accepted.slice(offset);
|
||
state.pendingFiles = remaining;
|
||
state.pendingAction = function () { uploadFiles(remaining); };
|
||
el.passwordError.hidden = true;
|
||
openModal(el.passwordModal, el.passwordInput);
|
||
showPasswordError('登录已过期,请重新解锁');
|
||
return;
|
||
}
|
||
|
||
if (result.status >= 200 && result.status < 300) {
|
||
var savedFiles = (result.data && result.data.files) || [];
|
||
var errors = (result.data && result.data.errors) || [];
|
||
uploaded += savedFiles.length;
|
||
failed += Math.max(0, batch.length - savedFiles.length);
|
||
if (errors.length && !firstError) firstError = errors[0].error || '';
|
||
} else {
|
||
failed += batch.length;
|
||
firstError = firstError
|
||
|| (result.data && (result.data.error
|
||
|| (result.data.errors && result.data.errors[0] && result.data.errors[0].error)))
|
||
|| '上传失败';
|
||
}
|
||
|
||
el.uploadMeta.textContent = '已上传 ' + uploaded + ' 个,失败 ' + failed + ' 个';
|
||
el.progressBar.style.width = Math.min(Math.round(sentBytes / totalBytes * 100), 99) + '%';
|
||
}
|
||
|
||
el.progressBar.style.width = '100%';
|
||
|
||
if (uploaded > 0) {
|
||
el.uploadTitle.textContent = '上传完成';
|
||
toast('已上传 ' + uploaded + ' 个文件' + (failed ? ',' + failed + ' 个失败' : ''));
|
||
window.setTimeout(function () { window.location.reload(); }, 800);
|
||
} else {
|
||
el.uploadTitle.textContent = '上传失败';
|
||
toast(firstError || '上传失败', true);
|
||
}
|
||
} finally {
|
||
state.uploading = false;
|
||
}
|
||
}
|
||
|
||
el.uploadClose.addEventListener('click', function () {
|
||
el.uploadPanel.hidden = true;
|
||
});
|
||
|
||
/* ---------- 弹窗关闭 ---------- */
|
||
Array.prototype.forEach.call(document.querySelectorAll('[data-close-modal]'), function (button) {
|
||
button.addEventListener('click', cancelModals);
|
||
});
|
||
|
||
[el.passwordModal, el.folderModal].forEach(function (modal) {
|
||
if (!modal) return;
|
||
modal.addEventListener('click', function (event) {
|
||
if (event.target === modal) cancelModals();
|
||
});
|
||
});
|
||
|
||
document.addEventListener('keydown', function (event) {
|
||
if (event.key === 'Escape' && (!el.passwordModal.hidden || !el.folderModal.hidden)) {
|
||
cancelModals();
|
||
}
|
||
});
|
||
|
||
/* ---------- 启动 ---------- */
|
||
// 把浮层挪到 body 下,避免被 main 的层叠上下文/父级样式影响命中测试
|
||
[el.passwordModal, el.folderModal, el.uploadPanel, el.toast].forEach(function (node) {
|
||
if (node && node.parentNode !== document.body) document.body.appendChild(node);
|
||
});
|
||
|
||
setUnlocked(state.unlocked);
|
||
})();
|