summaryrefslogtreecommitdiff
path: root/lib/gitlab/email/handler/create_issue_handler.rb
blob: 78a3a9489acacf6631539d83d0dee37f38d49a02 (plain)
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
# frozen_string_literal: true

require 'gitlab/email/handler/base_handler'

# 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)
module Gitlab
  module Email
    module Handler
      class CreateIssueHandler < BaseHandler
        include ReplyProcessing

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

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

          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]
          elsif matched = HANDLER_REGEX_LEGACY.match(mail_key.to_s)
            @project_path         = matched[:project_path]
            @incoming_email_token = matched[:incoming_email_token]
          end
        end

        def can_handle?
          incoming_email_token && (project_id || can_handle_legacy_format?)
        end

        def execute
          raise ProjectNotFound unless project

          validate_permission!(:create_issue)

          verify_record!(
            record: create_issue,
            invalid_exception: InvalidIssueError,
            record_name: 'issue')
        end

        # rubocop: disable CodeReuse/ActiveRecord
        def author
          @author ||= User.find_by(incoming_email_token: incoming_email_token)
        end
        # rubocop: enable CodeReuse/ActiveRecord

        private

        def create_issue
          Issues::CreateService.new(
            project,
            author,
            title:       mail.subject,
            description: message_including_reply
          ).execute
        end

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