-
Notifications
You must be signed in to change notification settings - Fork 1k
/
incoming_message_prototype.rb
101 lines (87 loc) 路 2.29 KB
/
incoming_message_prototype.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# frozen_string_literal: true
class IncomingMessagePrototype
attr_accessor :to
attr_accessor :from
attr_accessor :route_id
attr_accessor :subject
attr_accessor :plain_body
attr_accessor :attachments
def initialize(server, ip, source_type, attributes)
@server = server
@ip = ip
@source_type = source_type
@attachments = []
attributes.each do |key, value|
instance_variable_set("@#{key}", value)
end
end
def from_address
@from.gsub(/.*</, "").gsub(/>.*/, "").strip
end
def route
@routes ||= if @to.present?
uname, domain = @to.split("@", 2)
uname, _tag = uname.split("+", 2)
@server.routes.includes(:domain).where(domains: { name: domain }, name: uname).first
end
end
def attachments
(@attachments || []).map do |attachment|
{
name: attachment[:name],
content_type: attachment[:content_type] || "application/octet-stream",
data: attachment[:base64] ? Base64.decode64(attachment[:data]) : attachment[:data]
}
end
end
def create_messages
if valid?
messages = route.create_messages do |message|
message.rcpt_to = @to
message.mail_from = from_address
message.raw_message = raw_message
end
{ route.description => { id: messages.first.id, token: messages.first.token } }
else
false
end
end
def valid?
validate
errors.empty?
end
def errors
@errors || []
end
def validate
@errors = []
if route.nil?
@errors << "NoRoutesFound"
end
if from.empty?
@errors << "FromAddressMissing"
end
if subject.blank?
@errors << "SubjectMissing"
end
@errors
end
def raw_message
@raw_message ||= begin
mail = Mail.new
mail.to = @to
mail.from = @from
mail.subject = @subject
mail.text_part = @plain_body
mail.message_id = "<#{SecureRandom.uuid}@#{Postal.config.dns.return_path}>"
attachments.each do |attachment|
mail.attachments[attachment[:name]] = {
mime_type: attachment[:content_type],
content: attachment[:data]
}
end
mail.header["Received"] = Postal::ReceivedHeader.generate(@server, @source_type, @ip, :http)
mail.to_s
end
end
end