2015-08-20 14:05:06 -04:00
|
|
|
# Inspired in great part by Discourse's Email::Receiver
|
|
|
|
module Gitlab
|
|
|
|
module Email
|
|
|
|
class ReplyParser
|
|
|
|
attr_accessor :message
|
|
|
|
|
|
|
|
def initialize(message)
|
|
|
|
@message = message
|
|
|
|
end
|
|
|
|
|
|
|
|
def execute
|
|
|
|
body = select_body(message)
|
|
|
|
|
|
|
|
encoding = body.encoding
|
|
|
|
|
2016-11-18 04:57:37 -05:00
|
|
|
body = EmailReplyTrimmer.trim(body) or return ""
|
2015-08-20 14:05:06 -04:00
|
|
|
|
2016-11-15 02:58:37 -05:00
|
|
|
# [jneen] not using /\s+$/ here because that deletes empty lines
|
|
|
|
body = body.gsub(/[ \t]$/, '')
|
|
|
|
|
2015-08-20 14:05:06 -04:00
|
|
|
body.force_encoding(encoding).encode("UTF-8")
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def select_body(message)
|
2016-11-16 03:45:44 -05:00
|
|
|
if message.multipart?
|
|
|
|
part = message.text_part || message.html_part || message
|
2016-11-10 01:24:02 -05:00
|
|
|
else
|
2016-11-16 03:45:44 -05:00
|
|
|
part = message
|
2016-11-10 01:24:02 -05:00
|
|
|
end
|
2015-08-20 14:05:06 -04:00
|
|
|
|
2016-11-16 00:39:07 -05:00
|
|
|
decoded = fix_charset(part)
|
2016-11-10 01:24:02 -05:00
|
|
|
|
|
|
|
return "" unless decoded
|
2015-08-20 14:05:06 -04:00
|
|
|
|
|
|
|
# Certain trigger phrases that means we didn't parse correctly
|
2016-11-10 01:24:02 -05:00
|
|
|
if decoded =~ /(Content\-Type\:|multipart\/alternative|text\/plain)/
|
2015-08-20 14:05:06 -04:00
|
|
|
return ""
|
|
|
|
end
|
|
|
|
|
2016-11-16 00:39:07 -05:00
|
|
|
if (part.content_type || '').include? 'text/html'
|
2016-11-10 01:24:02 -05:00
|
|
|
HTMLParser.parse_reply(decoded)
|
|
|
|
else
|
|
|
|
decoded
|
|
|
|
end
|
2015-08-20 14:05:06 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
# Force encoding to UTF-8 on a Mail::Message or Mail::Part
|
|
|
|
def fix_charset(object)
|
|
|
|
return nil if object.nil?
|
|
|
|
|
|
|
|
if object.charset
|
|
|
|
object.body.decoded.force_encoding(object.charset.gsub(/utf8/i, "UTF-8")).encode("UTF-8").to_s
|
|
|
|
else
|
|
|
|
object.body.to_s
|
|
|
|
end
|
|
|
|
rescue
|
|
|
|
nil
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|