Only download one file on sign cert (#2397)

This commit is contained in:
reecebrowne 2024-12-05 15:58:27 +00:00 committed by GitHub
parent cce9f74eb9
commit 526dc9f911
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,26 +1,36 @@
(function () { (function () {
if (window.isDownloadScriptInitialized) return; // Prevent re-execution
window.isDownloadScriptInitialized = true;
const { pdfPasswordPrompt, multipleInputsForSingleRequest, disableMultipleFiles, remoteCall, sessionExpired, refreshPage, error } = window.stirlingPDF; const {
pdfPasswordPrompt,
multipleInputsForSingleRequest,
disableMultipleFiles,
remoteCall,
sessionExpired,
refreshPage,
error,
} = window.stirlingPDF;
function showErrorBanner(message, stackTrace) { function showErrorBanner(message, stackTrace) {
const errorContainer = document.getElementById("errorContainer"); const errorContainer = document.getElementById('errorContainer');
errorContainer.style.display = "block"; // Display the banner errorContainer.style.display = 'block'; // Display the banner
errorContainer.querySelector(".alert-heading").textContent = error; errorContainer.querySelector('.alert-heading').textContent = error;
errorContainer.querySelector("p").textContent = message; errorContainer.querySelector('p').textContent = message;
document.querySelector("#traceContent").textContent = stackTrace; document.querySelector('#traceContent').textContent = stackTrace;
} }
function showSessionExpiredPrompt() { function showSessionExpiredPrompt() {
const errorContainer = document.getElementById("errorContainer"); const errorContainer = document.getElementById('errorContainer');
errorContainer.style.display = "block"; errorContainer.style.display = 'block';
errorContainer.querySelector(".alert-heading").textContent = sessionExpired; errorContainer.querySelector('.alert-heading').textContent = sessionExpired;
errorContainer.querySelector("p").textContent = sessionExpired; errorContainer.querySelector('p').textContent = sessionExpired;
document.querySelector("#traceContent").textContent = ""; document.querySelector('#traceContent').textContent = '';
// Optional: Add a refresh button // Optional: Add a refresh button
const refreshButton = document.createElement("button"); const refreshButton = document.createElement('button');
refreshButton.textContent = refreshPage; refreshButton.textContent = refreshPage;
refreshButton.className = "btn btn-primary mt-3"; refreshButton.className = 'btn btn-primary mt-3';
refreshButton.onclick = () => location.reload(); refreshButton.onclick = () => location.reload();
errorContainer.appendChild(refreshButton); errorContainer.appendChild(refreshButton);
} }
@ -28,19 +38,19 @@
let firstErrorOccurred = false; let firstErrorOccurred = false;
$(document).ready(function () { $(document).ready(function () {
$("form").submit(async function (event) { $('form').submit(async function (event) {
event.preventDefault(); event.preventDefault();
firstErrorOccurred = false; firstErrorOccurred = false;
const url = this.action; const url = this.action;
const files = $("#fileInput-input")[0].files; const files = $('#fileInput-input')[0].files;
const formData = new FormData(this); const formData = new FormData(this);
const submitButton = document.getElementById("submitBtn"); const submitButton = document.getElementById('submitBtn');
const showGameBtn = document.getElementById("show-game-btn"); const showGameBtn = document.getElementById('show-game-btn');
const originalButtonText = submitButton.textContent; const originalButtonText = submitButton.textContent;
var boredWaiting = localStorage.getItem("boredWaiting") || "disabled"; var boredWaiting = localStorage.getItem('boredWaiting') || 'disabled';
if (showGameBtn) { if (showGameBtn) {
showGameBtn.style.display = "none"; showGameBtn.style.display = 'none';
} }
// Remove empty file entries // Remove empty file entries
@ -49,58 +59,60 @@
formData.delete(key); formData.delete(key);
} }
} }
const override = $("#override").val() || ""; const override = $('#override').val() || '';
console.log(override); console.log(override);
// Set a timeout to show the game button if operation takes more than 5 seconds // Set a timeout to show the game button if operation takes more than 5 seconds
const timeoutId = setTimeout(() => { const timeoutId = setTimeout(() => {
if (boredWaiting === "enabled" && showGameBtn) { if (boredWaiting === 'enabled' && showGameBtn) {
showGameBtn.style.display = "block"; showGameBtn.style.display = 'block';
showGameBtn.parentNode.insertBefore(document.createElement('br'), showGameBtn.nextSibling); showGameBtn.parentNode.insertBefore(document.createElement('br'), showGameBtn.nextSibling);
} }
}, 5000); }, 5000);
try { try {
submitButton.textContent = "Processing..."; submitButton.textContent = 'Processing...';
submitButton.disabled = true; submitButton.disabled = true;
if (remoteCall === true) { if (remoteCall === true) {
if (override === "multi" || (!multipleInputsForSingleRequest && files.length > 1 && override !== "single")) { if (override === 'multi' || (!multipleInputsForSingleRequest && files.length > 1 && override !== 'single')) {
await submitMultiPdfForm(url, files); await submitMultiPdfForm(url, files);
} else { } else {
await handleSingleDownload(url, formData); await handleSingleDownload(url, formData);
} }
} }
clearFileInput(); clearFileInput();
clearTimeout(timeoutId); clearTimeout(timeoutId);
if (showGameBtn) { if (showGameBtn) {
showGameBtn.style.display = "none"; showGameBtn.style.display = 'none';
showGameBtn.style.marginTop = ""; showGameBtn.style.marginTop = '';
} }
submitButton.textContent = originalButtonText; submitButton.textContent = originalButtonText;
submitButton.disabled = false; submitButton.disabled = false;
// After process finishes, check for boredWaiting and gameDialog open status // After process finishes, check for boredWaiting and gameDialog open status
const gameDialog = document.getElementById('game-container-wrapper'); const gameDialog = document.getElementById('game-container-wrapper');
if (boredWaiting === "enabled" && gameDialog && gameDialog.open) { if (boredWaiting === 'enabled' && gameDialog && gameDialog.open) {
// Display a green banner at the bottom of the screen saying "Download complete" // Display a green banner at the bottom of the screen saying "Download complete"
let downloadCompleteText = "Download Complete"; let downloadCompleteText = 'Download Complete';
if (window.downloadCompleteText) { if (window.downloadCompleteText) {
downloadCompleteText = window.downloadCompleteText; downloadCompleteText = window.downloadCompleteText;
} }
$("body").append('<div id="download-complete-banner" style="position:fixed;bottom:0;left:0;width:100%;background-color:green;color:white;text-align:center;padding:10px;font-size:16px;z-index:1000;">'+ downloadCompleteText + '</div>'); $('body').append(
'<div id="download-complete-banner" style="position:fixed;bottom:0;left:0;width:100%;background-color:green;color:white;text-align:center;padding:10px;font-size:16px;z-index:1000;">' +
downloadCompleteText +
'</div>'
);
setTimeout(function () { setTimeout(function () {
$("#download-complete-banner").fadeOut("slow", function() { $('#download-complete-banner').fadeOut('slow', function () {
$(this).remove(); // Remove the banner after fading out $(this).remove(); // Remove the banner after fading out
}); });
}, 5000); // Banner will fade out after 5 seconds }, 5000); // Banner will fade out after 5 seconds
} }
} catch (error) { } catch (error) {
clearTimeout(timeoutId); clearTimeout(timeoutId);
showGameBtn.style.display = "none"; showGameBtn.style.display = 'none';
submitButton.textContent = originalButtonText; submitButton.textContent = originalButtonText;
submitButton.disabled = false; submitButton.disabled = false;
handleDownloadError(error); handleDownloadError(error);
@ -112,7 +124,7 @@
async function getPDFPageCount(file) { async function getPDFPageCount(file) {
try { try {
const arrayBuffer = await file.arrayBuffer(); const arrayBuffer = await file.arrayBuffer();
pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdfjs-legacy/pdf.worker.mjs' pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdfjs-legacy/pdf.worker.mjs';
const pdf = await pdfjsLib.getDocument({data: arrayBuffer}).promise; const pdf = await pdfjsLib.getDocument({data: arrayBuffer}).promise;
return pdf.numPages; return pdf.numPages;
} catch (error) { } catch (error) {
@ -128,8 +140,8 @@
let errorMessage = null; let errorMessage = null;
try { try {
const response = await fetch(url, { method: "POST", body: formData }); const response = await fetch(url, {method: 'POST', body: formData});
const contentType = response.headers.get("content-type"); const contentType = response.headers.get('content-type');
if (!response.ok) { if (!response.ok) {
errorMessage = response.status; errorMessage = response.status;
@ -137,31 +149,30 @@
showSessionExpiredPrompt(); showSessionExpiredPrompt();
return; return;
} }
if (contentType && contentType.includes("application/json")) { if (contentType && contentType.includes('application/json')) {
console.error("Throwing error banner, response was not okay"); console.error('Throwing error banner, response was not okay');
return handleJsonResponse(response); return handleJsonResponse(response);
} }
throw new Error(`HTTP error! status: ${response.status}`); throw new Error(`HTTP error! status: ${response.status}`);
} }
const contentDisposition = response.headers.get("Content-Disposition"); const contentDisposition = response.headers.get('Content-Disposition');
let filename = getFilenameFromContentDisposition(contentDisposition); let filename = getFilenameFromContentDisposition(contentDisposition);
const blob = await response.blob(); const blob = await response.blob();
success = true; success = true;
if (contentType.includes("application/pdf") || contentType.includes("image/")) { if (contentType.includes('application/pdf') || contentType.includes('image/')) {
clearFileInput(); clearFileInput();
return handleResponse(blob, filename, !isMulti, isZip); return handleResponse(blob, filename, !isMulti, isZip);
} else { } else {
clearFileInput(); clearFileInput();
return handleResponse(blob, filename, false, isZip); return handleResponse(blob, filename, false, isZip);
} }
} catch (error) { } catch (error) {
success = false; success = false;
errorMessage = error.message; errorMessage = error.message;
console.error("Error in handleSingleDownload:", error); console.error('Error in handleSingleDownload:', error);
throw error; throw error;
} finally { } finally {
const processingTime = performance.now() - startTime; const processingTime = performance.now() - startTime;
@ -175,7 +186,7 @@
file_size: file ? file.size : 0, file_size: file ? file.size : 0,
processing_time: processingTime, processing_time: processingTime,
error_message: errorMessage, error_message: errorMessage,
pdf_pages: pageCount pdf_pages: pageCount,
}); });
} }
} }
@ -184,11 +195,11 @@
function getFilenameFromContentDisposition(contentDisposition) { function getFilenameFromContentDisposition(contentDisposition) {
let filename; let filename;
if (contentDisposition && contentDisposition.indexOf("attachment") !== -1) { if (contentDisposition && contentDisposition.indexOf('attachment') !== -1) {
filename = decodeURIComponent(contentDisposition.split("filename=")[1].replace(/"/g, "")).trim(); filename = decodeURIComponent(contentDisposition.split('filename=')[1].replace(/"/g, '')).trim();
} else { } else {
// If the Content-Disposition header is not present or does not contain the filename, use a default filename // If the Content-Disposition header is not present or does not contain the filename, use a default filename
filename = "download"; filename = 'download';
} }
return filename; return filename;
@ -198,30 +209,30 @@
const json = await response.json(); const json = await response.json();
const errorMessage = JSON.stringify(json, null, 2); const errorMessage = JSON.stringify(json, null, 2);
if ( if (
errorMessage.toLowerCase().includes("the password is incorrect") || errorMessage.toLowerCase().includes('the password is incorrect') ||
errorMessage.toLowerCase().includes("Password is not provided") || errorMessage.toLowerCase().includes('Password is not provided') ||
errorMessage.toLowerCase().includes("PDF contains an encryption dictionary") errorMessage.toLowerCase().includes('PDF contains an encryption dictionary')
) { ) {
if (!firstErrorOccurred) { if (!firstErrorOccurred) {
firstErrorOccurred = true; firstErrorOccurred = true;
alert(pdfPasswordPrompt); alert(pdfPasswordPrompt);
} }
} else { } else {
showErrorBanner(json.error + ":" + json.message, json.trace); showErrorBanner(json.error + ':' + json.message, json.trace);
} }
} }
async function handleResponse(blob, filename, considerViewOptions = false, isZip = false) { async function handleResponse(blob, filename, considerViewOptions = false, isZip = false) {
if (!blob) return; if (!blob) return;
const downloadOption = localStorage.getItem("downloadOption"); const downloadOption = localStorage.getItem('downloadOption');
if (considerViewOptions) { if (considerViewOptions) {
if (downloadOption === "sameWindow") { if (downloadOption === 'sameWindow') {
const url = URL.createObjectURL(blob); const url = URL.createObjectURL(blob);
window.location.href = url; window.location.href = url;
return; return;
} else if (downloadOption === "newWindow") { } else if (downloadOption === 'newWindow') {
const url = URL.createObjectURL(blob); const url = URL.createObjectURL(blob);
window.open(url, "_blank"); window.open(url, '_blank');
return; return;
} }
} }
@ -240,11 +251,11 @@
function downloadFile(blob, filename) { function downloadFile(blob, filename) {
if (!(blob instanceof Blob)) { if (!(blob instanceof Blob)) {
console.error("Invalid blob passed to downloadFile function"); console.error('Invalid blob passed to downloadFile function');
return; return;
} }
const url = URL.createObjectURL(blob); const url = URL.createObjectURL(blob);
const a = document.createElement("a"); const a = document.createElement('a');
a.href = url; a.href = url;
a.download = filename; a.download = filename;
a.click(); a.click();
@ -254,18 +265,18 @@
} }
async function submitMultiPdfForm(url, files) { async function submitMultiPdfForm(url, files) {
const zipThreshold = parseInt(localStorage.getItem("zipThreshold"), 10) || 4; const zipThreshold = parseInt(localStorage.getItem('zipThreshold'), 10) || 4;
const zipFiles = files.length > zipThreshold; const zipFiles = files.length > zipThreshold;
let jszip = null; let jszip = null;
// Add Space below Progress Bar before Showing // Add Space below Progress Bar before Showing
$('.progressBarContainer').after($('<br>')); $('.progressBarContainer').after($('<br>'));
$(".progressBarContainer").show(); $('.progressBarContainer').show();
// Initialize the progress bar // Initialize the progress bar
let progressBar = $(".progressBar"); let progressBar = $('.progressBar');
progressBar.css("width", "0%"); progressBar.css('width', '0%');
progressBar.attr("aria-valuenow", 0); progressBar.attr('aria-valuenow', 0);
progressBar.attr("aria-valuemax", files.length); progressBar.attr('aria-valuemax', files.length);
if (zipFiles) { if (zipFiles) {
jszip = new JSZip(); jszip = new JSZip();
@ -279,10 +290,10 @@
if (postForm) { if (postForm) {
formData = new FormData($(postForm)[0]); // Convert the form to a jQuery object and get the raw DOM element formData = new FormData($(postForm)[0]); // Convert the form to a jQuery object and get the raw DOM element
} else { } else {
console.log("No form with POST method found."); console.log('No form with POST method found.');
} }
//Remove file to reuse parameters for other runs //Remove file to reuse parameters for other runs
formData.delete("fileInput"); formData.delete('fileInput');
// Remove empty file entries // Remove empty file entries
for (let [key, value] of formData.entries()) { for (let [key, value] of formData.entries()) {
if (value instanceof File && !value.name) { if (value instanceof File && !value.name) {
@ -298,12 +309,12 @@
for (const chunk of chunks) { for (const chunk of chunks) {
const promises = chunk.map(async (file) => { const promises = chunk.map(async (file) => {
let fileFormData = new FormData(); let fileFormData = new FormData();
fileFormData.append("fileInput", file); fileFormData.append('fileInput', file);
console.log(fileFormData); console.log(fileFormData);
// Add other form data // Add other form data
for (let pair of formData.entries()) { for (let pair of formData.entries()) {
fileFormData.append(pair[0], pair[1]); fileFormData.append(pair[0], pair[1]);
console.log(pair[0] + ", " + pair[1]); console.log(pair[0] + ', ' + pair[1]);
} }
try { try {
@ -325,22 +336,22 @@
if (zipFiles) { if (zipFiles) {
try { try {
const content = await jszip.generateAsync({ type: "blob" }); const content = await jszip.generateAsync({type: 'blob'});
downloadFile(content, "files.zip"); downloadFile(content, 'files.zip');
} catch (error) { } catch (error) {
console.error("Error generating ZIP file: " + error); console.error('Error generating ZIP file: ' + error);
} }
} }
progressBar.css("width", "100%"); progressBar.css('width', '100%');
progressBar.attr("aria-valuenow", Array.from(files).length); progressBar.attr('aria-valuenow', Array.from(files).length);
} }
function updateProgressBar(progressBar, files) { function updateProgressBar(progressBar, files) {
let progress = (progressBar.attr("aria-valuenow") / files.length) * 100 + 100 / files.length; let progress = (progressBar.attr('aria-valuenow') / files.length) * 100 + 100 / files.length;
progressBar.css("width", progress + "%"); progressBar.css('width', progress + '%');
progressBar.attr("aria-valuenow", parseInt(progressBar.attr("aria-valuenow")) + 1); progressBar.attr('aria-valuenow', parseInt(progressBar.attr('aria-valuenow')) + 1);
} }
window.addEventListener("unload", () => { window.addEventListener('unload', () => {
for (const url of urls) { for (const url of urls) {
URL.revokeObjectURL(url); URL.revokeObjectURL(url);
} }
@ -349,15 +360,15 @@
// Clear file input after job // Clear file input after job
function clearFileInput() { function clearFileInput() {
let pathname = document.location.pathname; let pathname = document.location.pathname;
if(pathname != "/merge-pdfs"){ if (pathname != '/merge-pdfs') {
let formElement = document.querySelector("#fileInput-input"); let formElement = document.querySelector('#fileInput-input');
formElement.value = ''; formElement.value = '';
let editSectionElement = document.querySelector("#editSection"); let editSectionElement = document.querySelector('#editSection');
if (editSectionElement) { if (editSectionElement) {
editSectionElement.style.display = "none"; editSectionElement.style.display = 'none';
} }
let cropPdfCanvas = document.querySelector("#cropPdfCanvas"); let cropPdfCanvas = document.querySelector('#cropPdfCanvas');
let overlayCanvas = document.querySelector("#overlayCanvas"); let overlayCanvas = document.querySelector('#overlayCanvas');
if (cropPdfCanvas && overlayCanvas) { if (cropPdfCanvas && overlayCanvas) {
cropPdfCanvas.width = 0; cropPdfCanvas.width = 0;
cropPdfCanvas.height = 0; cropPdfCanvas.height = 0;