BigW Consortium Gitlab

web_hook.rb 1.67 KB
Newer Older
1 2 3 4
# == Schema Information
#
# Table name: web_hooks
#
5 6 7
#  id                    :integer          not null, primary key
#  url                   :string(255)
#  project_id            :integer
Dmitriy Zaporozhets committed
8 9
#  created_at            :datetime
#  updated_at            :datetime
10 11 12 13 14
#  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
Dmitriy Zaporozhets committed
15
#  tag_push_events       :boolean          default(FALSE)
16 17
#

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

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

25 26
  attr_accessible :url

27 28 29
  # HTTParty timeout
  default_timeout 10

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

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

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