File size: 1,708 Bytes
c4e128a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Content validator for physical PDF documents."""

from __future__ import annotations

from pathlib import Path

from app.models.document import ValidationResult


class ContentValidator:
    """Validates physical PDF files based on size, accessibility, and header markers."""

    def __init__(
        self,
        min_file_size_kb: float = 1.0,
        max_file_size_mb: float = 500.0,
    ) -> None:
        self._min_bytes = int(min_file_size_kb * 1024)
        self._max_bytes = int(max_file_size_mb * 1024 * 1024)

    def validate(self, pdf_path: Path) -> ValidationResult:
        pdf_path = Path(pdf_path).resolve()
        errors: list[str] = []
        warnings: list[str] = []

        if not pdf_path.exists():
            return ValidationResult(is_valid=False, errors=[f"File does not exist: {pdf_path}"])

        size = pdf_path.stat().st_size
        if size < self._min_bytes:
            errors.append(
                f"File size ({size} bytes) below minimum threshold ({self._min_bytes} bytes)"
            )
        if size > self._max_bytes:
            errors.append(
                f"File size ({size} bytes) exceeds maximum threshold ({self._max_bytes} bytes)"
            )

        # Verify PDF header magic bytes (%PDF-)
        try:
            with pdf_path.open("rb") as f:
                header = f.read(5)
                if header != b"%PDF-":
                    errors.append("Invalid PDF header magic bytes (missing %PDF-)")
        except Exception as exc:
            errors.append(f"Failed to read file header: {exc}")

        return ValidationResult(
            is_valid=len(errors) == 0,
            errors=errors,
            warnings=warnings,
        )