BigW Consortium Gitlab

campfire_service.rb 2.43 KB
Newer Older
1
class CampfireService < Service
2 3
  include HTTParty

4
  prop_accessor :token, :subdomain, :room
5 6 7 8 9 10 11 12 13 14
  validates :token, presence: true, if: :activated?

  def title
    'Campfire'
  end

  def description
    'Simple web-based real-time group chat'
  end

15
  def self.to_param
16 17 18 19 20
    'campfire'
  end

  def fields
    [
21
      { type: 'text', name: 'token',     placeholder: '', required: true },
22 23 24 25 26
      { type: 'text', name: 'subdomain', placeholder: '' },
      { type: 'text', name: 'room',      placeholder: '' }
    ]
  end

27
  def self.supported_events
28 29 30
    %w(push)
  end

31
  def execute(data)
32
    return unless supported_events.include?(data[:object_kind])
33

34
    self.class.base_uri base_uri
35
    message = build_message(data)
36
    speak(self.room, message, auth)
37 38 39 40
  end

  private

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
  def base_uri
    @base_uri ||= "https://#{subdomain}.campfirenow.com"
  end

  def auth
    # use a dummy password, as explained in the Campfire API doc:
    # https://github.com/basecamp/campfire-api#authentication
    @auth ||= {
      basic_auth: {
        username: token,
        password: 'X'
      }
    }
  end

  # Post a message into a room, returns the message Hash in case of success.
  # Returns nil otherwise.
  # https://github.com/basecamp/campfire-api/blob/master/sections/messages.md#create-message
  def speak(room_name, message, auth)
    room = rooms(auth).find { |r| r["name"] == room_name }
    return nil unless room

    path = "/room/#{room["id"]}/speak.json"
    body = {
      body: {
        message: {
          type: 'TextMessage',
          body: message
        }
      }
    }
    res = self.class.post(path, auth.merge(body))
    res.code == 201 ? res : nil
  end

  # Returns a list of rooms, or [].
  # https://github.com/basecamp/campfire-api/blob/master/sections/rooms.md#get-rooms
  def rooms(auth)
79
    res = self.class.get("/rooms.json", auth)
80
    res.code == 200 ? res["rooms"] : []
81 82 83
  end

  def build_message(push)
84
    ref = Gitlab::Git.ref_name(push[:ref])
85 86 87 88 89 90 91
    before = push[:before]
    after = push[:after]

    message = ""
    message << "[#{project.name_with_namespace}] "
    message << "#{push[:user_name]} "

92
    if Gitlab::Git.blank_ref?(before)
93
      message << "pushed new branch #{ref} \n"
94
    elsif Gitlab::Git.blank_ref?(after)
95 96 97 98 99 100 101 102 103
      message << "removed branch #{ref} \n"
    else
      message << "pushed #{push[:total_commits_count]} commits to #{ref}. "
      message << "#{project.web_url}/compare/#{before}...#{after}"
    end

    message
  end
end