314 lines
13 KiB
HTML
314 lines
13 KiB
HTML
{% extends 'admin/custom_base.html' %}
|
|
{% block body %}
|
|
<div class="container-fluid mt-3">
|
|
<h4 class="mb-3">Downloads</h4>
|
|
|
|
<div class="card mb-4">
|
|
<div class="card-header bg-primary text-white"><strong>+ Upload New Build</strong></div>
|
|
<div class="card-body">
|
|
<div class="form-row align-items-end">
|
|
<div class="form-group col-md-4 mb-2">
|
|
<label class="small font-weight-bold">Build Name <span class="text-danger">*</span></label>
|
|
<input type="text" class="form-control" id="up-name" placeholder="e.g. KittyRec-Client-v1.2">
|
|
</div>
|
|
<div class="form-group col-md-5 mb-2">
|
|
<label class="small font-weight-bold">ZIP File <span class="text-danger">*</span></label>
|
|
<div class="custom-file">
|
|
<input type="file" class="custom-file-input" id="up-file" accept=".zip"
|
|
onchange="document.getElementById('up-file-label').textContent = this.files[0]?.name || 'Choose .zip file'">
|
|
<label class="custom-file-label" id="up-file-label">Choose .zip file</label>
|
|
</div>
|
|
</div>
|
|
<div class="form-group col-md-3 mb-2">
|
|
<label class="small font-weight-bold"> </label>
|
|
<button class="btn btn-success btn-block d-block" onclick="doUpload()">Upload Build</button>
|
|
</div>
|
|
</div>
|
|
<div id="up-progress-wrap" class="mt-2" style="display:none">
|
|
<div class="progress mb-1" style="height:12px">
|
|
<div class="progress-bar bg-success progress-bar-striped progress-bar-animated" id="up-bar" style="width:0%"></div>
|
|
</div>
|
|
<small class="text-muted" id="up-label">0%</small>
|
|
</div>
|
|
<div id="up-result" class="mt-2"></div>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="card">
|
|
<div class="card-header d-flex align-items-center justify-content-between">
|
|
<strong>All Builds</strong>
|
|
<small class="text-muted">
|
|
Current: <span id="current-label" class="font-weight-bold text-success">None set</span>
|
|
· Permanent URL: <a href="/download/current" target="_blank">/download/current</a>
|
|
</small>
|
|
</div>
|
|
<div class="card-body p-0">
|
|
<table class="table table-sm table-hover mb-0">
|
|
<thead class="thead-dark">
|
|
<tr>
|
|
<th>Build Name</th>
|
|
<th>Date</th>
|
|
<th>Size</th>
|
|
<th>DLs</th>
|
|
<th>Uploaded By</th>
|
|
<th>Status</th>
|
|
<th>Actions</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody id="builds-tbody">
|
|
<tr><td colspan="7" class="text-center text-muted py-4">Loading…</td></tr>
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="url-modal" class="modal fade" tabindex="-1">
|
|
<div class="modal-dialog">
|
|
<div class="modal-content">
|
|
<div class="modal-header">
|
|
<h5 class="modal-title">Share URL</h5>
|
|
<button type="button" class="close" data-dismiss="modal">×</button>
|
|
</div>
|
|
<div class="modal-body">
|
|
<p class="text-muted small mb-2">Anyone with this link can download. Keep it private.</p>
|
|
<div class="input-group">
|
|
<input type="text" class="form-control" id="modal-url" readonly onclick="this.select()">
|
|
<div class="input-group-append">
|
|
<button class="btn btn-outline-secondary" onclick="copyUrl()">Copy</button>
|
|
</div>
|
|
</div>
|
|
<small class="text-success mt-1 d-none" id="modal-copied">Copied!</small>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<script>
|
|
function fmtSize(b) {
|
|
if (!b) return '—';
|
|
if (b >= 1073741824) return (b/1073741824).toFixed(2)+' GB';
|
|
if (b >= 1048576) return (b/1048576).toFixed(2)+' MB';
|
|
return (b/1024).toFixed(1)+' KB';
|
|
}
|
|
function esc(s) { return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); }
|
|
function escA(s) { return String(s).replace(/'/g,"'").replace(/"/g,'"'); }
|
|
function buildUrl(b) {
|
|
return location.origin + '/download/' + b.date + '/' + encodeURIComponent(b.build_name) + '/' + b.h1 + '/' + b.h2 + '/' + b.h3;
|
|
}
|
|
|
|
async function loadBuilds() {
|
|
try {
|
|
const r = await fetch('/admin/api/downloads/list');
|
|
const data = await r.json();
|
|
const builds = data.builds || [];
|
|
const currentId = data.current_build_id;
|
|
const cur = builds.find(b => b.id === currentId);
|
|
document.getElementById('current-label').textContent = cur ? cur.build_name : 'None set';
|
|
const tbody = document.getElementById('builds-tbody');
|
|
if (!builds.length) {
|
|
tbody.innerHTML = '<tr><td colspan="7" class="text-center text-muted py-4">No builds yet. Upload one above.</td></tr>';
|
|
return;
|
|
}
|
|
tbody.innerHTML = builds.map(b => {
|
|
const isCurrent = b.id === currentId;
|
|
return `<tr>
|
|
<td>
|
|
<strong>${esc(b.build_name)}</strong>
|
|
${isCurrent ? '<span class="badge badge-success ml-1">Current</span>' : ''}
|
|
<br><small class="text-muted">${b.sha256.slice(0,12)}…</small>
|
|
</td>
|
|
<td>${b.date}</td>
|
|
<td>${fmtSize(b.size)}</td>
|
|
<td>${b.download_count || 0}</td>
|
|
<td>${esc(b.uploaded_by||'—')}</td>
|
|
<td><span class="badge ${b.enabled?'badge-success':'badge-secondary'}">${b.enabled?'Active':'Disabled'}</span></td>
|
|
<td style="white-space:nowrap">
|
|
<button class="btn btn-xs btn-outline-info mr-1" onclick="showUrl('${escA(buildUrl(b))}')">URL</button>
|
|
<button class="btn btn-xs ${isCurrent?'btn-success':'btn-outline-secondary'} mr-1" onclick="setCurrent('${b.id}')">${isCurrent?'Current':'Set Current'}</button>
|
|
<button class="btn btn-xs btn-outline-secondary mr-1" onclick="toggleBuild('${b.id}')">${b.enabled?'Disable':'Enable'}</button>
|
|
<button class="btn btn-xs btn-outline-warning mr-1" onclick="renameBuild('${b.id}','${escA(b.build_name)}')">Rename</button>
|
|
<button class="btn btn-xs btn-outline-danger" onclick="deleteBuild('${b.id}','${escA(b.build_name)}')">Delete</button>
|
|
</td>
|
|
</tr>`;
|
|
}).join('');
|
|
} catch(e) {
|
|
document.getElementById('builds-tbody').innerHTML = '<tr><td colspan="7" class="text-danger text-center py-3">Failed to load builds.</td></tr>';
|
|
}
|
|
}
|
|
|
|
async function setCurrent(id) {
|
|
const r = await fetch('/admin/api/downloads/set_current/'+id, {method:'POST'});
|
|
const d = await r.json();
|
|
if (d.ok) loadBuilds();
|
|
else KR.toast(d.error || 'Failed', 'error');
|
|
}
|
|
async function toggleBuild(id) {
|
|
const r = await fetch('/admin/api/downloads/toggle/'+id, {method:'POST'});
|
|
const d = await r.json();
|
|
if (d.ok) loadBuilds();
|
|
else KR.toast(d.error || 'Toggle failed', 'error');
|
|
}
|
|
async function renameBuild(id, currentName) {
|
|
const newName = prompt('New build name:', currentName);
|
|
if (!newName || !newName.trim() || newName.trim() === currentName) return;
|
|
const r = await fetch('/admin/api/downloads/rename/'+id, {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({build_name: newName.trim()})});
|
|
const d = await r.json();
|
|
if (d.ok) loadBuilds();
|
|
else KR.toast(d.error || 'Rename failed', 'error');
|
|
}
|
|
async function deleteBuild(id, name) {
|
|
if (!confirm('Delete "'+name+'"? Cannot be undone.')) return;
|
|
const r = await fetch('/admin/api/downloads/delete/'+id, {method:'POST'});
|
|
const d = await r.json();
|
|
if (d.ok) { KR.toast('Build deleted'); loadBuilds(); }
|
|
else KR.toast(d.error || 'Delete failed', 'error');
|
|
}
|
|
function showUrl(url) {
|
|
document.getElementById('modal-url').value = url;
|
|
document.getElementById('modal-copied').classList.add('d-none');
|
|
$('#url-modal').modal('show');
|
|
}
|
|
function copyUrl() {
|
|
const el = document.getElementById('modal-url');
|
|
el.select();
|
|
navigator.clipboard.writeText(el.value).catch(()=>document.execCommand('copy'));
|
|
const c = document.getElementById('modal-copied');
|
|
c.classList.remove('d-none');
|
|
setTimeout(()=>c.classList.add('d-none'), 2000);
|
|
}
|
|
const CHUNK_SIZE = 8 * 1024 * 1024;
|
|
const CONCURRENCY = 4;
|
|
const MAX_RETRIES = 3;
|
|
let _uploading = false;
|
|
|
|
function doUpload() {
|
|
if (_uploading) return;
|
|
const name = document.getElementById('up-name').value.trim();
|
|
const fileEl = document.getElementById('up-file');
|
|
if (!name) { KR.toast('Enter a build name.', 'error'); return; }
|
|
if (!fileEl.files[0]) { KR.toast('Select a .zip file.', 'error'); return; }
|
|
const file = fileEl.files[0];
|
|
const totalChunks = Math.ceil(file.size / CHUNK_SIZE);
|
|
const wrap = document.getElementById('up-progress-wrap');
|
|
const bar = document.getElementById('up-bar');
|
|
const label = document.getElementById('up-label');
|
|
const result = document.getElementById('up-result');
|
|
const btn = document.querySelector('[onclick="doUpload()"]');
|
|
wrap.style.display = '';
|
|
result.innerHTML = '';
|
|
bar.style.width = '0%';
|
|
btn.disabled = true;
|
|
_uploading = true;
|
|
|
|
const bytesUploaded = new Array(totalChunks).fill(0);
|
|
const startTime = Date.now();
|
|
|
|
function updateProgress() {
|
|
const sent = bytesUploaded.reduce((a, b) => a + b, 0);
|
|
const pct = (sent / file.size * 100).toFixed(1);
|
|
const elapsed = (Date.now() - startTime) / 1000;
|
|
const speed = elapsed > 0.5 ? fmtSize(sent / elapsed) + '/s' : '';
|
|
bar.style.width = pct + '%';
|
|
label.textContent = pct + '% — ' + fmtSize(sent) + ' / ' + fmtSize(file.size) + (speed ? ' · ' + speed : '');
|
|
}
|
|
|
|
function xhrPost(url, body) {
|
|
return new Promise((resolve, reject) => {
|
|
const xhr = new XMLHttpRequest();
|
|
xhr.open('POST', url);
|
|
xhr.onload = () => {
|
|
try { resolve(JSON.parse(xhr.responseText)); }
|
|
catch(e) { reject(new Error('Bad response (' + xhr.status + '): ' + xhr.responseText.slice(0, 200))); }
|
|
};
|
|
xhr.onerror = () => reject(new Error('Network error'));
|
|
xhr.send(body);
|
|
});
|
|
}
|
|
|
|
async function uploadChunk(sessionId, i, attempt) {
|
|
attempt = attempt || 0;
|
|
const start = i * CHUNK_SIZE;
|
|
const slice = file.slice(start, start + CHUNK_SIZE);
|
|
const chunkSize = slice.size;
|
|
return new Promise((resolve, reject) => {
|
|
const xhr = new XMLHttpRequest();
|
|
xhr.open('POST', '/admin/api/downloads/upload/chunk');
|
|
xhr.upload.onprogress = e => {
|
|
bytesUploaded[i] = e.loaded;
|
|
updateProgress();
|
|
};
|
|
xhr.onload = () => {
|
|
try {
|
|
const d = JSON.parse(xhr.responseText);
|
|
if (d.ok) { bytesUploaded[i] = chunkSize; updateProgress(); resolve(); }
|
|
else reject(new Error('Chunk ' + i + ': ' + (d.error || 'failed')));
|
|
} catch(e) { reject(new Error('Chunk ' + i + ' bad response')); }
|
|
};
|
|
xhr.onerror = () => reject(new Error('Chunk ' + i + ' network error'));
|
|
const fd = new FormData();
|
|
fd.append('session_id', sessionId);
|
|
fd.append('chunk_index', i);
|
|
fd.append('chunk', slice, 'chunk');
|
|
xhr.send(fd);
|
|
}).catch(async err => {
|
|
if (attempt < MAX_RETRIES) {
|
|
await new Promise(r => setTimeout(r, 500 * (attempt + 1)));
|
|
return uploadChunk(sessionId, i, attempt + 1);
|
|
}
|
|
throw err;
|
|
});
|
|
}
|
|
|
|
async function runPool(sessionId) {
|
|
let next = 0;
|
|
async function worker() {
|
|
while (next < totalChunks) {
|
|
const i = next++;
|
|
await uploadChunk(sessionId, i);
|
|
}
|
|
}
|
|
await Promise.all(Array.from({length: Math.min(CONCURRENCY, totalChunks)}, () => worker()));
|
|
}
|
|
|
|
async function run() {
|
|
label.textContent = 'Starting…';
|
|
const startResp = await xhrPost('/admin/api/downloads/upload/start', JSON.stringify({build_name: name}));
|
|
if (!startResp.ok) throw new Error(startResp.error || 'Failed to start session');
|
|
await runPool(startResp.session_id);
|
|
label.textContent = 'Finalizing… hashing…';
|
|
bar.classList.add('progress-bar-animated');
|
|
const final = await xhrPost('/admin/api/downloads/upload/finalize', JSON.stringify({session_id: startResp.session_id, total_chunks: totalChunks}));
|
|
if (!final.ok) throw new Error(final.error || 'Finalize failed');
|
|
return final;
|
|
}
|
|
|
|
run().then(d => {
|
|
const url = location.origin + d.url;
|
|
wrap.style.display = 'none';
|
|
result.innerHTML = `<div class="alert alert-success p-2">
|
|
<strong>Upload complete!</strong> Share this URL:<br>
|
|
<div class="input-group mt-1">
|
|
<input type="text" class="form-control form-control-sm" value="${escA(url)}" readonly onclick="this.select()">
|
|
<div class="input-group-append">
|
|
<button class="btn btn-sm btn-outline-success" onclick="navigator.clipboard.writeText('${escA(url)}')">Copy</button>
|
|
</div>
|
|
</div>
|
|
</div>`;
|
|
loadBuilds();
|
|
document.getElementById('up-name').value = '';
|
|
fileEl.value = '';
|
|
document.getElementById('up-file-label').textContent = 'Choose .zip file';
|
|
}).catch(err => {
|
|
wrap.style.display = 'none';
|
|
result.innerHTML = '<div class="alert alert-danger p-2"><strong>Upload failed:</strong> ' + esc(err.message) + '</div>';
|
|
}).finally(() => {
|
|
btn.disabled = false;
|
|
_uploading = false;
|
|
bar.classList.remove('progress-bar-animated');
|
|
});
|
|
}
|
|
loadBuilds();
|
|
</script>
|
|
{% endblock %}
|
|
|