gitlab-org--gitlab-foss/lib/gitlab/email/receiver.rb

80 lines
2.3 KiB
Ruby
Raw Normal View History

require_dependency 'gitlab/email/handler'
# Inspired in great part by Discourse's Email::Receiver
module Gitlab
module Email
class ProcessingError < StandardError; end
class EmailUnparsableError < ProcessingError; end
class SentNotificationNotFoundError < ProcessingError; end
class ProjectNotFound < ProcessingError; end
class EmptyEmailError < ProcessingError; end
class AutoGeneratedEmailError < ProcessingError; end
class UserNotFoundError < ProcessingError; end
class UserBlockedError < ProcessingError; end
class UserNotAuthorizedError < ProcessingError; end
class NoteableNotFoundError < ProcessingError; end
class InvalidNoteError < ProcessingError; end
class InvalidIssueError < ProcessingError; end
class UnknownIncomingEmail < ProcessingError; end
class Receiver
def initialize(raw)
@raw = raw
end
def execute
raise EmptyEmailError if @raw.blank?
mail = build_mail
mail_key = extract_mail_key(mail)
2016-06-15 04:18:40 -04:00
handler = Handler.for(mail, mail_key)
2016-06-15 04:23:41 -04:00
raise UnknownIncomingEmail unless handler
handler.execute
end
private
def build_mail
Mail::Message.new(@raw)
rescue Encoding::UndefinedConversionError,
Encoding::InvalidByteSequenceError => e
2015-08-20 15:17:59 -04:00
raise EmailUnparsableError, e
end
def extract_mail_key(mail)
key_from_to_header(mail) || key_from_additional_headers(mail)
end
def key_from_to_header(mail)
mail.to.find do |address|
key = Gitlab::IncomingEmail.key_from_address(address)
break key if key
end
end
def key_from_additional_headers(mail)
find_key_from_references(ensure_references_array(mail.references))
end
def ensure_references_array(references)
case references
when Array
references
when String # Handle emails from Microsoft exchange which uses commas
Gitlab::IncomingEmail.scan_fallback_references(references)
end
end
def find_key_from_references(references)
references.find do |mail_id|
key = Gitlab::IncomingEmail.key_from_fallback_message_id(mail_id)
break key if key
end
end
end
end
end