File size: 1,538 Bytes
ba37a9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import * as fs from 'fs';
import * as path from 'path';
import AdmZip from 'adm-zip';
import { PDFDocument } from 'pdf-lib';
import { logger } from './logger';

export interface LocalDocumentMetadata {
  pageCount?: number;
  pageCountSource?: 'pdf' | 'docx_metadata';
}

export async function readLocalDocumentMetadata(
  filePath: string,
): Promise<LocalDocumentMetadata> {
  if (!filePath || !fs.existsSync(filePath)) return {};

  const extension = path.extname(filePath).toLowerCase();
  try {
    if (extension === '.pdf') {
      const bytes = await fs.promises.readFile(filePath);
      const pdf = await PDFDocument.load(bytes, {
        ignoreEncryption: true,
        updateMetadata: false,
      });
      const pageCount = pdf.getPageCount();
      return pageCount > 0 ? { pageCount, pageCountSource: 'pdf' } : {};
    }

    if (extension === '.docx') {
      const archive = new AdmZip(filePath);
      const appProperties = archive.getEntry('docProps/app.xml');
      if (!appProperties) return {};
      const xml = appProperties.getData().toString('utf-8');
      const match = xml.match(/<(?:\w+:)?Pages>\s*(\d+)\s*<\/(?:\w+:)?Pages>/i);
      const pageCount = match ? Number(match[1]) : 0;
      return pageCount > 0
        ? { pageCount, pageCountSource: 'docx_metadata' }
        : {};
    }
  } catch (error) {
    logger.warn('Could not read local document page count', {
      filePath: path.basename(filePath),
      error: error instanceof Error ? error.message : String(error),
    });
  }

  return {};
}