web_hook.rb 1.65 KB
Newer Older
1 2 3 4
# == Schema Information
#
# Table name: web_hooks
#
5 6 7 8 9 10 11 12 13 14
#  id                    :integer          not null, primary key
#  url                   :string(255)
#  project_id            :integer
#  created_at            :datetime         not null
#  updated_at            :datetime         not null
#  type                  :string(255)      default("ProjectHook")
#  service_id            :integer
#  push_events           :boolean          default(TRUE), not null
#  issues_events         :boolean          default(FALSE), not null
#  merge_requests_events :boolean          default(FALSE), not null
15 16
#

17 18 19
class WebHook < ActiveRecord::Base
  include HTTParty

20 21 22 23
  default_value_for :push_events, true
  default_value_for :issues_events, false
  default_value_for :merge_requests_events, false

24 25
  attr_accessible :url

26 27 28
  # HTTParty timeout
  default_timeout 10

Nihad Abbasov's avatar
Nihad Abbasov committed
29
  validates :url, presence: true,
Andrey Kumanyaev's avatar
Andrey Kumanyaev committed
30
                  format: { with: URI::regexp(%w(http https)), message: "should be a valid url" }
31 32

  def execute(data)
33 34
    parsed_url = URI.parse(url)
    if parsed_url.userinfo.blank?
35
      WebHook.post(url, body: data.to_json, headers: { "Content-Type" => "application/json" }, verify: false)
36
    else
Nihad Abbasov's avatar
Nihad Abbasov committed
37
      post_url = url.gsub("#{parsed_url.userinfo}@", "")
38 39 40 41
      auth = {
        username: URI.decode(parsed_url.user),
        password: URI.decode(parsed_url.password),
      }
42 43
      WebHook.post(post_url,
                   body: data.to_json,
Nihad Abbasov's avatar
Nihad Abbasov committed
44
                   headers: {"Content-Type" => "application/json"},
45
                   verify: false,
46
                   basic_auth: auth)
47
    end
48
  end
49 50 51 52

  def async_execute(data)
    Sidekiq::Client.enqueue(ProjectWebHookWorker, id, data)
  end
53
end