feat: докачиваемая загрузка файлов до 3 ГБ (tus 1.0.0)

Бэкенд (tus_upload.py): самодостаточное ядро tus — потоковая запись
кусков на диск (память не растёт), докачка с серверного offset,
изоляция по владельцу, перенос готового файла в work_dir как у legacy
/api/upload, лимит 3 ГБ + guard по свободному диску, авто-чистка
брошенных загрузок старше суток.

Фронт: tus-js-client (с SRI) — прогресс, авто-ретраи, обновление
токена перед истечением, докачка после обрыва/перезагрузки; мягкий
fallback на /api/upload если CDN недоступен.

Аудит: tus-куски не логируются по PATCH, только финализация (action=upload).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-06-02 15:43:56 +10:00
co-authored by Claude Opus 4.8
parent ac17dec3ce
commit 522b157acc
3 changed files with 290 additions and 10 deletions
+77 -9
View File
@@ -154,6 +154,7 @@ body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Robo
</div>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/tus-js-client@4.3.1/dist/tus.min.js" integrity="sha384-UlHjK3F7TCQCEUpnoa1ohMbP2oaWB3Aypv4gMo511vaZ86uUZ0Zv7UzZ0J1zRUT1" crossorigin="anonymous"></script>
<script>
// Configure marked for safe rendering
if (typeof marked !== 'undefined') {
@@ -356,20 +357,87 @@ function renderFileList() {
}
function removeFile(i) { pendingFiles.splice(i, 1); renderFileList(); }
// Access token (24h) can expire mid-upload of a multi-GB file; refresh just
// before it lapses so long uploads don't 401 halfway through.
function jwtExpSoon() {
try {
const p = JSON.parse(atob(token.split('.')[1]));
return (p.exp * 1000) < (Date.now() + 120000);
} catch { return false; }
}
// Resumable upload of one file via the tus protocol. Survives network drops and
// page reloads (tus-js-client stores the upload URL and resumes from the offset
// the server already has). Resolves {name, ok, status}.
function uploadOne(file, onPct) {
return new Promise((resolve) => {
const upload = new tus.Upload(file, {
endpoint: API + '/api/tus',
chunkSize: 32 * 1024 * 1024,
retryDelays: [0, 3000, 5000, 10000, 20000],
removeFingerprintOnSuccess: true,
metadata: { filename: file.name, tab_id: tabId },
async onBeforeRequest(req) {
if (jwtExpSoon()) await tryRefreshToken();
req.setHeader('Authorization', 'Bearer ' + token);
req.setHeader('X-Tab-Id', tabId);
},
onShouldRetry(err) {
const s = err.originalResponse ? err.originalResponse.getStatus() : 0;
if (s === 401) return !!localStorage.getItem('refresh_token');
return s === 0 || s === 429 || s >= 500;
},
onProgress(sent, total) { onPct(Math.floor(sent / total * 100)); },
onSuccess() { resolve({ name: file.name, ok: true }); },
onError(error) {
const s = error.originalResponse ? error.originalResponse.getStatus() : 0;
if (s === 401) logout();
resolve({ name: file.name, ok: false, status: s });
},
});
upload.findPreviousUploads().then((prev) => {
if (prev.length) upload.resumeFromPreviousUpload(prev[0]);
upload.start();
});
});
}
async function uploadFiles() {
if (typeof tus === 'undefined') return uploadFilesLegacy(); // CDN blocked → degrade
const files = pendingFiles.slice();
const prog = files.map(f => ({ name: f.name, pct: 0 }));
const fl = document.getElementById('file-list');
const render = () => {
fl.innerHTML = '';
prog.forEach(p => {
const b = document.createElement('span');
b.className = 'file-badge';
b.textContent = `${p.name} — ${p.pct}%`;
fl.appendChild(b);
});
};
render();
const results = [];
for (let i = 0; i < files.length; i++) {
results.push(await uploadOne(files[i], (pct) => { prog[i].pct = pct; render(); }));
}
pendingFiles = [];
renderFileList();
const failed = results.filter(r => !r.ok);
if (failed.length && !failed.some(r => r.status === 401)) {
addMsg('error', 'Не загружены: ' + failed.map(r => r.name).join(', '));
}
return results.filter(r => r.ok).map(r => r.name);
}
// Fallback for when the tus client isn't available (e.g. CDN unreachable).
async function uploadFilesLegacy() {
const uploaded = [];
for (const f of pendingFiles) {
const fd = new FormData();
fd.append('file', f);
const r = await fetch(API + '/api/upload', {
method: 'POST',
headers: authHeaders(),
body: fd,
});
if (r.ok) {
const data = await r.json();
uploaded.push(data.filename);
}
const r = await authFetch(API + '/api/upload', { method: 'POST', body: fd });
if (r.ok) uploaded.push((await r.json()).filename);
}
pendingFiles = [];
renderFileList();