create_issue_handler.rb 2.35 KB
Newer Older
1 2
# frozen_string_literal: true

3
require 'gitlab/email/handler/base_handler'
4

5 6 7
# handles issue creation emails with these formats:
#   incoming+gitlab-org-gitlab-ce-20-Author_Token12345678-issue@incoming.gitlab.com
#   incoming+gitlab-org/gitlab-ce+Author_Token12345678@incoming.gitlab.com (legacy)
8 9
module Gitlab
  module Email
10 11
    module Handler
      class CreateIssueHandler < BaseHandler
12
        include ReplyProcessing
13

14
        HANDLER_REGEX        = /\A#{HANDLER_ACTION_BASE_REGEX}-(?<incoming_email_token>.+)-issue\z/.freeze
15
        HANDLER_REGEX_LEGACY = /\A(?<project_path>[^\+]*)\+(?<incoming_email_token>.*)\z/.freeze
16 17 18

        def initialize(mail, mail_key)
          super(mail, mail_key)
19

20 21 22 23
          if !mail_key&.include?('/') && (matched = HANDLER_REGEX.match(mail_key.to_s))
            @project_slug         = matched[:project_slug]
            @project_id           = matched[:project_id]&.to_i
            @incoming_email_token = matched[:incoming_email_token]
24
          elsif matched = HANDLER_REGEX_LEGACY.match(mail_key.to_s)
25 26
            @project_path         = matched[:project_path]
            @incoming_email_token = matched[:incoming_email_token]
27
          end
28 29
        end

30
        def can_handle?
31
          incoming_email_token && (project_id || can_handle_legacy_format?)
32 33 34
        end

        def execute
35
          raise ProjectNotFound unless project
36

37 38
          validate_permission!(:create_issue)

39 40 41 42
          verify_record!(
            record: create_issue,
            invalid_exception: InvalidIssueError,
            record_name: 'issue')
43 44
        end

45
        # rubocop: disable CodeReuse/ActiveRecord
46
        def author
47
          @author ||= User.find_by(incoming_email_token: incoming_email_token)
48
        end
49
        # rubocop: enable CodeReuse/ActiveRecord
50

51 52 53 54
        def metrics_event
          :receive_email_create_issue
        end

55
        private
56

57 58
        def create_issue
          Issues::CreateService.new(
59 60 61 62 63
            project: project,
            current_user: author,
            params: {
              title: mail.subject,
              description: message_including_reply
64 65
            },
            spam_params: nil
66 67
          ).execute
        end
68 69 70 71

        def can_handle_legacy_format?
          project_path && !incoming_email_token.include?('+') && !mail_key.include?(Gitlab::IncomingEmail::UNSUBSCRIBE_SUFFIX_LEGACY)
        end
72 73 74 75
      end
    end
  end
end