fix: PK signature offset searching for UDF files in backend

This commit is contained in:
mstfyldz
2026-08-14 13:23:48 +03:00
parent 6dd34fe703
commit 95478c09e8
+35 -11
View File
@@ -405,24 +405,44 @@ export async function extractTextFromUploadedFile(file: { buffer: Buffer; mimety
if (fileName.endsWith('.udf')) {
try {
const zip = new AdmZip(file.buffer);
const zipEntries = zip.getEntries();
let zip: AdmZip | null = null;
try {
zip = new AdmZip(file.buffer);
} catch (e) {
// PK\x03\x04 imzasını (0x50, 0x4B, 0x03, 0x04) buffer içinde ara (UYAP e-imza başlığı olan dosyalar için)
const pkSignature = Buffer.from([0x50, 0x4b, 0x03, 0x04]);
const pkIndex = file.buffer.indexOf(pkSignature);
if (pkIndex > 0) {
try {
zip = new AdmZip(file.buffer.subarray(pkIndex));
} catch (_) {}
}
}
if (zip) {
const zipEntries = zip.getEntries().filter((e: any) => !e.isDirectory);
// 1. Önce XML dosyasını kontrol et (content.xml veya *.xml)
const xmlEntry = zipEntries.find((entry: any) =>
!entry.isDirectory && (entry.entryName === "content.xml" || entry.entryName.toLowerCase().endsWith(".xml"))
entry.entryName === "content.xml" || entry.entryName.toLowerCase().endsWith(".xml")
);
// 2. İçerisinde gömülü PDF dosyası var mı kontrol et (*.pdf)
const pdfEntry = zipEntries.find((entry: any) =>
!entry.isDirectory && entry.entryName.toLowerCase().endsWith(".pdf")
entry.entryName.toLowerCase().endsWith(".pdf")
);
// Eğer XML bulunmuşsa XML üzerinden devam et
if (xmlEntry) {
const xmlData = zip.readAsText(xmlEntry);
if (xmlData && xmlData.trim()) {
const plainText = xmlData.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
const rawXml = zip.readAsText(xmlEntry);
if (rawXml && rawXml.trim()) {
const plainText = rawXml.replace(/<style[\s\S]*?<\/style>/gi, '')
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<\/p>/gi, '\n')
.replace(/<[^>]+>/g, " ")
.replace(/&nbsp;/g, " ")
.replace(/\s+/g, " ")
.trim();
if (plainText.length > 20) {
return plainText;
}
@@ -438,11 +458,15 @@ export async function extractTextFromUploadedFile(file: { buffer: Buffer; mimety
return pdfText.trim();
}
}
}
// Yedek durum: Son çare XML metnini döndür
if (xmlEntry) {
const xmlData = zip.readAsText(xmlEntry);
return xmlData.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
// ZIP çözülemediyse düz XML / metin olarak oku
const rawText = file.buffer.toString('utf8');
if (rawText && rawText.trim().length > 20) {
const plainText = rawText.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
if (plainText.length > 20) {
return plainText;
}
}
throw new Error("UDF/ZIP arşivinde okunabilir XML veya PDF içeriği bulunamadı.");