BigW Consortium Gitlab

receiver.rb 1.85 KB
Newer Older
1

2
require_dependency 'gitlab/email/handler'
3

4 5 6
# Inspired in great part by Discourse's Email::Receiver
module Gitlab
  module Email
7 8 9 10 11 12 13 14 15 16 17 18
    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
19
    class UnknownIncomingEmail < ProcessingError; end
20

21 22
    class Receiver
      def initialize(raw)
23
        @raw = raw
24 25 26
      end

      def execute
27 28 29 30
        raise EmptyEmailError if @raw.blank?

        mail = build_mail
        mail_key = extract_mail_key(mail)
Lin Jen-Shin committed
31
        handler = Handler.for(mail, mail_key)
32

33 34 35
        raise UnknownIncomingEmail unless handler

        handler.execute
36
      end
37

38 39
      def build_mail
        Mail::Message.new(@raw)
40 41
      rescue Encoding::UndefinedConversionError,
             Encoding::InvalidByteSequenceError => e
42 43 44
        raise EmailUnparsableError, e
      end

45 46
      def extract_mail_key(mail)
        key_from_to_header(mail) || key_from_additional_headers(mail)
47 48
      end

49
      def key_from_to_header(mail)
50
        mail.to.find do |address|
51
          key = Gitlab::IncomingEmail.key_from_address(address)
52
          break key if key
53 54 55
        end
      end

56
      def key_from_additional_headers(mail)
57
        Array(mail.references).find do |mail_id|
58
          key = Gitlab::IncomingEmail.key_from_fallback_message_id(mail_id)
59
          break key if key
60 61
        end
      end
62 63 64
    end
  end
end