summaryrefslogtreecommitdiff
path: root/lib/mattermost/presenter.rb
blob: 3db55d6bd5114185375ac6b4a6664c9c951953a4 (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
module Mattermost
  class Presenter
    class << self
      COMMAND_PREFIX = '/gitlab'.freeze

      def authorize_chat_name(params)
        url = ChatNames::RequestService.new(service, params).execute

        {
          response_type: :ephemeral,
          message: "You are not authorized. Click this [link](#{url}) to authorize."
        }
      end

      def help(messages)
        messages = ["Available commands:"]

        messages.each do |messsage|
          messages << "- #{message}"
        end

        {
          response_type: :ephemeral,
          text: messages.join("\n")
        }
      end

      def not_found
        {
          response_type: :ephemeral,
          text: "404 not found! GitLab couldn't find what your were looking for! :boom:",
        }
      end

      def present(resource)
        return not_found unless resource

        if resource.respond_to?(:count)
          if resource.count > 1
            return multiple_resources(resource)
          elsif resource.count == 0
            return not_found
          else
            resource = resource.first
          end
        end

        single_resource(resource)
      end

      private

      def single_resource(resource)
        message = title(resource)
        message << "\n\n#{resource.description}" if resource.description

        {
          response_type: :in_channel,
          text: message
        }
      end

      def multiple_resources(resources)
        message = "Multiple results were found:\n"
        message << resources.map { |resource| "  #{title(resource)}" }.join("\n")

        {
          response_type: :ephemeral,
          text: message
        }
      end

      def title(resource)
        "### [#{resource.to_reference} #{resource.title}](#{url(resource)})"
      end

      def url(resource)
        helper = Rails.application.routes.url_helpers

        case resource
        when Issue
          helper.namespace_project_issue_url(resource.project.namespace.becomes(Namespace), resource.project, resource)
        when MergeRequest
          helper.namespace_project_merge_request_url(resource.project.namespace.becomes(Namespace), resource.project, resource)
        end
      end
    end
  end
end