notifier.rb 1.18 KB
Newer Older
1 2
# frozen_string_literal: true

3 4 5 6
module MicrosoftTeams
  class Notifier
    def initialize(webhook)
      @webhook = webhook
Tiago Botelho's avatar
Tiago Botelho committed
7
      @header = { 'Content-type' => 'application/json' }
8 9 10
    end

    def ping(options = {})
Tiago Botelho's avatar
Tiago Botelho committed
11 12 13
      result = false

      begin
14
        response = Gitlab::HTTP.post(
Tiago Botelho's avatar
Tiago Botelho committed
15 16
          @webhook.to_str,
          headers: @header,
17
          allow_local_requests: true,
Tiago Botelho's avatar
Tiago Botelho committed
18 19 20 21
          body: body(options)
        )

        result = true if response
22
      rescue Gitlab::HTTP::Error, StandardError => error
23
        Rails.logger.info("#{self.class.name}: Error while connecting to #{@webhook}: #{error.message}") # rubocop:disable Gitlab/RailsLogger
Tiago Botelho's avatar
Tiago Botelho committed
24 25 26
      end

      result
27 28 29 30 31 32 33
    end

    private

    def body(options = {})
      result = { 'sections' => [] }

34
      result['title'] = options[:title]
35
      result['summary'] = options[:summary]
Tiago Botelho's avatar
Tiago Botelho committed
36
      result['sections'] << MicrosoftTeams::Activity.new(options[:activity]).prepare
Tiago Botelho's avatar
Tiago Botelho committed
37

Tiago Botelho's avatar
Tiago Botelho committed
38 39 40 41 42 43 44
      attachments = options[:attachments]
      unless attachments.blank?
        result['sections'] << {
          'title' => 'Details',
          'facts' => [{ 'name' => 'Attachments', 'value' => attachments }]
        }
      end
45 46 47 48 49

      result.to_json
    end
  end
end