File size: 8,761 Bytes
bbfde3f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 | const Busboy = require('busboy');
const JSZip = require('jszip');
const { applyCorsHeaders, handleCorsPreflight } = require('../lib/cors-middleware');
let analyzePowerPoint;
try {
const pptxAnalyzer = require('../lib/pptx-analyzer');
analyzePowerPoint = pptxAnalyzer.analyzePowerPoint;
} catch (err) {
console.error('Failed to load pptx-analyzer:', err);
}
// Helper function to send JSON with proper headers
function sendJson(res, status, data) {
res.setHeader('Content-Type', 'application/json');
res.status(status).end(JSON.stringify(data));
}
// Helper function to extract text from paragraph XML - moved to top for availability
function extractTextFromParagraph(paragraphXml) {
const textMatches = paragraphXml.match(/<w:t[^>]*>(.*?)<\/w:t>/g);
if (!textMatches) return '';
return textMatches
.map(t => t.replace(/<w:t[^>]*>|<\/w:t>/g, ''))
.join('')
.trim();
}
module.exports = async (req, res) => {
if (handleCorsPreflight(req, res, { allowedMethods: 'POST, OPTIONS' })) {
return;
}
applyCorsHeaders(req, res, { allowedMethods: 'POST, OPTIONS' });
if (req.method !== 'POST') {
sendJson(res, 405, { error: 'Method not allowed' });
return;
}
try {
const busboy = Busboy({ headers: req.headers });
let fileData = null;
let filename = null;
busboy.on('file', (fieldname, file, info) => {
filename = info.filename;
const chunks = [];
file.on('data', (chunk) => {
chunks.push(chunk);
});
file.on('end', () => {
fileData = Buffer.concat(chunks);
});
});
busboy.on('finish', async () => {
if (!fileData || !filename) {
sendJson(res, 400, { error: 'No file uploaded' });
return;
}
const filenameLower = filename.toLowerCase();
// Support both PowerPoint and Word documents
const isPowerPoint = ['.pptx', '.ppt', '.pps', '.pot', '.potx', '.ppsx'].some(ext => filenameLower.endsWith(ext));
const isWord = filenameLower.endsWith('.docx');
if (!isPowerPoint && !isWord) {
sendJson(res, 400, { error: 'Please upload a PowerPoint or Word document (.docx, .pptx)' });
return;
}
try {
let report;
if (isPowerPoint) {
// Route PowerPoint files to the PowerPoint analyzer
if (!analyzePowerPoint) {
throw new Error('PowerPoint analyzer not available');
}
report = await analyzePowerPoint(fileData, filename);
} else {
// Route Word documents to the Word analyzer
report = await analyzeDocx(fileData, filename);
}
sendJson(res, 200, {
fileName: filename,
suggestedFileName: filename,
report: report
});
} catch (error) {
console.error('Analysis error:', error);
sendJson(res, 500, { error: error.message });
}
});
req.pipe(busboy);
} catch (error) {
console.error('Upload error:', error);
sendJson(res, 500, { error: error.message });
}
};
module.exports.analyzeDocx = analyzeDocx;
async function analyzeDocx(fileData, filename) {
const report = {
fileName: filename,
suggestedFileName: filename,
summary: { fixed: 0, flagged: 0 },
details: {
// Requirement 1: Lists are formatted correctly
hyphenatedParagraphsNeedingLists: [],
formattedListsCount: 0,
// Requirement 2: Images have alt text (max 250 chars)
imagesMissingAltText: [],
imagesWithAltTextOver250Chars: [],
imagesWithValidAltText: 0,
}
};
try {
const zip = await JSZip.loadAsync(fileData);
// Read core documents needed for the two requirements
const documentXml = await zip.file('word/document.xml')?.async('string');
const relsXml = await zip.file('word/_rels/document.xml.rels')?.async('string');
// ===== REQUIREMENT 1: Check for lists formatted correctly =====
if (documentXml) {
const listIssues = analyzeListFormatting(documentXml);
if (listIssues.hyphenatedParagraphs.length > 0) {
report.details.hyphenatedParagraphsNeedingLists = listIssues.hyphenatedParagraphs;
report.summary.flagged += listIssues.hyphenatedParagraphs.length;
}
report.details.formattedListsCount = listIssues.properlyFormattedLists;
}
// ===== REQUIREMENT 2: Check for images with alt text =====
if (relsXml && documentXml) {
const imageAnalysis = analyzeImageAltText(documentXml, relsXml);
if (imageAnalysis.missingAltText.length > 0) {
report.details.imagesMissingAltText = imageAnalysis.missingAltText;
report.summary.flagged += imageAnalysis.missingAltText.length;
}
if (imageAnalysis.altTextOver250Chars.length > 0) {
report.details.imagesWithAltTextOver250Chars = imageAnalysis.altTextOver250Chars;
report.summary.flagged += imageAnalysis.altTextOver250Chars.length;
}
report.details.imagesWithValidAltText = imageAnalysis.validAltTextCount;
}
return report;
} catch (error) {
console.error('[analyzeDocx] Error analyzing document:', error);
return {
fileName: filename,
error: error.message,
summary: { fixed: 0, flagged: 0 },
details: {}
};
}
}
// ===== HELPER FUNCTIONS =====
/**
* Analyze list formatting in the document
* Detects hyphenated paragraphs that should be formatted as lists
*/
function analyzeListFormatting(documentXml) {
const results = {
hyphenatedParagraphs: [],
properlyFormattedLists: 0
};
if (!documentXml) return results;
// Extract all paragraphs
const paragraphMatches = documentXml.match(/<w:p[^>]*>([\s\S]*?)<\/w:p>/g) || [];
paragraphMatches.forEach((paragraph, index) => {
// Extract text content from paragraph
const textMatches = paragraph.match(/<w:t[^>]*>(.*?)<\/w:t>/g) || [];
const text = textMatches
.map(t => t.replace(/<w:t[^>]*>|<\/w:t>/g, ''))
.join('')
.trim();
// Check if paragraph starts with hyphen/dash (indicates list formatting issue)
if (text && /^[-–—]\s+/.test(text)) {
results.hyphenatedParagraphs.push({
index: index + 1,
text: text.substring(0, 100), // First 100 chars
message: 'This paragraph appears to be a list item but is formatted as a regular paragraph'
});
}
// Count properly formatted lists (pPr contains pStyle with list references)
if (paragraph.includes('pStyle w:val="ListParagraph"') || paragraph.includes('numPr')) {
results.properlyFormattedLists++;
}
});
return results;
}
/**
* Analyze image alt text requirements
* Checks for missing alt text and validates length
*/
function analyzeImageAltText(documentXml, relsXml) {
const results = {
missingAltText: [],
altTextOver250Chars: [],
validAltTextCount: 0
};
if (!documentXml || !relsXml) return results;
// Find all images/drawings
const drawingMatches = documentXml.match(/<wp:inline[^>]*>[\s\S]*?<\/wp:inline>|<wp:anchor[^>]*>[\s\S]*?<\/wp:anchor>/g) || [];
drawingMatches.forEach((drawing, index) => {
// Extract relationship ID to find the image file
const rIdMatch = drawing.match(/r:embed="(rId\d+)"/);
if (!rIdMatch) return;
const rId = rIdMatch[1];
// Extract alternate text (docProperties)
const altTextMatch = drawing.match(/<wp:docPr[^>]*descr="([^"]*)"/) || drawing.match(/<wp:cNvPicPr[^>]*>[\s\S]*?<a:picLocks[^>]*descr="([^"]*)"/);
const altText = altTextMatch ? altTextMatch[1] : null;
// Also check for extent/alt description in other formats
const titleMatch = drawing.match(/<wp:docPr[^>]*name="([^"]*)"[^>]*title="([^"]*)"/) || drawing.match(/<wp:docPr[^>]*title="([^"]*)"[^>]*name="([^"]*)"/);
// Check if this image has proper alt text
if (!altText || altText.trim() === '') {
results.missingAltText.push({
index: index + 1,
rId: rId,
message: 'Image is missing alt text description'
});
} else if (altText.length > 250) {
results.altTextOver250Chars.push({
index: index + 1,
rId: rId,
altText: altText.substring(0, 100) + '...',
length: altText.length,
message: `Alt text is ${altText.length} characters (max 250)`
});
} else {
// Valid alt text
results.validAltTextCount++;
}
});
return results;
}
|