Class: Pdf::Utility::FileNormalizer

Inherits:
Object
  • Object
show all
Defined in:
app/services/pdf/utility/file_normalizer.rb

Overview

Normalizes PDF files accidentally saved with a raw HTTP response prepended.

The response headers are stripped with streaming I/O before any PDF parser
sees the file. Arbitrary data containing a later "%PDF-" marker is left
untouched, so ordinary images cannot be misclassified and overwritten.

Class Method Summary collapse

Class Method Details

.call(file_path) ⇒ Boolean

Normalize +file_path+ when it starts with PDF bytes or a raw HTTP response.

Parameters:

  • file_path (String)

    path to inspect and, when necessary, rewrite

Returns:

  • (Boolean)

    whether the resulting file starts with a PDF signature



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'app/services/pdf/utility/file_normalizer.rb', line 20

def call(file_path)
  return false unless file_path && File.file?(file_path)

  header = File.binread(file_path, HEADER_BYTES)
  return true if header.start_with?(PDF_SIGNATURE)

  pdf_offset = http_body_offset(header)
  return false unless pdf_offset

  strip_prefix!(file_path, pdf_offset)
  Rails.logger.info { "[PdfFileNormalizer] Stripped HTTP response headers from #{file_path}" }
  true
rescue StandardError => e
  Rails.logger.error { "[PdfFileNormalizer] Failed to normalize #{file_path}: #{e.message}" }
  false
end