Files
docuseal/lib/templates/create_attachments.rb
T

61 lines
1.8 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
def call(template, params)
2024-04-06 15:44:50 +03:00
Array.wrap(params[:files].presence || params[:file]).map do |file|
if file.content_type.exclude?('image') && file.content_type != PDF_CONTENT_TYPE
file, document_data = handle_file_types(file)
2023-09-05 20:33:40 +03:00
end
2024-04-06 15:44:50 +03:00
document_data ||= file.read
2024-01-14 23:22:41 +02:00
2024-04-06 15:44:50 +03:00
if file.content_type == PDF_CONTENT_TYPE
document_data = maybe_decrypt_pdf_or_raise(document_data, params)
2024-01-14 23:22:41 +02:00
2023-10-22 01:54:20 +03:00
annotations =
2024-04-06 15:44:50 +03:00
document_data.size < ANNOTATIONS_SIZE_LIMIT ? Templates::BuildAnnotations.call(document_data) : []
2023-09-01 01:27:13 +03:00
end
2024-04-06 15:44:50 +03:00
sha256 = Base64.urlsafe_encode64(Digest::SHA256.digest(document_data))
2023-09-01 01:27:13 +03:00
2024-04-06 15:44:50 +03:00
blob = ActiveStorage::Blob.create_and_upload!(
io: StringIO.new(document_data),
2023-09-01 01:27:13 +03:00
filename: file.original_filename,
2024-04-06 15:44:50 +03:00
metadata: {
identified: file.content_type == PDF_CONTENT_TYPE,
analyzed: file.content_type == PDF_CONTENT_TYPE,
pdf: { annotations: }.compact_blank, sha256:
}.compact_blank,
2023-09-01 01:27:13 +03:00
content_type: file.content_type
)
2024-04-06 15:44:50 +03:00
document = template.documents.create!(blob:)
Templates::ProcessDocument.call(document, document_data)
2023-09-01 01:27:13 +03:00
end
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-06 15:44:50 +03:00
def handle_file_types(_file)
2023-09-05 20:33:40 +03:00
raise InvalidFileType, blob.content_type
end
2023-09-01 01:27:13 +03:00
end
end