2013-06-10 16:46:08 -04:00
#
# Handles an incoming message
#
module Email
class Receiver
def self . results
2013-06-13 18:11:10 -04:00
@results || = Enum . new ( :unprocessable , :missing , :processed )
2013-06-10 16:46:08 -04:00
end
2013-06-13 18:11:10 -04:00
attr_reader :body , :reply_key , :email_log
def initialize ( raw )
@raw = raw
2013-06-10 16:46:08 -04:00
end
def process
2013-06-13 18:11:10 -04:00
return Email :: Receiver . results [ :unprocessable ] if @raw . blank?
2013-06-19 12:14:01 -04:00
@message = Mail :: Message . new ( @raw )
parse_body
2013-06-13 18:11:10 -04:00
return Email :: Receiver . results [ :unprocessable ] if @body . blank?
2013-06-10 16:46:08 -04:00
2013-06-19 12:14:01 -04:00
@reply_key = @message . to . first
2013-06-13 18:11:10 -04:00
# Extract the `reply_key` from the format the site has specified
tokens = SiteSetting . reply_by_email_address . split ( " %{reply_key} " )
tokens . each do | t |
@reply_key . gsub! ( t , " " ) if t . present?
2013-06-10 16:46:08 -04:00
end
2013-06-13 18:11:10 -04:00
# Look up the email log for the reply key
@email_log = EmailLog . for ( reply_key )
return Email :: Receiver . results [ :missing ] if @email_log . blank?
create_reply
Email :: Receiver . results [ :processed ]
end
private
2013-06-19 12:14:01 -04:00
def parse_body
@body = @message . body . to_s . strip
return if @body . blank?
# I really hate to have to do this, but there seems to be a bug in Mail::Message
# with content boundaries in emails. Until it is fixed, this hack removes stuff
# we don't want from emails bodies
content_type = @message . header [ 'Content-Type' ] . to_s
if content_type . present?
boundary_match = content_type . match ( / boundary \ =(.*)$ / )
boundary = boundary_match [ 1 ] if boundary_match && boundary_match [ 1 ] . present?
if boundary . present? and @body . present?
lines = @body . lines
lines = lines [ 1 .. - 1 ] if lines . present? and lines [ 0 ] =~ / ^-- #{ boundary } /
lines = lines [ 1 .. - 1 ] if lines . present? and lines [ 0 ] =~ / ^Content-Type /
@body = lines . join . strip!
end
end
@body = EmailReplyParser . read ( @body ) . visible_text
end
2013-06-13 18:11:10 -04:00
def create_reply
# Try to post the body as a reply
creator = PostCreator . new ( email_log . user ,
raw : @body ,
topic_id : @email_log . topic_id ,
reply_to_post_number : @email_log . post . post_number )
2013-06-10 16:46:08 -04:00
2013-06-13 18:11:10 -04:00
creator . create
2013-06-10 16:46:08 -04:00
end
end
end