CyberStrikeAI/web/static/js/vulnerability-download.js

62 lines
3.2 KiB
JavaScript

let vulnerabilityDownloadID = null;
let vulnerabilityDownloadBusy = false;
let vulnerabilityDownloadButton = null;
function openVulnerabilityDownload(id, event) {
if (event) event.stopPropagation();
if (vulnerabilityDownloadBusy) return;
vulnerabilityDownloadID = id;
vulnerabilityDownloadButton = event?.target?.closest('button') || null;
document.getElementById('vulnerability-download-message').textContent = '';
document.getElementById('vulnerability-download-dialog').showModal();
}
function closeVulnerabilityDownload() {
if (vulnerabilityDownloadBusy) return;
document.getElementById('vulnerability-download-dialog').close();
vulnerabilityDownloadID = null;
}
async function downloadSelectedVulnerability(format) {
if (!vulnerabilityDownloadID || vulnerabilityDownloadBusy || !['md', 'docx'].includes(format)) return;
vulnerabilityDownloadBusy = true;
const dialog = document.getElementById('vulnerability-download-dialog');
const message = document.getElementById('vulnerability-download-message');
dialog.querySelectorAll('button').forEach(button => { button.disabled = true; });
message.textContent = vulnT('vulnerabilityDownload.busy');
try {
if (format === 'md') {
// Preserve the existing localized Markdown content and filename.
const ok = await downloadVulnerabilityAsMarkdown(vulnerabilityDownloadID, { target: vulnerabilityDownloadButton });
if (!ok) { message.textContent = ''; return; }
} else {
const response = await apiFetch(`/api/vulnerabilities/${encodeURIComponent(vulnerabilityDownloadID)}/download?format=docx`);
if (!response.ok) {
const body = await response.json().catch(() => ({}));
throw new Error(body.error || vulnT('vulnerabilityPage.downloadFailed'));
}
const disposition = response.headers.get('Content-Disposition') || '';
const encodedName = disposition.match(/filename\*=utf-8''([^;]+)/i);
let filename = `vulnerability-${vulnerabilityDownloadID}.docx`;
if (encodedName) filename = decodeURIComponent(encodedName[1]);
else {
const plainName = disposition.match(/filename="([^"]+)"|filename=([^;]+)/i);
if (plainName) filename = plainName[1] || plainName[2];
}
const url = URL.createObjectURL(await response.blob());
const link = document.createElement('a');
link.href = url; link.download = filename;
document.body.appendChild(link); link.click(); link.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
dialog.close();
vulnerabilityDownloadID = null;
} catch (error) {
message.textContent = vulnT('vulnerabilityPage.downloadFailed') + ': ' + error.message;
} finally {
vulnerabilityDownloadBusy = false;
dialog.querySelectorAll('button').forEach(button => { button.disabled = false; });
}
}
document.getElementById('vulnerability-download-dialog').addEventListener('cancel', event => {
if (vulnerabilityDownloadBusy) event.preventDefault();
else vulnerabilityDownloadID = null;
});