summaryrefslogtreecommitdiff
path: root/app/models/project_services/mattermost_slash_commands_service.rb
blob: 92e2ae637fb773b58f76c2a199d23ff303fac1e7 (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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
class MattermostSlashCommandsService < ChatService
  include TriggersHelper

  prop_accessor :token

  def can_test?
    false
  end

  def title
    'Mattermost Command'
  end

  def description
    "Perform common operations on GitLab in Mattermost"
  end

  def to_param
    'mattermost_slash_commands'
  end

  def fields
    [
      { type: 'text', name: 'token', placeholder: '' }
    ]
  end

  def configure(current_user, params)
    result = Mattermost::Session.new(current_user).with_session do |session|
      Mattermost::Command.create(session, params[:team_id], command)
    end

    if result.has_key?('message')
      result['message']
    else
      update!(token: result['token'], active: true)
    end
  end

  def list_teams(current_user)
    begin
      response = Mattermost::Session.new(current_user).with_session do |session|
        Mattermost::Team.all(session)
      end

      # We ignore the error message as we can't display it
      response.has_key?('message') ? [] : response
    rescue Mattermost::NoSessionError
      []
    end
  end

  def trigger(params)
    return nil unless valid_token?(params[:token])

    user = find_chat_user(params)
    unless user
      url = authorize_chat_name_url(params)
      return Mattermost::Presenter.authorize_chat_name(url)
    end

    Gitlab::ChatCommands::Command.new(project, user, params).execute
  end

  private

  def command(trigger:, url:, icon_url:)
    pretty_project_name = project.name_with_namespace

    {
      auto_complete: true,
      auto_complete_desc: "Perform common operations on: #{pretty_project_name}",
      auto_complete_hint: '[help]',
      description: "Perform common operations on: #{pretty_project_name}",
      display_name: "GitLab  / #{pretty_project_name}",
      method: 'P',
      user_name: 'GitLab',
      trigger: trigger,
      url: url,
      icon_url: icon_url
    }
  end

  def find_chat_user(params)
    ChatNames::FindUserService.new(self, params).execute
  end

  def authorize_chat_name_url(params)
    ChatNames::AuthorizeUserService.new(self, params).execute
  end
end