Files
docuseal/lib/templates/create_attachments.rb
T

65 lines
2.0 KiB
Ruby
Raw Normal View History

2023-09-01 01:27:13 +03:00
# frozen_string_literal: true
module Templates
module CreateAttachments
PDF_CONTENT_TYPE = 'application/pdf'
2023-10-22 01:54:20 +03:00
ANNOTATIONS_SIZE_LIMIT = 6.megabytes
2023-09-05 20:33:40 +03:00
InvalidFileType = Class.new(StandardError)
2024-01-14 23:22:41 +02:00
PdfEncrypted = Class.new(StandardError)
2023-09-01 01:27:13 +03:00
module_function
2024-06-22 13:16:22 +03:00
def call(template, params, extract_fields: false)
2024-04-10 00:44:36 +03:00
Array.wrap(params[:files].presence || params[:file]).map do |file|
2024-04-06 15:44:50 +03:00
if file.content_type.exclude?('image') && file.content_type != PDF_CONTENT_TYPE
2024-04-06 21:44:44 +03:00
next handle_file_types(template, file, params)
2023-09-05 20:33:40 +03:00
end
2024-06-22 13:16:22 +03:00
handle_pdf_or_image(template, file, file.read, params, extract_fields:)
2024-04-06 21:44:44 +03:00
end
end
2024-01-14 23:22:41 +02:00
2024-06-22 13:16:22 +03:00
def handle_pdf_or_image(template, file, document_data = nil, params = {}, extract_fields: false)
2024-04-06 21:44:44 +03:00
document_data ||= file.read
2024-01-14 23:22:41 +02:00
2024-04-06 21:44:44 +03:00
if file.content_type == PDF_CONTENT_TYPE
document_data = maybe_decrypt_pdf_or_raise(document_data, params)
2023-09-01 01:27:13 +03:00
2024-04-06 21:44:44 +03:00
annotations =
document_data.size < ANNOTATIONS_SIZE_LIMIT ? Templates::BuildAnnotations.call(document_data) : []
end
2023-09-01 01:27:13 +03:00
2024-04-06 21:44:44 +03:00
sha256 = Base64.urlsafe_encode64(Digest::SHA256.digest(document_data))
2024-04-06 15:44:50 +03:00
2024-04-06 21:44:44 +03:00
blob = ActiveStorage::Blob.create_and_upload!(
io: StringIO.new(document_data),
filename: file.original_filename,
metadata: {
identified: file.content_type == PDF_CONTENT_TYPE,
analyzed: file.content_type == PDF_CONTENT_TYPE,
pdf: { annotations: }.compact_blank, sha256:
}.compact_blank,
content_type: file.content_type
)
2024-04-06 15:44:50 +03:00
2024-04-06 21:44:44 +03:00
document = template.documents.create!(blob:)
2024-06-22 13:16:22 +03:00
Templates::ProcessDocument.call(document, document_data, extract_fields:)
2023-09-01 01:27:13 +03:00
end
2023-09-05 20:33:40 +03:00
2024-01-14 23:22:41 +02:00
def maybe_decrypt_pdf_or_raise(data, params)
if data.size < ANNOTATIONS_SIZE_LIMIT && PdfUtils.encrypted?(data)
PdfUtils.decrypt(data, params[:password])
else
data
end
rescue HexaPDF::EncryptionError
raise PdfEncrypted
end
2024-04-07 11:14:34 +03:00
def handle_file_types(_template, file, _params)
2024-04-06 21:44:44 +03:00
raise InvalidFileType, file.content_type
2023-09-05 20:33:40 +03:00
end
2023-09-01 01:27:13 +03:00
end
end