Class: MailDude::AttachmentLocator

Inherits:
Object
  • Object
show all
Defined in:
lib/mail_dude/attachment_locator.rb

Defined Under Namespace

Classes: Attachment

Instance Method Summary collapse

Constructor Details

#initialize(message) ⇒ AttachmentLocator

Returns a new instance of AttachmentLocator.



25
26
27
# File 'lib/mail_dude/attachment_locator.rb', line 25

def initialize(message)
  @message = message
end

Instance Method Details

#attachmentsObject



29
30
31
32
33
34
35
36
# File 'lib/mail_dude/attachment_locator.rb', line 29

def attachments
  return [] unless MailDude.configuration.capture_attachments

  attachment_parts.each_with_index.map do |part, index|
    id = "a#{index}"
    Attachment.new(id: id, part: part, metadata: (part, id))
  end
end

#find(attachment_id) ⇒ Object



38
39
40
41
42
43
# File 'lib/mail_dude/attachment_locator.rb', line 38

def find(attachment_id)
  raise AttachmentNotFoundError, 'Attachment not found' unless attachment_id.to_s.match?(/\Aa\d+\z/)

  attachments.find { |attachment| attachment.id == attachment_id.to_s } ||
    raise(AttachmentNotFoundError, 'Attachment not found')
end

#find_inline_by_cid(content_id) ⇒ Object



45
46
47
48
# File 'lib/mail_dude/attachment_locator.rb', line 45

def find_inline_by_cid(content_id)
  normalized = normalize_content_id(content_id)
  attachments.find { |attachment| attachment.['content_id'] == normalized }
end

#normalize_content_id(content_id) ⇒ Object



50
51
52
# File 'lib/mail_dude/attachment_locator.rb', line 50

def normalize_content_id(content_id)
  content_id.to_s.delete_prefix('cid:').delete_prefix('<').delete_suffix('>').strip
end

#sanitize_filename(filename, fallback:) ⇒ Object



54
55
56
57
58
# File 'lib/mail_dude/attachment_locator.rb', line 54

def sanitize_filename(filename, fallback:)
  sanitized = filename.to_s.encode('UTF-8', invalid: :replace, undef: :replace)
  sanitized = sanitized.gsub(%r{[/\\\0[:cntrl:]]}, '_').strip
  sanitized.presence || fallback
end