aboutsummaryrefslogtreecommitdiff
blob: 4d81197170a608fce2f6c4b66ad6b6fd2e110a9b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
require 'sanitize'
require 'cgi'

module Ag::Rendering
  class HTMLizer
    def self.HTMLize(mail)
      if mail.multipart?
        content_type = mime_split(mail.parts.first.content_type)

        if content_type == 'text/plain' or content_type == 'text/html'
          to_content(content_type, mail.parts.first.decoded, get_encoding(mail.parts.first))
        else
          # Nested multipart?
          if mail.parts.first.multipart?
            content_type = mime_split(mail.parts.first.parts.first.content_type)

            if content_type == 'text/plain' or content_type == 'text/html'
              to_content(content_type, mail.parts.first.parts.first.decoded, get_encoding(mail.parts.first.parts.first))
            else
              raise "Cannot find body: #{mail.message_id}"
            end
          # Specialty: Gnus/Emacs signed emails with no explicit multipart type
          elsif mime_split(mail.content_type) == 'multipart/signed'
            to_content('text/plain', mail.parts.first.decoded, get_encoding(mail.parts.first))
          end
        end
      else
        # No Content-Type, assume plain text (git-send-email)
        if mail.content_type == nil
          to_content('text/plain', mail.body.decoded, get_encoding(mail))
        else
          to_content(mime_split(mail.content_type), mail.body.decoded, get_encoding(mail))
        end
      end
    end

    def self.get_encoding(part)
      if part.content_type_parameters
        part.content_type_parameters['charset']
      else
        nil
      end
    end

    def self.to_content(content_type, content, charset = nil)
      #content = content.force_encoding(charset) if charset

      if content_type == 'text/plain'
        escaped_content = CGI::escapeHTML(content)
        escaped_content.lines.map do |line|
          if line.start_with? '>'
            "<div class=\"ag-quote\">#{line.rstrip}</div>\n"
          else
            line
          end
        end.join.gsub("</div>\n<div class=\"ag-quote\">", "\n")
      elsif content_type == 'text/html'
        '<div class="ag-html-content">' + Sanitize.clean(content, Sanitize::Config::BASIC) + '</div>'
      else
        '<div class="alert alert-danger" role="alert"><strong>Unsupported Content-Type</strong></div>'
      end
    end

    def self.mime_split(content_type)
      (content_type || '').split(';').first
    end
  end
end
# vim: ts=2 sts=2 et ft=ruby: