const POLL_INTERVAL = 5000; // 5 seconds document.addEventListener('DOMContentLoaded', function() { console.log('DOM fully loaded and parsed'); loadJobHistory(); document.getElementById('uploadForm').addEventListener('submit', handleFormSubmit); document.getElementById('bulkDownload').addEventListener('click', bulkDownload); document.querySelector('input[type="file"]').addEventListener('change', updateSelectedFiles); addSelectAllButton(); // Initialize dark mode initDarkMode(); console.log('Microsoft Translator Document Translation initialized'); }); function handleFormSubmit(e) { e.preventDefault(); console.log('Form submitted'); const formData = new FormData(this); const files = formData.getAll('documents[]'); const targetLang = formData.get('target_lang'); console.log(`Number of files selected: ${files.length}`); files.forEach((file, index) => { console.log(`Processing file ${index + 1}: ${file.name}`); const individualFormData = new FormData(); individualFormData.append('file', file); individualFormData.append('source_lang', formData.get('source_lang')); individualFormData.append('target_lang', targetLang); individualFormData.append('formality', formData.get('formality')); uploadFile(individualFormData); }); } function uploadFile(formData) { console.log(`Uploading file: ${formData.get('file').name}`); const endpoint = 'process.php'; console.log(`Using endpoint: ${endpoint}`); fetch(endpoint, { method: 'POST', body: formData }) .then(response => response.json()) .then(data => { console.log(`Response from ${endpoint}:`, data); if (data.document_id && data.document_key) { console.log(`Document ID received: ${data.document_id}, Document Key: ${data.document_key}`); addJobToList(data.document_id, formData.get('file').name); pollJobStatus(data.document_id, data.document_key); addToJobHistory(data.document_id, formData.get('file').name, data.document_key, formData.get('target_lang')); } else if (data.error) { console.error('Error:', data.error); } }) .catch(error => { console.error('Error:', error); }); } function addJobToList(documentId, fileName) { console.log(`Adding job to list: ${fileName} (ID: ${documentId})`); const jobList = document.getElementById('jobList'); const jobItem = document.createElement('div'); jobItem.id = `job-${documentId}`; jobItem.innerHTML = ` `; jobList.appendChild(jobItem); if (!document.getElementById('selectAll')) { addSelectAllButton(); } document.getElementById('bulkDownload').style.display = 'block'; } function pollJobStatus(documentId, documentKey) { console.log(`Starting to poll status for document ID: ${documentId}`); const statusEndpoint = 'status.php'; console.log(`Using status endpoint: ${statusEndpoint}`); const pollInterval = setInterval(() => { console.log(`Polling status for document ID: ${documentId}`); fetch(`${statusEndpoint}?document_id=${documentId}&document_key=${documentKey}`) .then(response => response.json()) .then(data => { console.log(`Status response for document ID ${documentId}:`, data); updateJobStatus(documentId, data.status); if (data.status === 'done') { console.log(`Job completed for document ID: ${documentId}`); clearInterval(pollInterval); // Update job history with completed status let history = JSON.parse(localStorage.getItem('jobHistory')) || []; const jobIndex = history.findIndex(job => job.documentId === documentId); if (jobIndex !== -1) { history[jobIndex].status = 'Completed'; localStorage.setItem('jobHistory', JSON.stringify(history)); updateJobHistoryDisplay(); } } }) .catch(error => { console.error('Error polling status:', error); }); }, POLL_INTERVAL); } function updateJobStatus(documentId, status) { console.log(`Updating job status: ${documentId} - ${status}`); const jobItem = document.getElementById(`job-${documentId}`); if (jobItem) { const label = jobItem.querySelector('label'); label.textContent = `${label.textContent.split(' - ')[0]} - Status: ${status}`; if (status === 'done') { jobItem.querySelector('button').style.display = 'inline-block'; } } } function downloadJob(documentId) { console.log(`Initiating download for document ID: ${documentId}`); let history = JSON.parse(localStorage.getItem('jobHistory')) || []; const job = history.find(job => job.documentId === documentId); if (job && job.documentKey && job.fileName && job.targetLang) { console.log(`Found job in history: ${JSON.stringify(job)}`); const downloadUrl = `download.php?document_id=${documentId}&document_key=${job.documentKey}&original_filename=${encodeURIComponent(job.fileName)}&target_lang=${job.targetLang}`; // Create a hidden iframe to trigger the download and webhook const iframe = document.createElement('iframe'); iframe.style.display = 'none'; document.body.appendChild(iframe); iframe.src = downloadUrl; // Remove the iframe after a short delay setTimeout(() => { document.body.removeChild(iframe); }, 5000); } else { console.error(`Job not found in history or missing required information for document ID: ${documentId}`); alert('This job is no longer available for download or is missing required information.'); updateJobHistoryDisplay(); } } function addToJobHistory(documentId, fileName, documentKey, targetLang) { console.log(`Adding job to history: ${documentId}, ${fileName}, ${documentKey}, ${targetLang}`); let history = JSON.parse(localStorage.getItem('jobHistory')) || []; history.push({ documentId, fileName, documentKey, targetLang, status: 'Uploading', timestamp: Date.now() }); localStorage.setItem('jobHistory', JSON.stringify(history)); updateJobHistoryDisplay(); } function loadJobHistory() { updateJobHistoryDisplay(); } function updateJobHistoryDisplay() { cleanupOldJobs(); const historyContainer = document.getElementById('jobHistory'); const history = JSON.parse(localStorage.getItem('jobHistory')) || []; let historyHTML = '
No translation jobs yet.
'; } historyContainer.innerHTML = historyHTML; if (history.length > 0) { document.getElementById('clearHistory').addEventListener('click', clearJobHistory); } } function clearJobHistory() { localStorage.removeItem('jobHistory'); updateJobHistoryDisplay(); } function bulkDownload() { const checkedJobs = document.querySelectorAll('#jobList input[type="checkbox"]:checked'); checkedJobs.forEach(checkbox => { const documentId = checkbox.id.replace('check-', ''); downloadJob(documentId); }); } function updateSelectedFiles() { const fileInput = document.querySelector('input[type="file"]'); const fileList = document.getElementById('selectedFiles'); if (!fileList) { const newFileList = document.createElement('div'); newFileList.id = 'selectedFiles'; fileInput.parentNode.insertBefore(newFileList, fileInput.nextSibling); } const files = fileInput.files; let fileListHTML = 'Selected Files: