2017-09-30 01:20:12 +02:00
|
|
|
require "email_reply_trimmer"
|
|
|
|
|
2017-08-19 15:45:48 +02:00
|
|
|
class MessagesMailReceiver
|
|
|
|
|
|
|
|
def self.regexp
|
|
|
|
/(?<message_id>\d+)\.(?<user_id>\d+)\.(?<hash>\w+)/
|
|
|
|
end
|
|
|
|
|
2017-10-02 16:16:02 +02:00
|
|
|
def initialize(match)
|
|
|
|
@message = Message.find_by_id(match[:message_id])
|
|
|
|
@user = User.find_by_id(match[:user_id])
|
2017-08-19 15:45:48 +02:00
|
|
|
|
2017-10-02 16:16:02 +02:00
|
|
|
raise "Message could not be found" if @message.nil?
|
|
|
|
raise "User could not be found" if @user.nil?
|
2017-08-19 15:45:48 +02:00
|
|
|
|
2017-10-02 16:16:02 +02:00
|
|
|
hash = @message.mail_hash_for_user(@user)
|
2017-08-19 15:45:48 +02:00
|
|
|
raise "Hash does not match expectations" unless hash.casecmp(match[:hash]) == 0
|
2017-10-02 16:16:02 +02:00
|
|
|
end
|
2017-08-19 15:45:48 +02:00
|
|
|
|
2017-10-02 16:16:02 +02:00
|
|
|
def received(data)
|
2017-08-19 15:45:48 +02:00
|
|
|
mail = Mail.new data
|
|
|
|
|
|
|
|
mail_part = nil
|
|
|
|
if mail.multipart?
|
|
|
|
for part in mail.parts
|
2017-09-30 01:18:02 +02:00
|
|
|
content_type = MIME::Type.simplified(part.content_type)
|
|
|
|
if content_type == "text/plain" || !mail_part && content_type == "text/html"
|
|
|
|
mail_part = part
|
|
|
|
end
|
2017-08-19 15:45:48 +02:00
|
|
|
end
|
|
|
|
else
|
|
|
|
mail_part = mail
|
|
|
|
end
|
|
|
|
|
|
|
|
body = mail_part.body.decoded
|
|
|
|
unless mail_part.content_type_parameters.nil?
|
|
|
|
body = body.force_encoding mail_part.content_type_parameters[:charset]
|
|
|
|
end
|
|
|
|
|
2017-09-30 01:18:02 +02:00
|
|
|
if MIME::Type.simplified(mail_part.content_type) == "text/html"
|
|
|
|
body = Nokogiri::HTML(body).text
|
|
|
|
end
|
|
|
|
|
2017-09-30 01:20:12 +02:00
|
|
|
body = EmailReplyTrimmer.trim(body)
|
|
|
|
|
2017-10-02 16:16:02 +02:00
|
|
|
message = @user.send_messages.new body: body,
|
|
|
|
group: @message.group,
|
|
|
|
private: @message.private,
|
|
|
|
received_email: data,
|
2017-08-19 15:45:48 +02:00
|
|
|
subject: mail.subject.gsub("[#{FoodsoftConfig[:name]}] ", "")
|
2017-10-02 16:16:02 +02:00
|
|
|
if @message.reply_to
|
|
|
|
message.reply_to_message = @message.reply_to_message
|
2017-08-19 15:45:48 +02:00
|
|
|
else
|
2017-10-02 16:16:02 +02:00
|
|
|
message.reply_to_message = @message
|
2017-08-19 15:45:48 +02:00
|
|
|
end
|
2017-10-02 16:16:02 +02:00
|
|
|
message.add_recipients @message.recipients
|
|
|
|
message.add_recipients [@message.sender]
|
2017-08-19 15:45:48 +02:00
|
|
|
|
|
|
|
message.save!
|
|
|
|
Resque.enqueue(MessageNotifier, FoodsoftConfig.scope, "message_deliver", message.id)
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|