debian-mirror-gitlab/lib/gitlab/email/receiver.rb

65 lines
1.8 KiB
Ruby
Raw Normal View History

2016-09-13 17:45:13 +05:30
require_dependency 'gitlab/email/handler'
2015-09-25 12:07:36 +05:30
# Inspired in great part by Discourse's Email::Receiver
module Gitlab
module Email
2016-09-13 17:45:13 +05:30
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
2015-09-25 12:07:36 +05:30
2016-09-13 17:45:13 +05:30
class Receiver
2015-09-25 12:07:36 +05:30
def initialize(raw)
@raw = raw
end
def execute
raise EmptyEmailError if @raw.blank?
2016-09-13 17:45:13 +05:30
mail = build_mail
mail_key = extract_mail_key(mail)
handler = Handler.for(mail, mail_key)
2015-09-25 12:07:36 +05:30
2016-09-13 17:45:13 +05:30
raise UnknownIncomingEmail unless handler
2015-09-25 12:07:36 +05:30
2016-09-13 17:45:13 +05:30
handler.execute
2015-09-25 12:07:36 +05:30
end
2016-09-13 17:45:13 +05:30
def build_mail
Mail::Message.new(@raw)
rescue Encoding::UndefinedConversionError,
Encoding::InvalidByteSequenceError => e
2015-09-25 12:07:36 +05:30
raise EmailUnparsableError, e
end
2016-09-13 17:45:13 +05:30
def extract_mail_key(mail)
key_from_to_header(mail) || key_from_additional_headers(mail)
2016-06-02 11:05:42 +05:30
end
2016-09-13 17:45:13 +05:30
def key_from_to_header(mail)
mail.to.find do |address|
2016-06-02 11:05:42 +05:30
key = Gitlab::IncomingEmail.key_from_address(address)
2016-09-13 17:45:13 +05:30
break key if key
2016-06-02 11:05:42 +05:30
end
end
2016-09-13 17:45:13 +05:30
def key_from_additional_headers(mail)
Array(mail.references).find do |mail_id|
key = Gitlab::IncomingEmail.key_from_fallback_message_id(mail_id)
break key if key
2015-09-25 12:07:36 +05:30
end
end
end
end
end