discourse/lib/email_cook.rb

61 lines
1.2 KiB
Ruby
Raw Normal View History

# A very simple formatter for imported emails
class EmailCook
def self.url_regexp
/^((?:https?:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.])(?:[^\s()<>]+|\([^\s()<>]+\))+(?:\([^\s()<>]+\)|[^`!()\[\]{};:'".,<>?«»“”‘’\s]))/
end
def initialize(raw)
@raw = raw
end
def cook
result = ""
2016-07-12 15:37:19 -04:00
in_text = false
in_quote = false
2016-07-12 15:37:19 -04:00
quote_buffer = ""
@raw.each_line do |l|
if l =~ /^\s*>/
in_quote = true
quote_buffer << l.sub(/^[\s>]*/, '') << "<br>"
elsif in_quote
result << "<blockquote>#{quote_buffer}</blockquote>"
quote_buffer = ""
in_quote = false
else
sz = l.size
2015-10-29 16:07:45 -04:00
l.scan(EmailCook.url_regexp).each do |m|
url = m[0]
l.gsub!(url, "<a href='#{url}'>#{url}</a>")
end
result << l
2016-07-12 15:37:19 -04:00
if sz < 60
result << "<br>"
if in_text
result << "<br>"
end
in_text = false
else
in_text = true
end
end
end
if in_quote
result << "<blockquote>#{quote_buffer}</blockquote>"
end
2016-07-12 15:37:19 -04:00
result.gsub!(/(<br>\n*){3,10}/, '<br><br>')
result
end
end