2015-06-05 23:46:21 +08:00
|
|
|
# A very simple formatter for imported emails
|
2015-10-29 01:31:28 +08:00
|
|
|
|
2015-06-05 23:46:21 +08:00
|
|
|
class EmailCook
|
|
|
|
|
2015-10-30 04:01:50 +08:00
|
|
|
def self.url_regexp
|
2016-07-19 01:46:13 +08:00
|
|
|
/((?:https?:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.])(?:[^\s()<>]+|\([^\s()<>]+\))+(?:\([^\s()<>]+\)|[^`!()\[\]{};:'".,<>?«»“”‘’\s]))/
|
2015-10-30 04:01:50 +08:00
|
|
|
end
|
|
|
|
|
2015-06-05 23:46:21 +08:00
|
|
|
def initialize(raw)
|
|
|
|
@raw = raw
|
|
|
|
end
|
|
|
|
|
2016-07-16 03:36:56 +08:00
|
|
|
def add_quote(result, buffer)
|
|
|
|
if buffer.present?
|
|
|
|
return if buffer =~ /\A(<br>)+\z$/
|
|
|
|
result << "<blockquote>#{buffer}</blockquote>"
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2016-07-19 02:38:40 +08:00
|
|
|
def link_string!(str)
|
|
|
|
str.scan(EmailCook.url_regexp).each do |m|
|
|
|
|
url = m[0]
|
2016-07-19 03:00:12 +08:00
|
|
|
|
|
|
|
if str.strip == url
|
2017-10-18 02:36:57 +08:00
|
|
|
# this could be oneboxed
|
|
|
|
val = %|<a href="#{url}" class="onebox" target="_blank">#{url}</a>|
|
|
|
|
else
|
|
|
|
val = %|<a href="#{url}">#{url}</a>|
|
2016-07-19 03:00:12 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
str.gsub!(url, val)
|
2016-07-19 02:38:40 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2015-06-05 23:46:21 +08:00
|
|
|
def cook
|
|
|
|
result = ""
|
|
|
|
|
2016-07-13 03:37:19 +08:00
|
|
|
in_text = false
|
2015-06-05 23:46:21 +08:00
|
|
|
in_quote = false
|
2016-07-13 03:37:19 +08:00
|
|
|
|
2015-06-05 23:46:21 +08:00
|
|
|
quote_buffer = ""
|
|
|
|
@raw.each_line do |l|
|
|
|
|
|
|
|
|
if l =~ /^\s*>/
|
|
|
|
in_quote = true
|
2016-07-19 02:38:40 +08:00
|
|
|
link_string!(l)
|
2015-06-05 23:46:21 +08:00
|
|
|
quote_buffer << l.sub(/^[\s>]*/, '') << "<br>"
|
|
|
|
elsif in_quote
|
2016-07-16 03:36:56 +08:00
|
|
|
add_quote(result, quote_buffer)
|
2015-06-05 23:46:21 +08:00
|
|
|
quote_buffer = ""
|
|
|
|
in_quote = false
|
|
|
|
else
|
2015-10-30 04:01:50 +08:00
|
|
|
|
2016-07-13 01:49:03 +08:00
|
|
|
sz = l.size
|
|
|
|
|
2016-07-19 02:38:40 +08:00
|
|
|
link_string!(l)
|
2016-07-13 01:49:03 +08:00
|
|
|
|
|
|
|
result << l
|
2016-07-13 03:37:19 +08:00
|
|
|
|
|
|
|
if sz < 60
|
|
|
|
result << "<br>"
|
|
|
|
if in_text
|
|
|
|
result << "<br>"
|
|
|
|
end
|
|
|
|
in_text = false
|
|
|
|
else
|
|
|
|
in_text = true
|
|
|
|
end
|
2015-06-05 23:46:21 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2016-07-16 03:36:56 +08:00
|
|
|
if in_quote && quote_buffer.present?
|
|
|
|
add_quote(result, quote_buffer)
|
2015-06-05 23:46:21 +08:00
|
|
|
end
|
|
|
|
|
2016-07-13 03:37:19 +08:00
|
|
|
result.gsub!(/(<br>\n*){3,10}/, '<br><br>')
|
2015-06-05 23:46:21 +08:00
|
|
|
result
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|