Class: Mail2FrontMatter::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/mail2frontmatter/parser.rb

Constant Summary collapse

ALLOWED_TYPES =
{
  "audio" => "audio",
  "video" => "videos", 
  "image" => "images"
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(message) ⇒ Parser

Returns a new instance of Parser.



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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/mail2frontmatter/parser.rb', line 16

def initialize(message)
  @message = message
  raw_parsed_html = Nokogiri::HTML.parse(@message.html_part.body.raw_source.strip)
  @body = raw_parsed_html.at("body")

  # remove extraneous nesting
  while(@body.children.count == 1 && @body.children.first.name == "div") do
    @body = @body.children.first
  end

  attachments = {}

  @message.attachments.each do |attachment|
    if Parser::ALLOWED_TYPES.keys.include?(attachment.main_type)

      # save attachments
      media_directory = File.join(Dir.pwd, 'source', Parser::ALLOWED_TYPES[attachment.main_type])
      FileUtils.mkdir_p(media_directory)

      filepath = File.join(media_directory, attachment.filename) 

      # save attachment
      File.open(filepath, "w+b", 0644) {|f| f.write attachment.body.decoded}

      # retain metadata
      attachments[attachment.cid] = {
        maintype: attachment.main_type,
        mimetype: attachment.mime_type,
        filename: attachment.filename,
        filepath: filepath
      }

    # file type not allowed
    else
      # remove cooresponding node from html
      @body.xpath("//*[@src='cid:#{attachment.content_id}']").remove

    end
  end

  # convert body immediately to a string, why?
  # Plugins / pre-processors may wish to manipulate the body
  # however Nokogiri is strict and won't allow template tags
  # for obvious good reasons
  @body = @body.inner_html

  @metadata = {
    from:        message[:from].value,
    to:          message[:to].value,
    received:    message.date,
    subject:     message.subject,
    attachments: attachments
  }

end

Instance Attribute Details

#bodyObject

Returns the value of attribute body.



8
9
10
# File 'lib/mail2frontmatter/parser.rb', line 8

def body
  @body
end

#messageObject

Returns the value of attribute message.



8
9
10
# File 'lib/mail2frontmatter/parser.rb', line 8

def message
  @message
end

#metadataObject

Returns the value of attribute metadata.



8
9
10
# File 'lib/mail2frontmatter/parser.rb', line 8

def 
  @metadata
end